repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
smarie/python-autoclass | autoclass/autodict_.py | _execute_autodict_on_class | def _execute_autodict_on_class(object_type, # type: Type[T]
include=None, # type: Union[str, Tuple[str]]
exclude=None, # type: Union[str, Tuple[str]]
only_constructor_args=True, # type: bool
only_public_fields=True # type: bool
):
"""
This method makes objects of the class behave like a read-only `dict`. It does several things:
* it adds collections.Mapping to the list of parent classes (i.e. to the class' `__bases__`)
* it generates `__len__`, `__iter__` and `__getitem__` in order for the appropriate fields to be exposed in the dict
view.
* it adds a static from_dict method to build objects from dicts (only if only_constructor_args=True)
* it overrides eq method if not already implemented
* it overrides str and repr method if not already implemented
Parameters allow to customize the list of fields that will be visible.
:param object_type: the class on which to execute.
:param include: a tuple of explicit attribute names to include (None means all)
:param exclude: a tuple of explicit attribute names to exclude. In such case, include should be None.
:param only_constructor_args: if True (default), only constructor arguments will be exposed through the dictionary
view, not any other field that would be created in the constructor or dynamically. This makes it very convenient
to use in combination with @autoargs. If set to False, the dictionary is a direct view of public object fields.
:param only_public_fields: this parameter is only used when only_constructor_args is set to False. If
only_public_fields is set to False, all fields are visible. Otherwise (default), class-private fields will be
hidden
:return:
"""
# 0. first check parameters
validate_include_exclude(include, exclude)
# if issubclass(object_type, Mapping):
# raise ValueError('@autodict can not be set on classes that are already subclasses of Mapping, and therefore '
# 'already behave like dict')
super_is_already_a_mapping = issubclass(object_type, Mapping)
# 1. implement the abstract method required by Mapping to work, according to the options
if only_constructor_args:
# ** easy: we know the exact list of fields to make visible in the Mapping
# a. Find the __init__ constructor signature
constructor = get_constructor(object_type, allow_inheritance=True)
s = signature(constructor)
# b. Collect all attributes that are not 'self' and are included and not excluded
added = []
for attr_name in s.parameters.keys():
if is_attr_selected(attr_name, include=include, exclude=exclude):
added.append(attr_name)
# c. Finally build the methods
def __iter__(self):
"""
Generated by @autodict.
Implements the __iter__ method from collections.Iterable by relying on a hardcoded list of fields
PLUS the super dictionary if relevant
:param self:
:return:
"""
if super_is_already_a_mapping:
return iter(added + [o for o in super(object_type, self).__iter__() if o not in added])
else:
return iter(added)
# def __len__(self):
# """
# Generated by @autodict.
# Implements the __len__ method from collections.Sized by relying on a hardcoded list of fields
# PLUS the super dictionary if relevant
# :param self:
# :return:
# """
# if super_is_already_a_mapping:
# return len(added) + super(object_type, self).__len__()
# else:
# return len(added)
if super_is_already_a_mapping:
def __getitem__(self, key):
"""
Generated by @autodict.
Implements the __getitem__ method from collections.Mapping by relying on a hardcoded list of fields
PLUS the parent dictionary when not found in self
:param self:
:param key:
:return:
"""
if key in added:
try:
return getattr(self, key)
except AttributeError:
try:
return super(object_type, self).__getitem__(key)
except Exception as e:
raise KeyError('@autodict generated dict view - {key} is a constructor parameter but is not'
' a field (was the constructor called ?). Delegating to super[{key}] raises '
'an exception: {etyp} {err}'.format(key=key, etyp=type(e).__name__, err=e))
else:
try:
return super(object_type, self).__getitem__(key)
except Exception as e:
raise KeyError('@autodict generated dict view - {key} is not a constructor parameter so not '
' handled by this dict view. Delegating to super[{key}] raised an exception: '
'{etyp} {err}'.format(key=key, etyp=type(e).__name__, err=e))
else:
def __getitem__(self, key):
"""
Generated by @autodict.
Implements the __getitem__ method from collections.Mapping by relying on a hardcoded list of fields
:param self:
:param key:
:return:
"""
if key in added:
try:
return getattr(self, key)
except AttributeError:
raise KeyError('@autodict generated dict view - {} is a constructor parameter but is not a '
'field (was the constructor called ?)'.format(key))
else:
raise KeyError('@autodict generated dict view - invalid or hidden field name: %s' % key)
else:
# ** all dynamic fields are allowed
if include is None and exclude is None and not only_public_fields:
# easy: all of vars is exposed
def __iter__(self):
"""
Generated by @autodict.
Implements the __iter__ method from collections.Iterable by relying on vars(self)
PLUS the super dictionary if relevant
:param self:
:return:
"""
if super_is_already_a_mapping:
return iter(list(vars(self)) + [o for o in super(object_type, self).__iter__()
if o not in vars(self)])
else:
return iter(vars(self))
# def __len__(self):
# """
# Generated by @autodict.
# Implements the __len__ method from collections.Sized by relying on vars(self)
# PLUS the super dictionary if relevant
# :param self:
# :return:
# """
# if super_is_already_a_mapping:
# return len(list(vars(self)) + [o for o in super(object_type, self).__iter__()
# if o not in vars(self)])
# else:
# return len(vars(self))
if super_is_already_a_mapping:
def __getitem__(self, key):
"""
Generated by @autodict.
Implements the __getitem__ method from collections.Mapping by relying on getattr(self, key)
PLUS the super dictionary
:param self:
:param key:
:return:
"""
try:
return getattr(self, key)
except AttributeError:
try:
return super(object_type, self).__getitem__(key)
except Exception as e:
raise KeyError('@autodict generated dict view - {key} is not a valid field (was the '
'constructor called?). Delegating to super[{key}] raises an exception: '
'{etyp} {err}'.format(key=key, etyp=type(e).__name__, err=e))
else:
def __getitem__(self, key):
"""
Generated by @autodict.
Implements the __getitem__ method from collections.Mapping by relying on getattr(self, key)
:param self:
:param key:
:return:
"""
try:
return getattr(self, key)
except AttributeError:
raise KeyError('@autodict generated dict view - {key} is not a valid field (was the '
'constructor called?)'.format(key=key))
else:
# harder: all fields are allowed, but there are filters on this dynamic list
# private_name_prefix = '_' + object_type.__name__ + '_'
private_name_prefix = '_'
if super_is_already_a_mapping:
def __iter__(self):
"""
Generated by @autodict.
Implements the __iter__ method from collections.Iterable by relying on a filtered vars(self)
:param self:
:return:
"""
myattrs = [possibly_replace_with_property_name(self.__class__, att_name) for att_name in vars(self)]
for att_name in myattrs + [o for o in super(object_type, self).__iter__() if o not in vars(self)]:
if is_attr_selected(att_name, include=include, exclude=exclude):
if not only_public_fields \
or (only_public_fields and not att_name.startswith(private_name_prefix)):
yield att_name
else:
def __iter__(self):
"""
Generated by @autodict.
Implements the __iter__ method from collections.Iterable by relying on a filtered vars(self)
:param self:
:return:
"""
for att_name in [possibly_replace_with_property_name(self.__class__, att_name)
for att_name in vars(self)]:
if is_attr_selected(att_name, include=include, exclude=exclude):
if not only_public_fields \
or (only_public_fields and not att_name.startswith(private_name_prefix)):
yield att_name
# def __len__(self):
# """
# Generated by @autodict.
# Implements the __len__ method from collections.Sized by relying on a filtered vars(self)
# :param self:
# :return:
# """
# # rely on iter()
# return sum(1 for e in self)
if super_is_already_a_mapping:
def __getitem__(self, key):
"""
Generated by @autodict.
Implements the __getitem__ method from collections.Mapping by relying on a filtered getattr(self, key)
:param self:
:param key:
:return:
"""
if hasattr(self, key):
key = possibly_replace_with_property_name(self.__class__, key)
if is_attr_selected(key, include=include, exclude=exclude) and \
(not only_public_fields or
(only_public_fields and not key.startswith(private_name_prefix))):
return getattr(self, key)
else:
try:
return super(object_type, self).__getitem__(key)
except Exception as e:
raise KeyError('@autodict generated dict view - {key} is a '
'hidden field and super[{key}] raises an exception: {etyp} {err}'
''.format(key=key, etyp=type(e).__name__, err=e))
else:
try:
return super(object_type, self).__getitem__(key)
except Exception as e:
raise KeyError('@autodict generated dict view - {key} is an '
'invalid field name (was the constructor called?). Delegating to '
'super[{key}] raises an exception: {etyp} {err}'
''.format(key=key, etyp=type(e).__name__, err=e))
else:
def __getitem__(self, key):
"""
Generated by @autodict.
Implements the __getitem__ method from collections.Mapping by relying on a filtered getattr(self, key)
:param self:
:param key:
:return:
"""
if hasattr(self, key):
key = possibly_replace_with_property_name(self.__class__, key)
if is_attr_selected(key, include=include, exclude=exclude) and \
(not only_public_fields or
(only_public_fields and not key.startswith(private_name_prefix))):
return getattr(self, key)
else:
raise KeyError('@autodict generated dict view - hidden field name: ' + key)
else:
raise KeyError('@autodict generated dict view - {key} is an invalid field name (was the '
'constructor called? are the constructor arg names identical to the field '
'names ?)'.format(key=key))
def __len__(self):
"""
Generated by @autodict.
Implements the __len__ method from collections.Sized by relying on self.__iter__, so that the length will always
match the true length.
:param self:
:return:
"""
return sum(1 for e in self)
if method_already_there(object_type, '__len__', this_class_only=True):
if not hasattr(object_type.__len__, __AUTODICT_OVERRIDE_ANNOTATION):
warn('__len__ is already defined on class {}, it will be overridden with the one generated by '
'@autodict/@autoclass ! If you want to use your version, annotate it with @autodict_override'
''.format(str(object_type)))
object_type.__len__ = __len__
else:
object_type.__len__ = __len__
if method_already_there(object_type, '__iter__', this_class_only=True):
if not hasattr(object_type.__iter__, __AUTODICT_OVERRIDE_ANNOTATION):
warn('__iter__ is already defined on class {}, it will be overridden with the one generated by '
'@autodict/@autoclass ! If you want to use your version, annotate it with @autodict_override'
''.format(str(object_type)))
object_type.__iter__ = __iter__
else:
object_type.__iter__ = __iter__
if method_already_there(object_type, '__getitem__', this_class_only=True):
if not hasattr(object_type.__getitem__, __AUTODICT_OVERRIDE_ANNOTATION):
warn('__getitem__ is already defined on class {}, it will be overridden with the one generated by '
'@autodict/@autoclass ! If you want to use your version, annotate it with @autodict_override'
''.format(str(object_type)))
else:
object_type.__getitem__ = __getitem__
else:
object_type.__getitem__ = __getitem__
# 2. add the methods from Mapping to the class
# -- current proposition: add inheritance dynamically
type_bases = object_type.__bases__
if Mapping not in type_bases:
bazz = tuple(t for t in type_bases if t is not object)
if len(bazz) == len(type_bases):
# object was not there
new_bases = bazz + (Mapping,)
else:
# object was there, put it at the end
new_bases = bazz + (Mapping, object)
try:
object_type.__bases__ = new_bases
except TypeError:
try:
# maybe a metaclass issue, we can try this
object_type.__bases__ = with_metaclass(type(object_type), *new_bases)
except TypeError:
# python 2.x and object type is a new-style class directly inheriting from object
# open bug: https://bugs.python.org/issue672115
# -- alternate way: add methods one by one
names = [
# no need
# '__class__', '__metaclass__', '__subclasshook__', '__init__', '__ne__', '__new__'
# no need: object
# '__getattribute__','__delattr__','__setattr__','__format__','__reduce__','__reduce_ex__','__sizeof__'
# -----
# '__getitem__', overridden above
# '__iter__', overridden above
# '__len__', overridden above
# '__eq__', overridden below
# '__repr__', overridden below
# '__str__', overridden below
'__contains__',
'get',
'items',
'iteritems',
'iterkeys',
'itervalues',
'keys',
'values']
# from inspect import getmembers
# def is_useful(m):
# return m
# meths = getmembers(Mapping.get(), predicate=is_useful)
# for name, func in meths:
for name in names:
# bind method to this class too (we access 'im_func' to get the original method)
setattr(object_type, name, getattr(Mapping, name).im_func)
# 3. add the static class method to build objects from a dict
# if only_constructor_args:
# only do it if there is no existing method on the type
if not method_already_there(object_type, 'from_dict'):
def from_dict(cls,
dct # type: Dict[str, Any]
):
"""
Generated by @autodict.
A class method to construct an object from a dictionary of field values.
:param cls:
:param dct:
:return:
"""
return cls(**dct)
object_type.from_dict = classmethod(from_dict)
# 4. override equality method if not already implemented LOCALLY (on this type - we dont care about the super
# since we'll delegate to them when we can't handle)
if not method_already_there(object_type, '__eq__', this_class_only=True):
def __eq__(self, other):
"""
Generated by @autodict.
In the case the other is of the same type, use the dict comparison. Otherwise, falls back to super.
:param self:
:param other:
:return:
"""
# in the case the other is of the same type, use the dict comparison, that relies on the appropriate fields
if isinstance(other, object_type):
return dict(self) == dict(other)
else:
# else fallback to inherited behaviour, whatever it is
try:
f = super(object_type, self).__eq__
except AttributeError:
# can happen in python 2 when adding Mapping inheritance failed
return Mapping.__eq__(dict(self), other)
else:
return f(other)
object_type.__eq__ = __eq__
# 5. override str and repr method if not already implemented
if not method_already_there(object_type, '__str__', this_class_only=True):
def __str__(self):
"""
Generated by @autodict.
Uses the dict representation and puts the type in front
:param self:
:return:
"""
# python 2 compatibility: use self.__class__ not type()
return self.__class__.__name__ + '(' + print_ordered_dict(self) + ')'
object_type.__str__ = __str__
if not method_already_there(object_type, '__repr__', this_class_only=True):
def __repr__(self):
"""
Generated by @autodict.
Uses the dict representation and puts the type in front
maybe?
:param self:
:return:
"""
# python 2 compatibility: use self.__class__ not type()
return self.__class__.__name__ + '(' + print_ordered_dict(self) + ')'
object_type.__repr__ = __repr__
return | python | def _execute_autodict_on_class(object_type, # type: Type[T]
include=None, # type: Union[str, Tuple[str]]
exclude=None, # type: Union[str, Tuple[str]]
only_constructor_args=True, # type: bool
only_public_fields=True # type: bool
):
"""
This method makes objects of the class behave like a read-only `dict`. It does several things:
* it adds collections.Mapping to the list of parent classes (i.e. to the class' `__bases__`)
* it generates `__len__`, `__iter__` and `__getitem__` in order for the appropriate fields to be exposed in the dict
view.
* it adds a static from_dict method to build objects from dicts (only if only_constructor_args=True)
* it overrides eq method if not already implemented
* it overrides str and repr method if not already implemented
Parameters allow to customize the list of fields that will be visible.
:param object_type: the class on which to execute.
:param include: a tuple of explicit attribute names to include (None means all)
:param exclude: a tuple of explicit attribute names to exclude. In such case, include should be None.
:param only_constructor_args: if True (default), only constructor arguments will be exposed through the dictionary
view, not any other field that would be created in the constructor or dynamically. This makes it very convenient
to use in combination with @autoargs. If set to False, the dictionary is a direct view of public object fields.
:param only_public_fields: this parameter is only used when only_constructor_args is set to False. If
only_public_fields is set to False, all fields are visible. Otherwise (default), class-private fields will be
hidden
:return:
"""
# 0. first check parameters
validate_include_exclude(include, exclude)
# if issubclass(object_type, Mapping):
# raise ValueError('@autodict can not be set on classes that are already subclasses of Mapping, and therefore '
# 'already behave like dict')
super_is_already_a_mapping = issubclass(object_type, Mapping)
# 1. implement the abstract method required by Mapping to work, according to the options
if only_constructor_args:
# ** easy: we know the exact list of fields to make visible in the Mapping
# a. Find the __init__ constructor signature
constructor = get_constructor(object_type, allow_inheritance=True)
s = signature(constructor)
# b. Collect all attributes that are not 'self' and are included and not excluded
added = []
for attr_name in s.parameters.keys():
if is_attr_selected(attr_name, include=include, exclude=exclude):
added.append(attr_name)
# c. Finally build the methods
def __iter__(self):
"""
Generated by @autodict.
Implements the __iter__ method from collections.Iterable by relying on a hardcoded list of fields
PLUS the super dictionary if relevant
:param self:
:return:
"""
if super_is_already_a_mapping:
return iter(added + [o for o in super(object_type, self).__iter__() if o not in added])
else:
return iter(added)
# def __len__(self):
# """
# Generated by @autodict.
# Implements the __len__ method from collections.Sized by relying on a hardcoded list of fields
# PLUS the super dictionary if relevant
# :param self:
# :return:
# """
# if super_is_already_a_mapping:
# return len(added) + super(object_type, self).__len__()
# else:
# return len(added)
if super_is_already_a_mapping:
def __getitem__(self, key):
"""
Generated by @autodict.
Implements the __getitem__ method from collections.Mapping by relying on a hardcoded list of fields
PLUS the parent dictionary when not found in self
:param self:
:param key:
:return:
"""
if key in added:
try:
return getattr(self, key)
except AttributeError:
try:
return super(object_type, self).__getitem__(key)
except Exception as e:
raise KeyError('@autodict generated dict view - {key} is a constructor parameter but is not'
' a field (was the constructor called ?). Delegating to super[{key}] raises '
'an exception: {etyp} {err}'.format(key=key, etyp=type(e).__name__, err=e))
else:
try:
return super(object_type, self).__getitem__(key)
except Exception as e:
raise KeyError('@autodict generated dict view - {key} is not a constructor parameter so not '
' handled by this dict view. Delegating to super[{key}] raised an exception: '
'{etyp} {err}'.format(key=key, etyp=type(e).__name__, err=e))
else:
def __getitem__(self, key):
"""
Generated by @autodict.
Implements the __getitem__ method from collections.Mapping by relying on a hardcoded list of fields
:param self:
:param key:
:return:
"""
if key in added:
try:
return getattr(self, key)
except AttributeError:
raise KeyError('@autodict generated dict view - {} is a constructor parameter but is not a '
'field (was the constructor called ?)'.format(key))
else:
raise KeyError('@autodict generated dict view - invalid or hidden field name: %s' % key)
else:
# ** all dynamic fields are allowed
if include is None and exclude is None and not only_public_fields:
# easy: all of vars is exposed
def __iter__(self):
"""
Generated by @autodict.
Implements the __iter__ method from collections.Iterable by relying on vars(self)
PLUS the super dictionary if relevant
:param self:
:return:
"""
if super_is_already_a_mapping:
return iter(list(vars(self)) + [o for o in super(object_type, self).__iter__()
if o not in vars(self)])
else:
return iter(vars(self))
# def __len__(self):
# """
# Generated by @autodict.
# Implements the __len__ method from collections.Sized by relying on vars(self)
# PLUS the super dictionary if relevant
# :param self:
# :return:
# """
# if super_is_already_a_mapping:
# return len(list(vars(self)) + [o for o in super(object_type, self).__iter__()
# if o not in vars(self)])
# else:
# return len(vars(self))
if super_is_already_a_mapping:
def __getitem__(self, key):
"""
Generated by @autodict.
Implements the __getitem__ method from collections.Mapping by relying on getattr(self, key)
PLUS the super dictionary
:param self:
:param key:
:return:
"""
try:
return getattr(self, key)
except AttributeError:
try:
return super(object_type, self).__getitem__(key)
except Exception as e:
raise KeyError('@autodict generated dict view - {key} is not a valid field (was the '
'constructor called?). Delegating to super[{key}] raises an exception: '
'{etyp} {err}'.format(key=key, etyp=type(e).__name__, err=e))
else:
def __getitem__(self, key):
"""
Generated by @autodict.
Implements the __getitem__ method from collections.Mapping by relying on getattr(self, key)
:param self:
:param key:
:return:
"""
try:
return getattr(self, key)
except AttributeError:
raise KeyError('@autodict generated dict view - {key} is not a valid field (was the '
'constructor called?)'.format(key=key))
else:
# harder: all fields are allowed, but there are filters on this dynamic list
# private_name_prefix = '_' + object_type.__name__ + '_'
private_name_prefix = '_'
if super_is_already_a_mapping:
def __iter__(self):
"""
Generated by @autodict.
Implements the __iter__ method from collections.Iterable by relying on a filtered vars(self)
:param self:
:return:
"""
myattrs = [possibly_replace_with_property_name(self.__class__, att_name) for att_name in vars(self)]
for att_name in myattrs + [o for o in super(object_type, self).__iter__() if o not in vars(self)]:
if is_attr_selected(att_name, include=include, exclude=exclude):
if not only_public_fields \
or (only_public_fields and not att_name.startswith(private_name_prefix)):
yield att_name
else:
def __iter__(self):
"""
Generated by @autodict.
Implements the __iter__ method from collections.Iterable by relying on a filtered vars(self)
:param self:
:return:
"""
for att_name in [possibly_replace_with_property_name(self.__class__, att_name)
for att_name in vars(self)]:
if is_attr_selected(att_name, include=include, exclude=exclude):
if not only_public_fields \
or (only_public_fields and not att_name.startswith(private_name_prefix)):
yield att_name
# def __len__(self):
# """
# Generated by @autodict.
# Implements the __len__ method from collections.Sized by relying on a filtered vars(self)
# :param self:
# :return:
# """
# # rely on iter()
# return sum(1 for e in self)
if super_is_already_a_mapping:
def __getitem__(self, key):
"""
Generated by @autodict.
Implements the __getitem__ method from collections.Mapping by relying on a filtered getattr(self, key)
:param self:
:param key:
:return:
"""
if hasattr(self, key):
key = possibly_replace_with_property_name(self.__class__, key)
if is_attr_selected(key, include=include, exclude=exclude) and \
(not only_public_fields or
(only_public_fields and not key.startswith(private_name_prefix))):
return getattr(self, key)
else:
try:
return super(object_type, self).__getitem__(key)
except Exception as e:
raise KeyError('@autodict generated dict view - {key} is a '
'hidden field and super[{key}] raises an exception: {etyp} {err}'
''.format(key=key, etyp=type(e).__name__, err=e))
else:
try:
return super(object_type, self).__getitem__(key)
except Exception as e:
raise KeyError('@autodict generated dict view - {key} is an '
'invalid field name (was the constructor called?). Delegating to '
'super[{key}] raises an exception: {etyp} {err}'
''.format(key=key, etyp=type(e).__name__, err=e))
else:
def __getitem__(self, key):
"""
Generated by @autodict.
Implements the __getitem__ method from collections.Mapping by relying on a filtered getattr(self, key)
:param self:
:param key:
:return:
"""
if hasattr(self, key):
key = possibly_replace_with_property_name(self.__class__, key)
if is_attr_selected(key, include=include, exclude=exclude) and \
(not only_public_fields or
(only_public_fields and not key.startswith(private_name_prefix))):
return getattr(self, key)
else:
raise KeyError('@autodict generated dict view - hidden field name: ' + key)
else:
raise KeyError('@autodict generated dict view - {key} is an invalid field name (was the '
'constructor called? are the constructor arg names identical to the field '
'names ?)'.format(key=key))
def __len__(self):
"""
Generated by @autodict.
Implements the __len__ method from collections.Sized by relying on self.__iter__, so that the length will always
match the true length.
:param self:
:return:
"""
return sum(1 for e in self)
if method_already_there(object_type, '__len__', this_class_only=True):
if not hasattr(object_type.__len__, __AUTODICT_OVERRIDE_ANNOTATION):
warn('__len__ is already defined on class {}, it will be overridden with the one generated by '
'@autodict/@autoclass ! If you want to use your version, annotate it with @autodict_override'
''.format(str(object_type)))
object_type.__len__ = __len__
else:
object_type.__len__ = __len__
if method_already_there(object_type, '__iter__', this_class_only=True):
if not hasattr(object_type.__iter__, __AUTODICT_OVERRIDE_ANNOTATION):
warn('__iter__ is already defined on class {}, it will be overridden with the one generated by '
'@autodict/@autoclass ! If you want to use your version, annotate it with @autodict_override'
''.format(str(object_type)))
object_type.__iter__ = __iter__
else:
object_type.__iter__ = __iter__
if method_already_there(object_type, '__getitem__', this_class_only=True):
if not hasattr(object_type.__getitem__, __AUTODICT_OVERRIDE_ANNOTATION):
warn('__getitem__ is already defined on class {}, it will be overridden with the one generated by '
'@autodict/@autoclass ! If you want to use your version, annotate it with @autodict_override'
''.format(str(object_type)))
else:
object_type.__getitem__ = __getitem__
else:
object_type.__getitem__ = __getitem__
# 2. add the methods from Mapping to the class
# -- current proposition: add inheritance dynamically
type_bases = object_type.__bases__
if Mapping not in type_bases:
bazz = tuple(t for t in type_bases if t is not object)
if len(bazz) == len(type_bases):
# object was not there
new_bases = bazz + (Mapping,)
else:
# object was there, put it at the end
new_bases = bazz + (Mapping, object)
try:
object_type.__bases__ = new_bases
except TypeError:
try:
# maybe a metaclass issue, we can try this
object_type.__bases__ = with_metaclass(type(object_type), *new_bases)
except TypeError:
# python 2.x and object type is a new-style class directly inheriting from object
# open bug: https://bugs.python.org/issue672115
# -- alternate way: add methods one by one
names = [
# no need
# '__class__', '__metaclass__', '__subclasshook__', '__init__', '__ne__', '__new__'
# no need: object
# '__getattribute__','__delattr__','__setattr__','__format__','__reduce__','__reduce_ex__','__sizeof__'
# -----
# '__getitem__', overridden above
# '__iter__', overridden above
# '__len__', overridden above
# '__eq__', overridden below
# '__repr__', overridden below
# '__str__', overridden below
'__contains__',
'get',
'items',
'iteritems',
'iterkeys',
'itervalues',
'keys',
'values']
# from inspect import getmembers
# def is_useful(m):
# return m
# meths = getmembers(Mapping.get(), predicate=is_useful)
# for name, func in meths:
for name in names:
# bind method to this class too (we access 'im_func' to get the original method)
setattr(object_type, name, getattr(Mapping, name).im_func)
# 3. add the static class method to build objects from a dict
# if only_constructor_args:
# only do it if there is no existing method on the type
if not method_already_there(object_type, 'from_dict'):
def from_dict(cls,
dct # type: Dict[str, Any]
):
"""
Generated by @autodict.
A class method to construct an object from a dictionary of field values.
:param cls:
:param dct:
:return:
"""
return cls(**dct)
object_type.from_dict = classmethod(from_dict)
# 4. override equality method if not already implemented LOCALLY (on this type - we dont care about the super
# since we'll delegate to them when we can't handle)
if not method_already_there(object_type, '__eq__', this_class_only=True):
def __eq__(self, other):
"""
Generated by @autodict.
In the case the other is of the same type, use the dict comparison. Otherwise, falls back to super.
:param self:
:param other:
:return:
"""
# in the case the other is of the same type, use the dict comparison, that relies on the appropriate fields
if isinstance(other, object_type):
return dict(self) == dict(other)
else:
# else fallback to inherited behaviour, whatever it is
try:
f = super(object_type, self).__eq__
except AttributeError:
# can happen in python 2 when adding Mapping inheritance failed
return Mapping.__eq__(dict(self), other)
else:
return f(other)
object_type.__eq__ = __eq__
# 5. override str and repr method if not already implemented
if not method_already_there(object_type, '__str__', this_class_only=True):
def __str__(self):
"""
Generated by @autodict.
Uses the dict representation and puts the type in front
:param self:
:return:
"""
# python 2 compatibility: use self.__class__ not type()
return self.__class__.__name__ + '(' + print_ordered_dict(self) + ')'
object_type.__str__ = __str__
if not method_already_there(object_type, '__repr__', this_class_only=True):
def __repr__(self):
"""
Generated by @autodict.
Uses the dict representation and puts the type in front
maybe?
:param self:
:return:
"""
# python 2 compatibility: use self.__class__ not type()
return self.__class__.__name__ + '(' + print_ordered_dict(self) + ')'
object_type.__repr__ = __repr__
return | This method makes objects of the class behave like a read-only `dict`. It does several things:
* it adds collections.Mapping to the list of parent classes (i.e. to the class' `__bases__`)
* it generates `__len__`, `__iter__` and `__getitem__` in order for the appropriate fields to be exposed in the dict
view.
* it adds a static from_dict method to build objects from dicts (only if only_constructor_args=True)
* it overrides eq method if not already implemented
* it overrides str and repr method if not already implemented
Parameters allow to customize the list of fields that will be visible.
:param object_type: the class on which to execute.
:param include: a tuple of explicit attribute names to include (None means all)
:param exclude: a tuple of explicit attribute names to exclude. In such case, include should be None.
:param only_constructor_args: if True (default), only constructor arguments will be exposed through the dictionary
view, not any other field that would be created in the constructor or dynamically. This makes it very convenient
to use in combination with @autoargs. If set to False, the dictionary is a direct view of public object fields.
:param only_public_fields: this parameter is only used when only_constructor_args is set to False. If
only_public_fields is set to False, all fields are visible. Otherwise (default), class-private fields will be
hidden
:return: | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/autodict_.py#L97-L549 |
smarie/python-autoclass | autoclass/autodict_.py | autodict_override_decorate | def autodict_override_decorate(func # type: Callable
):
# type: (...) -> Callable
"""
Used to decorate a function as an overridden dictionary method (such as __iter__), without using the
@autodict_override annotation.
:param func: the function on which to execute. Note that it won't be wrapped but simply annotated.
:return:
"""
if func.__name__ not in {Mapping.__iter__.__name__, Mapping.__getitem__.__name__, Mapping.__len__.__name__}:
raise ValueError('@autodict_override can only be used on one of the three Mapping methods __iter__,'
'__getitem__ and __len__. Found: ' + func.__name__)
# Simply annotate the function
if hasattr(func, __AUTODICT_OVERRIDE_ANNOTATION):
raise DuplicateOverrideError('Function is overridden twice : ' + func.__name__)
else:
setattr(func, __AUTODICT_OVERRIDE_ANNOTATION, True)
return func | python | def autodict_override_decorate(func # type: Callable
):
# type: (...) -> Callable
"""
Used to decorate a function as an overridden dictionary method (such as __iter__), without using the
@autodict_override annotation.
:param func: the function on which to execute. Note that it won't be wrapped but simply annotated.
:return:
"""
if func.__name__ not in {Mapping.__iter__.__name__, Mapping.__getitem__.__name__, Mapping.__len__.__name__}:
raise ValueError('@autodict_override can only be used on one of the three Mapping methods __iter__,'
'__getitem__ and __len__. Found: ' + func.__name__)
# Simply annotate the function
if hasattr(func, __AUTODICT_OVERRIDE_ANNOTATION):
raise DuplicateOverrideError('Function is overridden twice : ' + func.__name__)
else:
setattr(func, __AUTODICT_OVERRIDE_ANNOTATION, True)
return func | Used to decorate a function as an overridden dictionary method (such as __iter__), without using the
@autodict_override annotation.
:param func: the function on which to execute. Note that it won't be wrapped but simply annotated.
:return: | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/autodict_.py#L560-L581 |
alexflint/process-isolation | process_isolation.py | map_values | def map_values(f, D):
'''Map each value in the dictionary D to f(value).'''
return { key:f(val) for key,val in D.iteritems() } | python | def map_values(f, D):
'''Map each value in the dictionary D to f(value).'''
return { key:f(val) for key,val in D.iteritems() } | Map each value in the dictionary D to f(value). | https://github.com/alexflint/process-isolation/blob/1b09862a5ed63be71049dfa8ad22f7c5fc75745c/process_isolation.py#L62-L64 |
alexflint/process-isolation | process_isolation.py | raw_repr | def raw_repr(obj):
'''Produce a representation using the default repr() regardless of
whether the object provides an implementation of its own.'''
if isproxy(obj):
return '<%s with prime_id=%d>' % (obj.__class__.__name__, obj.prime_id)
else:
return repr(obj) | python | def raw_repr(obj):
'''Produce a representation using the default repr() regardless of
whether the object provides an implementation of its own.'''
if isproxy(obj):
return '<%s with prime_id=%d>' % (obj.__class__.__name__, obj.prime_id)
else:
return repr(obj) | Produce a representation using the default repr() regardless of
whether the object provides an implementation of its own. | https://github.com/alexflint/process-isolation/blob/1b09862a5ed63be71049dfa8ad22f7c5fc75745c/process_isolation.py#L72-L78 |
alexflint/process-isolation | process_isolation.py | _load_module | def _load_module(module_name, path):
'''A helper function invoked on the server to tell it to import a module.'''
# TODO: handle the case that the module is already loaded
try:
# First try to find a non-builtin, non-frozen, non-special
# module using the client's search path
fd, filename, info = imp.find_module(module_name, path)
except ImportError:
# The above will fail for builtin, frozen, or special
# modules. We search for those now...
fd, filename, info = imp.find_module(module_name)
# Now import the module given the info found above
try:
return imp.load_module(module_name, fd, filename, info)
finally:
if fd is not None:
fd.close() | python | def _load_module(module_name, path):
'''A helper function invoked on the server to tell it to import a module.'''
# TODO: handle the case that the module is already loaded
try:
# First try to find a non-builtin, non-frozen, non-special
# module using the client's search path
fd, filename, info = imp.find_module(module_name, path)
except ImportError:
# The above will fail for builtin, frozen, or special
# modules. We search for those now...
fd, filename, info = imp.find_module(module_name)
# Now import the module given the info found above
try:
return imp.load_module(module_name, fd, filename, info)
finally:
if fd is not None:
fd.close() | A helper function invoked on the server to tell it to import a module. | https://github.com/alexflint/process-isolation/blob/1b09862a5ed63be71049dfa8ad22f7c5fc75745c/process_isolation.py#L84-L101 |
alexflint/process-isolation | process_isolation.py | byvalue | def byvalue(proxy):
'''Return a copy of the underlying object for which the argument
is a proxy.'''
assert isinstance(proxy, Proxy)
return proxy.client.execute(ByValueDelegate(proxy)) | python | def byvalue(proxy):
'''Return a copy of the underlying object for which the argument
is a proxy.'''
assert isinstance(proxy, Proxy)
return proxy.client.execute(ByValueDelegate(proxy)) | Return a copy of the underlying object for which the argument
is a proxy. | https://github.com/alexflint/process-isolation/blob/1b09862a5ed63be71049dfa8ad22f7c5fc75745c/process_isolation.py#L103-L107 |
alexflint/process-isolation | process_isolation.py | import_isolated | def import_isolated(module_name, fromlist=[], level=-1, path=None):
'''Import an module into an isolated context as if with
"__import__('module_name')"'''
sys.modules[module_name] = load_module(module_name, path=path)
return __import__(module_name, fromlist=fromlist, level=level) | python | def import_isolated(module_name, fromlist=[], level=-1, path=None):
'''Import an module into an isolated context as if with
"__import__('module_name')"'''
sys.modules[module_name] = load_module(module_name, path=path)
return __import__(module_name, fromlist=fromlist, level=level) | Import an module into an isolated context as if with
"__import__('module_name')" | https://github.com/alexflint/process-isolation/blob/1b09862a5ed63be71049dfa8ad22f7c5fc75745c/process_isolation.py#L945-L949 |
alexflint/process-isolation | process_isolation.py | Client.state | def state(self, state):
'''Change the state of the client. This is one of the values
defined in ClientStates.'''
logger.debug('client changing to state=%s', ClientState.Names[state])
self._state = state | python | def state(self, state):
'''Change the state of the client. This is one of the values
defined in ClientStates.'''
logger.debug('client changing to state=%s', ClientState.Names[state])
self._state = state | Change the state of the client. This is one of the values
defined in ClientStates. | https://github.com/alexflint/process-isolation/blob/1b09862a5ed63be71049dfa8ad22f7c5fc75745c/process_isolation.py#L607-L611 |
alexflint/process-isolation | process_isolation.py | Client._read_result | def _read_result(self, num_retries):
'''Read an object from a channel, possibly retrying if the attempt
is interrupted by a signal from the operating system.'''
for i in range(num_retries):
self._assert_alive()
try:
return self._result_channel.get()
except IOError as ex:
if ex.errno == 4:
# errno=4 corresponds to "System call interrupted",
# which means a signal was recieved before any data
# was sent. For now I think it's safe to ignore this
# and continue.
logger.exception('attempt to read from channel was interrupted by something')
sys.exc_clear()
else:
# Something else went wrong - raise the exception as usual
raise ex
raise ChannelError('failed to read from channel after %d retries' % num_retries) | python | def _read_result(self, num_retries):
'''Read an object from a channel, possibly retrying if the attempt
is interrupted by a signal from the operating system.'''
for i in range(num_retries):
self._assert_alive()
try:
return self._result_channel.get()
except IOError as ex:
if ex.errno == 4:
# errno=4 corresponds to "System call interrupted",
# which means a signal was recieved before any data
# was sent. For now I think it's safe to ignore this
# and continue.
logger.exception('attempt to read from channel was interrupted by something')
sys.exc_clear()
else:
# Something else went wrong - raise the exception as usual
raise ex
raise ChannelError('failed to read from channel after %d retries' % num_retries) | Read an object from a channel, possibly retrying if the attempt
is interrupted by a signal from the operating system. | https://github.com/alexflint/process-isolation/blob/1b09862a5ed63be71049dfa8ad22f7c5fc75745c/process_isolation.py#L697-L716 |
alexflint/process-isolation | process_isolation.py | Client.terminate | def terminate(self):
'''Stop the server process and change our state to TERMINATING. Only valid if state=READY.'''
logger.debug('client.terminate() called (state=%s)', self.strstate)
if self.state == ClientState.WAITING_FOR_RESULT:
raise ClientStateError('terimate() called while state='+self.strstate)
if self.state == ClientState.TERMINATING:
raise ClientStateError('terimate() called while state='+self.strstate)
elif self.state in ClientState.TerminatedSet:
assert not self._server_process.is_alive()
return
elif self.state == ClientState.READY:
# Check that the process itself is still alive
self._assert_alive()
# Make sure the SIGCHLD signal handler doesn't throw any exceptions
self.state = ClientState.TERMINATING
# Do not call execute() because that function will check
# whether the process is alive and throw an exception if not
# TODO: can the queue itself throw exceptions?
self._delegate_channel.put(FunctionCallDelegate(_raise_terminate))
# Wait for acknowledgement
try:
self._read_result(num_retries=5)
except ProcessTerminationError as ex:
pass
except ChannelError as ex:
# Was interrupted five times in a row! Ignore for now
logger.debug('client failed to read sentinel from channel after 5 retries - will terminate anyway')
self.state = ClientState.TERMINATED_CLEANLY | python | def terminate(self):
'''Stop the server process and change our state to TERMINATING. Only valid if state=READY.'''
logger.debug('client.terminate() called (state=%s)', self.strstate)
if self.state == ClientState.WAITING_FOR_RESULT:
raise ClientStateError('terimate() called while state='+self.strstate)
if self.state == ClientState.TERMINATING:
raise ClientStateError('terimate() called while state='+self.strstate)
elif self.state in ClientState.TerminatedSet:
assert not self._server_process.is_alive()
return
elif self.state == ClientState.READY:
# Check that the process itself is still alive
self._assert_alive()
# Make sure the SIGCHLD signal handler doesn't throw any exceptions
self.state = ClientState.TERMINATING
# Do not call execute() because that function will check
# whether the process is alive and throw an exception if not
# TODO: can the queue itself throw exceptions?
self._delegate_channel.put(FunctionCallDelegate(_raise_terminate))
# Wait for acknowledgement
try:
self._read_result(num_retries=5)
except ProcessTerminationError as ex:
pass
except ChannelError as ex:
# Was interrupted five times in a row! Ignore for now
logger.debug('client failed to read sentinel from channel after 5 retries - will terminate anyway')
self.state = ClientState.TERMINATED_CLEANLY | Stop the server process and change our state to TERMINATING. Only valid if state=READY. | https://github.com/alexflint/process-isolation/blob/1b09862a5ed63be71049dfa8ad22f7c5fc75745c/process_isolation.py#L808-L839 |
alexflint/process-isolation | process_isolation.py | Client.cleanup | def cleanup(self):
'''Terminate this client if it has not already terminated.'''
if self.state == ClientState.WAITING_FOR_RESULT:
# There is an ongoing call to execute()
# Not sure what to do here
logger.warn('cleanup() called while state is WAITING_FOR_RESULT: ignoring')
elif self.state == ClientState.TERMINATING:
# terminate() has been called but we have not recieved SIGCHLD yet
# Not sure what to do here
logger.warn('cleanup() called while state is TERMINATING: ignoring')
elif self.state in ClientState.TerminatedSet:
# We have already terminated
# TODO: should we deal with TERMINATED_ASYNC in some special way?
logger.debug('cleanup() called while state is TERMINATING: nothing needs to be done')
else:
logger.debug('cleanup() called while state is %s: attempting to terminate',
self.strstate)
try:
self.terminate()
except ProcessTerminationError as ex:
# Terminate can throw a ProcessTerminationError if the
# process terminated at some point between the last
# execute() and the call to terminate()
# For now we just ignore this.
pass | python | def cleanup(self):
'''Terminate this client if it has not already terminated.'''
if self.state == ClientState.WAITING_FOR_RESULT:
# There is an ongoing call to execute()
# Not sure what to do here
logger.warn('cleanup() called while state is WAITING_FOR_RESULT: ignoring')
elif self.state == ClientState.TERMINATING:
# terminate() has been called but we have not recieved SIGCHLD yet
# Not sure what to do here
logger.warn('cleanup() called while state is TERMINATING: ignoring')
elif self.state in ClientState.TerminatedSet:
# We have already terminated
# TODO: should we deal with TERMINATED_ASYNC in some special way?
logger.debug('cleanup() called while state is TERMINATING: nothing needs to be done')
else:
logger.debug('cleanup() called while state is %s: attempting to terminate',
self.strstate)
try:
self.terminate()
except ProcessTerminationError as ex:
# Terminate can throw a ProcessTerminationError if the
# process terminated at some point between the last
# execute() and the call to terminate()
# For now we just ignore this.
pass | Terminate this client if it has not already terminated. | https://github.com/alexflint/process-isolation/blob/1b09862a5ed63be71049dfa8ad22f7c5fc75745c/process_isolation.py#L841-L865 |
alexflint/process-isolation | process_isolation.py | IsolationContext.start | def start(self):
'''Create a process in which the isolated code will be run.'''
assert self._client is None
logger.debug('IsolationContext[%d] starting', id(self))
# Create the queues
request_queue = multiprocessing.Queue()
response_queue = multiprocessing.Queue()
# Launch the server process
server = Server(request_queue, response_queue) # Do not keep a reference to this object!
server_process = multiprocessing.Process(target=server.loop)
server_process.start()
# Create a client to talk to the server
self._client = Client(server_process, request_queue, response_queue) | python | def start(self):
'''Create a process in which the isolated code will be run.'''
assert self._client is None
logger.debug('IsolationContext[%d] starting', id(self))
# Create the queues
request_queue = multiprocessing.Queue()
response_queue = multiprocessing.Queue()
# Launch the server process
server = Server(request_queue, response_queue) # Do not keep a reference to this object!
server_process = multiprocessing.Process(target=server.loop)
server_process.start()
# Create a client to talk to the server
self._client = Client(server_process, request_queue, response_queue) | Create a process in which the isolated code will be run. | https://github.com/alexflint/process-isolation/blob/1b09862a5ed63be71049dfa8ad22f7c5fc75745c/process_isolation.py#L898-L914 |
alexflint/process-isolation | process_isolation.py | IsolationContext.load_module | def load_module(self, module_name, path=None):
'''Import a module into this isolation context and return a proxy for it.'''
self.ensure_started()
if path is None:
path = sys.path
mod = self.client.call(_load_module, module_name, path)
mod.__isolation_context__ = self
return mod | python | def load_module(self, module_name, path=None):
'''Import a module into this isolation context and return a proxy for it.'''
self.ensure_started()
if path is None:
path = sys.path
mod = self.client.call(_load_module, module_name, path)
mod.__isolation_context__ = self
return mod | Import a module into this isolation context and return a proxy for it. | https://github.com/alexflint/process-isolation/blob/1b09862a5ed63be71049dfa8ad22f7c5fc75745c/process_isolation.py#L921-L928 |
smarie/python-autoclass | ci_tools/generate-junit-badge.py | download_badge | def download_badge(test_stats, # type: TestStats
dest_folder='reports/junit' # type: str
):
"""
Downloads the badge corresponding to the provided success percentage, from https://img.shields.io.
:param test_stats:
:param dest_folder:
:return:
"""
if not path.exists(dest_folder):
makedirs(dest_folder) # , exist_ok=True) not python 2 compliant
if test_stats.success_percentage < 50:
color = 'red'
elif test_stats.success_percentage < 75:
color = 'orange'
elif test_stats.success_percentage < 90:
color = 'green'
else:
color = 'brightgreen'
left_txt = "tests"
# right_txt = "%s%%" % test_stats.success_percentage
right_txt = "%s/%s" % (test_stats.success, test_stats.runned)
url = 'https://img.shields.io/badge/%s-%s-%s.svg' % (left_txt, quote_plus(right_txt), color)
dest_file = path.join(dest_folder, 'junit-badge.svg')
print('Generating junit badge from : ' + url)
response = requests.get(url, stream=True)
with open(dest_file, 'wb') as out_file:
response.raw.decode_content = True
shutil.copyfileobj(response.raw, out_file)
del response | python | def download_badge(test_stats, # type: TestStats
dest_folder='reports/junit' # type: str
):
"""
Downloads the badge corresponding to the provided success percentage, from https://img.shields.io.
:param test_stats:
:param dest_folder:
:return:
"""
if not path.exists(dest_folder):
makedirs(dest_folder) # , exist_ok=True) not python 2 compliant
if test_stats.success_percentage < 50:
color = 'red'
elif test_stats.success_percentage < 75:
color = 'orange'
elif test_stats.success_percentage < 90:
color = 'green'
else:
color = 'brightgreen'
left_txt = "tests"
# right_txt = "%s%%" % test_stats.success_percentage
right_txt = "%s/%s" % (test_stats.success, test_stats.runned)
url = 'https://img.shields.io/badge/%s-%s-%s.svg' % (left_txt, quote_plus(right_txt), color)
dest_file = path.join(dest_folder, 'junit-badge.svg')
print('Generating junit badge from : ' + url)
response = requests.get(url, stream=True)
with open(dest_file, 'wb') as out_file:
response.raw.decode_content = True
shutil.copyfileobj(response.raw, out_file)
del response | Downloads the badge corresponding to the provided success percentage, from https://img.shields.io.
:param test_stats:
:param dest_folder:
:return: | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/ci_tools/generate-junit-badge.py#L42-L76 |
smarie/python-autoclass | autoclass/autoprops_.py | autoprops | def autoprops(include=None, # type: Union[str, Tuple[str]]
exclude=None, # type: Union[str, Tuple[str]]
cls=DECORATED):
"""
A decorator to automatically generate all properties getters and setters from the class constructor.
* if a @contract annotation exist on the __init__ method, mentioning a contract for a given parameter, the
parameter contract will be added on the generated setter method
* The user may override the generated getter and/or setter by creating them explicitly in the class and annotating
them with @getter_override or @setter_override. Note that the contract will still be dynamically added on the
setter, even if the setter already has one (in such case a `UserWarning` will be issued)
:param include: a tuple of explicit attribute names to include (None means all)
:param exclude: a tuple of explicit attribute names to exclude. In such case, include should be None.
:return:
"""
return autoprops_decorate(cls, include=include, exclude=exclude) | python | def autoprops(include=None, # type: Union[str, Tuple[str]]
exclude=None, # type: Union[str, Tuple[str]]
cls=DECORATED):
"""
A decorator to automatically generate all properties getters and setters from the class constructor.
* if a @contract annotation exist on the __init__ method, mentioning a contract for a given parameter, the
parameter contract will be added on the generated setter method
* The user may override the generated getter and/or setter by creating them explicitly in the class and annotating
them with @getter_override or @setter_override. Note that the contract will still be dynamically added on the
setter, even if the setter already has one (in such case a `UserWarning` will be issued)
:param include: a tuple of explicit attribute names to include (None means all)
:param exclude: a tuple of explicit attribute names to exclude. In such case, include should be None.
:return:
"""
return autoprops_decorate(cls, include=include, exclude=exclude) | A decorator to automatically generate all properties getters and setters from the class constructor.
* if a @contract annotation exist on the __init__ method, mentioning a contract for a given parameter, the
parameter contract will be added on the generated setter method
* The user may override the generated getter and/or setter by creating them explicitly in the class and annotating
them with @getter_override or @setter_override. Note that the contract will still be dynamically added on the
setter, even if the setter already has one (in such case a `UserWarning` will be issued)
:param include: a tuple of explicit attribute names to include (None means all)
:param exclude: a tuple of explicit attribute names to exclude. In such case, include should be None.
:return: | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/autoprops_.py#L46-L61 |
smarie/python-autoclass | autoclass/autoprops_.py | autoprops_decorate | def autoprops_decorate(cls, # type: Type[T]
include=None, # type: Union[str, Tuple[str]]
exclude=None # type: Union[str, Tuple[str]]
):
# type: (...) -> Type[T]
"""
To automatically generate all properties getters and setters from the class constructor manually, without using
@autoprops decorator.
* if a @contract annotation exist on the __init__ method, mentioning a contract for a given parameter, the
parameter contract will be added on the generated setter method
* The user may override the generated getter and/or setter by creating them explicitly in the class and annotating
them with @getter_override or @setter_override. Note that the contract will still be dynamically added on the
setter, even if the setter already has one (in such case a `UserWarning` will be issued)
:param cls: the class on which to execute. Note that it won't be wrapped.
:param include: a tuple of explicit attribute names to include (None means all)
:param exclude: a tuple of explicit attribute names to exclude. In such case, include should be None.
:return:
"""
# first check that we do not conflict with other known decorators
_check_known_decorators(cls, '@autoprops')
# perform the class mod
_execute_autoprops_on_class(cls, include=include, exclude=exclude)
# TODO better create a wrapper than modify the class? Probably not
# class Autoprops_Wrapper(object):
# def __init__(self, *args, **kwargs):
# self.wrapped = cls(*args, **kwargs)
#
# return Autoprops_Wrapper
return cls | python | def autoprops_decorate(cls, # type: Type[T]
include=None, # type: Union[str, Tuple[str]]
exclude=None # type: Union[str, Tuple[str]]
):
# type: (...) -> Type[T]
"""
To automatically generate all properties getters and setters from the class constructor manually, without using
@autoprops decorator.
* if a @contract annotation exist on the __init__ method, mentioning a contract for a given parameter, the
parameter contract will be added on the generated setter method
* The user may override the generated getter and/or setter by creating them explicitly in the class and annotating
them with @getter_override or @setter_override. Note that the contract will still be dynamically added on the
setter, even if the setter already has one (in such case a `UserWarning` will be issued)
:param cls: the class on which to execute. Note that it won't be wrapped.
:param include: a tuple of explicit attribute names to include (None means all)
:param exclude: a tuple of explicit attribute names to exclude. In such case, include should be None.
:return:
"""
# first check that we do not conflict with other known decorators
_check_known_decorators(cls, '@autoprops')
# perform the class mod
_execute_autoprops_on_class(cls, include=include, exclude=exclude)
# TODO better create a wrapper than modify the class? Probably not
# class Autoprops_Wrapper(object):
# def __init__(self, *args, **kwargs):
# self.wrapped = cls(*args, **kwargs)
#
# return Autoprops_Wrapper
return cls | To automatically generate all properties getters and setters from the class constructor manually, without using
@autoprops decorator.
* if a @contract annotation exist on the __init__ method, mentioning a contract for a given parameter, the
parameter contract will be added on the generated setter method
* The user may override the generated getter and/or setter by creating them explicitly in the class and annotating
them with @getter_override or @setter_override. Note that the contract will still be dynamically added on the
setter, even if the setter already has one (in such case a `UserWarning` will be issued)
:param cls: the class on which to execute. Note that it won't be wrapped.
:param include: a tuple of explicit attribute names to include (None means all)
:param exclude: a tuple of explicit attribute names to exclude. In such case, include should be None.
:return: | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/autoprops_.py#L64-L97 |
smarie/python-autoclass | autoclass/autoprops_.py | _execute_autoprops_on_class | def _execute_autoprops_on_class(object_type, # type: Type[T]
include=None, # type: Union[str, Tuple[str]]
exclude=None # type: Union[str, Tuple[str]]
):
"""
This method will automatically add one getter and one setter for each constructor argument, except for those
overridden using autoprops_override_decorate(), @getter_override or @setter_override.
It will add a @contract on top of all setters (generated or overridden, if they don't already have one)
:param object_type: the class on which to execute.
:param include: a tuple of explicit attribute names to include (None means all)
:param exclude: a tuple of explicit attribute names to exclude. In such case, include should be None.
:return:
"""
# 0. first check parameters
validate_include_exclude(include, exclude)
# 1. Find the __init__ constructor signature and possible pycontracts @contract
constructor = get_constructor(object_type, allow_inheritance=True)
s = signature(constructor)
# option a) pycontracts
contracts_dict = constructor.__contracts__ if hasattr(constructor, '__contracts__') else {}
# option b) valid8
validators_dict = constructor.__validators__ if hasattr(constructor, '__validators__') else {}
# 2. For each attribute that is not 'self' and is included and not excluded, add the property
added = []
for attr_name in s.parameters.keys():
if is_attr_selected(attr_name, include=include, exclude=exclude):
added.append(attr_name)
# pycontract
if attr_name in contracts_dict.keys():
pycontract = contracts_dict[attr_name]
else:
pycontract = None
# valid8 validators: create copies, because we will modify them (changing the validated function ref)
if attr_name in validators_dict.keys():
validators = [copy(v) for v in validators_dict[attr_name]]
else:
validators = None
_add_property(object_type, s.parameters[attr_name], pycontract=pycontract, validators=validators)
# 3. Finally check that there is no overridden setter or getter that does not correspond to an attribute
extra_overrides = getmembers(object_type, predicate=(lambda fun: callable(fun) and
(hasattr(fun, __GETTER_OVERRIDE_ANNOTATION)
and getattr(fun, __GETTER_OVERRIDE_ANNOTATION) not in added)
or
(hasattr(fun, __SETTER_OVERRIDE_ANNOTATION))
and getattr(fun, __SETTER_OVERRIDE_ANNOTATION) not in added)
)
if len(extra_overrides) > 0:
raise AttributeError('Attribute named \'' + extra_overrides[0][0] + '\' was not found in constructor signature.'
'Therefore its getter/setter can not be overridden by function '
+ extra_overrides[0][1].__qualname__) | python | def _execute_autoprops_on_class(object_type, # type: Type[T]
include=None, # type: Union[str, Tuple[str]]
exclude=None # type: Union[str, Tuple[str]]
):
"""
This method will automatically add one getter and one setter for each constructor argument, except for those
overridden using autoprops_override_decorate(), @getter_override or @setter_override.
It will add a @contract on top of all setters (generated or overridden, if they don't already have one)
:param object_type: the class on which to execute.
:param include: a tuple of explicit attribute names to include (None means all)
:param exclude: a tuple of explicit attribute names to exclude. In such case, include should be None.
:return:
"""
# 0. first check parameters
validate_include_exclude(include, exclude)
# 1. Find the __init__ constructor signature and possible pycontracts @contract
constructor = get_constructor(object_type, allow_inheritance=True)
s = signature(constructor)
# option a) pycontracts
contracts_dict = constructor.__contracts__ if hasattr(constructor, '__contracts__') else {}
# option b) valid8
validators_dict = constructor.__validators__ if hasattr(constructor, '__validators__') else {}
# 2. For each attribute that is not 'self' and is included and not excluded, add the property
added = []
for attr_name in s.parameters.keys():
if is_attr_selected(attr_name, include=include, exclude=exclude):
added.append(attr_name)
# pycontract
if attr_name in contracts_dict.keys():
pycontract = contracts_dict[attr_name]
else:
pycontract = None
# valid8 validators: create copies, because we will modify them (changing the validated function ref)
if attr_name in validators_dict.keys():
validators = [copy(v) for v in validators_dict[attr_name]]
else:
validators = None
_add_property(object_type, s.parameters[attr_name], pycontract=pycontract, validators=validators)
# 3. Finally check that there is no overridden setter or getter that does not correspond to an attribute
extra_overrides = getmembers(object_type, predicate=(lambda fun: callable(fun) and
(hasattr(fun, __GETTER_OVERRIDE_ANNOTATION)
and getattr(fun, __GETTER_OVERRIDE_ANNOTATION) not in added)
or
(hasattr(fun, __SETTER_OVERRIDE_ANNOTATION))
and getattr(fun, __SETTER_OVERRIDE_ANNOTATION) not in added)
)
if len(extra_overrides) > 0:
raise AttributeError('Attribute named \'' + extra_overrides[0][0] + '\' was not found in constructor signature.'
'Therefore its getter/setter can not be overridden by function '
+ extra_overrides[0][1].__qualname__) | This method will automatically add one getter and one setter for each constructor argument, except for those
overridden using autoprops_override_decorate(), @getter_override or @setter_override.
It will add a @contract on top of all setters (generated or overridden, if they don't already have one)
:param object_type: the class on which to execute.
:param include: a tuple of explicit attribute names to include (None means all)
:param exclude: a tuple of explicit attribute names to exclude. In such case, include should be None.
:return: | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/autoprops_.py#L100-L157 |
smarie/python-autoclass | autoclass/autoprops_.py | _add_property | def _add_property(object_type, # type: Type[T]
parameter, # type: Parameter
pycontract=None, # type: Any
validators=None # type: Any
):
"""
A method to dynamically add a property to a class with the optional given pycontract or validators.
If the property getter and/or setter have been overridden, it is taken into account too.
:param object_type: the class on which to execute.
:param parameter:
:param pycontract:
:param validators:
:return:
"""
property_name = parameter.name
# 1. create the private field name , e.g. '_foobar'
private_property_name = '_' + property_name
# 2. property getter (@property) - create or use overridden
getter_fun = _get_getter_fun(object_type, parameter, private_property_name)
# 3. property setter (@property_name.setter) - create or use overridden
setter_fun, var_name = _get_setter_fun(object_type, parameter, private_property_name)
# 4. add the contract to the setter, if any
setter_fun_with_possible_contract = setter_fun
if pycontract is not None:
setter_fun_with_possible_contract = _add_contract_to_setter(setter_fun, var_name, pycontract,
property_name)
elif validators is not None:
setter_fun_with_possible_contract = _add_validators_to_setter(setter_fun, var_name, validators,
property_name)
# 5. change the function name to make it look nice
setter_fun_with_possible_contract.__name__ = property_name
setter_fun_with_possible_contract.__module__ = object_type.__module__
setter_fun_with_possible_contract.__qualname__ = object_type.__name__ + '.' + property_name
# __annotations__
# __doc__
# __dict__
# 6. Finally add the property to the class
# WARNING : property_obj.setter(f) does absolutely nothing :) > we have to assign the result
# setattr(object_type, property_name, property_obj.setter(f))
new_prop = property(fget=getter_fun, fset=setter_fun_with_possible_contract)
# # specific for enforce: here we might wrap the overriden property setter on which enforce has already written
# # something.
# if hasattr(setter_fun_with_possible_contract, '__enforcer__'):
# new_prop.__enforcer__ = setter_fun_with_possible_contract.__enforcer__
# DESIGN DECISION > although this would probably work, it is probably better to 'force' users to always use the
# @autoprops annotation BEFORE any other annotation. This is now done in autoprops_decorate
setattr(object_type, property_name, new_prop) | python | def _add_property(object_type, # type: Type[T]
parameter, # type: Parameter
pycontract=None, # type: Any
validators=None # type: Any
):
"""
A method to dynamically add a property to a class with the optional given pycontract or validators.
If the property getter and/or setter have been overridden, it is taken into account too.
:param object_type: the class on which to execute.
:param parameter:
:param pycontract:
:param validators:
:return:
"""
property_name = parameter.name
# 1. create the private field name , e.g. '_foobar'
private_property_name = '_' + property_name
# 2. property getter (@property) - create or use overridden
getter_fun = _get_getter_fun(object_type, parameter, private_property_name)
# 3. property setter (@property_name.setter) - create or use overridden
setter_fun, var_name = _get_setter_fun(object_type, parameter, private_property_name)
# 4. add the contract to the setter, if any
setter_fun_with_possible_contract = setter_fun
if pycontract is not None:
setter_fun_with_possible_contract = _add_contract_to_setter(setter_fun, var_name, pycontract,
property_name)
elif validators is not None:
setter_fun_with_possible_contract = _add_validators_to_setter(setter_fun, var_name, validators,
property_name)
# 5. change the function name to make it look nice
setter_fun_with_possible_contract.__name__ = property_name
setter_fun_with_possible_contract.__module__ = object_type.__module__
setter_fun_with_possible_contract.__qualname__ = object_type.__name__ + '.' + property_name
# __annotations__
# __doc__
# __dict__
# 6. Finally add the property to the class
# WARNING : property_obj.setter(f) does absolutely nothing :) > we have to assign the result
# setattr(object_type, property_name, property_obj.setter(f))
new_prop = property(fget=getter_fun, fset=setter_fun_with_possible_contract)
# # specific for enforce: here we might wrap the overriden property setter on which enforce has already written
# # something.
# if hasattr(setter_fun_with_possible_contract, '__enforcer__'):
# new_prop.__enforcer__ = setter_fun_with_possible_contract.__enforcer__
# DESIGN DECISION > although this would probably work, it is probably better to 'force' users to always use the
# @autoprops annotation BEFORE any other annotation. This is now done in autoprops_decorate
setattr(object_type, property_name, new_prop) | A method to dynamically add a property to a class with the optional given pycontract or validators.
If the property getter and/or setter have been overridden, it is taken into account too.
:param object_type: the class on which to execute.
:param parameter:
:param pycontract:
:param validators:
:return: | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/autoprops_.py#L160-L215 |
smarie/python-autoclass | autoclass/autoprops_.py | _has_annotation | def _has_annotation(annotation, value):
""" Returns a function that can be used as a predicate in get_members, that """
def matches_property_name(fun):
""" return true if fun is a callable that has the correct annotation with value """
return callable(fun) and hasattr(fun, annotation) \
and getattr(fun, annotation) is value
return matches_property_name | python | def _has_annotation(annotation, value):
""" Returns a function that can be used as a predicate in get_members, that """
def matches_property_name(fun):
""" return true if fun is a callable that has the correct annotation with value """
return callable(fun) and hasattr(fun, annotation) \
and getattr(fun, annotation) is value
return matches_property_name | Returns a function that can be used as a predicate in get_members, that | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/autoprops_.py#L218-L225 |
smarie/python-autoclass | autoclass/autoprops_.py | _get_getter_fun | def _get_getter_fun(object_type, # type: Type
parameter, # type: Parameter
private_property_name # type: str
):
"""
Utility method to find the overridden getter function for a given property, or generate a new one
:param object_type:
:param property_name:
:param private_property_name:
:return:
"""
property_name = parameter.name
# -- check overridden getter for this property name
overridden_getters = getmembers(object_type, predicate=_has_annotation(__GETTER_OVERRIDE_ANNOTATION, property_name))
if len(overridden_getters) > 0:
if len(overridden_getters) > 1:
raise DuplicateOverrideError('Getter is overridden more than once for attribute name : ' + property_name)
# --use the overridden getter
getter_fun = overridden_getters[0][1]
# --check its signature
s = signature(getter_fun)
if not ('self' in s.parameters.keys() and len(s.parameters.keys()) == 1):
raise IllegalGetterSignatureException('overridden getter must only have a self parameter, found ' +
str(len(s.parameters.items()) - 1) + ' for function ' + str(
getter_fun.__qualname__))
# --use the overridden getter ?
property_obj = property(getter_fun)
else:
# -- generate the getter :
def autoprops_generated_getter(self):
return getattr(self, private_property_name)
# -- use the generated getter
getter_fun = autoprops_generated_getter
try:
annotations = getter_fun.__annotations__
except AttributeError:
# python 2
pass
else:
annotations['return'] = parameter.annotation # add type hint to output declaration
return getter_fun | python | def _get_getter_fun(object_type, # type: Type
parameter, # type: Parameter
private_property_name # type: str
):
"""
Utility method to find the overridden getter function for a given property, or generate a new one
:param object_type:
:param property_name:
:param private_property_name:
:return:
"""
property_name = parameter.name
# -- check overridden getter for this property name
overridden_getters = getmembers(object_type, predicate=_has_annotation(__GETTER_OVERRIDE_ANNOTATION, property_name))
if len(overridden_getters) > 0:
if len(overridden_getters) > 1:
raise DuplicateOverrideError('Getter is overridden more than once for attribute name : ' + property_name)
# --use the overridden getter
getter_fun = overridden_getters[0][1]
# --check its signature
s = signature(getter_fun)
if not ('self' in s.parameters.keys() and len(s.parameters.keys()) == 1):
raise IllegalGetterSignatureException('overridden getter must only have a self parameter, found ' +
str(len(s.parameters.items()) - 1) + ' for function ' + str(
getter_fun.__qualname__))
# --use the overridden getter ?
property_obj = property(getter_fun)
else:
# -- generate the getter :
def autoprops_generated_getter(self):
return getattr(self, private_property_name)
# -- use the generated getter
getter_fun = autoprops_generated_getter
try:
annotations = getter_fun.__annotations__
except AttributeError:
# python 2
pass
else:
annotations['return'] = parameter.annotation # add type hint to output declaration
return getter_fun | Utility method to find the overridden getter function for a given property, or generate a new one
:param object_type:
:param property_name:
:param private_property_name:
:return: | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/autoprops_.py#L228-L278 |
smarie/python-autoclass | autoclass/autoprops_.py | _get_setter_fun | def _get_setter_fun(object_type, # type: Type
parameter, # type: Parameter
private_property_name # type: str
):
"""
Utility method to find the overridden setter function for a given property, or generate a new one
:param object_type:
:param property_name:
:param property_type:
:param private_property_name:
:return:
"""
# the property will have the same name than the constructor argument
property_name = parameter.name
overridden_setters = getmembers(object_type, _has_annotation(__SETTER_OVERRIDE_ANNOTATION, property_name))
if len(overridden_setters) > 0:
# --check that we only have one
if len(overridden_setters) > 1:
raise DuplicateOverrideError('Setter is overridden more than once for attribute name : %s' % property_name)
# --use the overridden setter
setter_fun = overridden_setters[0][1]
try:
# python 2
setter_fun = setter_fun.im_func
except AttributeError:
pass
# --find the parameter name and check the signature
s = signature(setter_fun)
p = [attribute_name for attribute_name, param in s.parameters.items() if attribute_name is not 'self']
if len(p) != 1:
try:
qname = setter_fun.__qualname__
except AttributeError:
qname = setter_fun.__name__
raise IllegalSetterSignatureException('overridden setter must have only 1 non-self argument, found ' +
'%s for function %s'
'' % (len(s.parameters.items()) - 1, qname))
var_name = p[0]
else:
# --create the setter, equivalent of:
# ** Dynamically compile a wrapper with correct argument name **
sig = Signature(parameters=[Parameter('self', kind=Parameter.POSITIONAL_OR_KEYWORD), parameter])
@with_signature(sig)
def autoprops_generated_setter(self, **kwargs):
setattr(self, private_property_name, kwargs.popitem()[1])
setter_fun = autoprops_generated_setter
var_name = property_name
return setter_fun, var_name | python | def _get_setter_fun(object_type, # type: Type
parameter, # type: Parameter
private_property_name # type: str
):
"""
Utility method to find the overridden setter function for a given property, or generate a new one
:param object_type:
:param property_name:
:param property_type:
:param private_property_name:
:return:
"""
# the property will have the same name than the constructor argument
property_name = parameter.name
overridden_setters = getmembers(object_type, _has_annotation(__SETTER_OVERRIDE_ANNOTATION, property_name))
if len(overridden_setters) > 0:
# --check that we only have one
if len(overridden_setters) > 1:
raise DuplicateOverrideError('Setter is overridden more than once for attribute name : %s' % property_name)
# --use the overridden setter
setter_fun = overridden_setters[0][1]
try:
# python 2
setter_fun = setter_fun.im_func
except AttributeError:
pass
# --find the parameter name and check the signature
s = signature(setter_fun)
p = [attribute_name for attribute_name, param in s.parameters.items() if attribute_name is not 'self']
if len(p) != 1:
try:
qname = setter_fun.__qualname__
except AttributeError:
qname = setter_fun.__name__
raise IllegalSetterSignatureException('overridden setter must have only 1 non-self argument, found ' +
'%s for function %s'
'' % (len(s.parameters.items()) - 1, qname))
var_name = p[0]
else:
# --create the setter, equivalent of:
# ** Dynamically compile a wrapper with correct argument name **
sig = Signature(parameters=[Parameter('self', kind=Parameter.POSITIONAL_OR_KEYWORD), parameter])
@with_signature(sig)
def autoprops_generated_setter(self, **kwargs):
setattr(self, private_property_name, kwargs.popitem()[1])
setter_fun = autoprops_generated_setter
var_name = property_name
return setter_fun, var_name | Utility method to find the overridden setter function for a given property, or generate a new one
:param object_type:
:param property_name:
:param property_type:
:param private_property_name:
:return: | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/autoprops_.py#L281-L338 |
smarie/python-autoclass | autoclass/autoprops_.py | getter_override | def getter_override(attribute=None, # type: str
f=DECORATED
):
"""
A decorator to indicate an overridden getter for a given attribute. If the attribute name is None, the function name
will be used as the attribute name.
:param attribute: the attribute name for which the decorated function is an overridden getter
:return:
"""
return autoprops_override_decorate(f, attribute=attribute, is_getter=True) | python | def getter_override(attribute=None, # type: str
f=DECORATED
):
"""
A decorator to indicate an overridden getter for a given attribute. If the attribute name is None, the function name
will be used as the attribute name.
:param attribute: the attribute name for which the decorated function is an overridden getter
:return:
"""
return autoprops_override_decorate(f, attribute=attribute, is_getter=True) | A decorator to indicate an overridden getter for a given attribute. If the attribute name is None, the function name
will be used as the attribute name.
:param attribute: the attribute name for which the decorated function is an overridden getter
:return: | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/autoprops_.py#L431-L441 |
smarie/python-autoclass | autoclass/autoprops_.py | setter_override | def setter_override(attribute=None, # type: str
f=DECORATED
):
"""
A decorator to indicate an overridden setter for a given attribute. If the attribute name is None, the function name
will be used as the attribute name. The @contract will still be dynamically added.
:param attribute: the attribute name for which the decorated function is an overridden setter
:return:
"""
return autoprops_override_decorate(f, attribute=attribute, is_getter=False) | python | def setter_override(attribute=None, # type: str
f=DECORATED
):
"""
A decorator to indicate an overridden setter for a given attribute. If the attribute name is None, the function name
will be used as the attribute name. The @contract will still be dynamically added.
:param attribute: the attribute name for which the decorated function is an overridden setter
:return:
"""
return autoprops_override_decorate(f, attribute=attribute, is_getter=False) | A decorator to indicate an overridden setter for a given attribute. If the attribute name is None, the function name
will be used as the attribute name. The @contract will still be dynamically added.
:param attribute: the attribute name for which the decorated function is an overridden setter
:return: | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/autoprops_.py#L445-L455 |
smarie/python-autoclass | autoclass/autoprops_.py | autoprops_override_decorate | def autoprops_override_decorate(func, # type: Callable
attribute=None, # type: str
is_getter=True # type: bool
):
# type: (...) -> Callable
"""
Used to decorate a function as an overridden getter or setter, without using the @getter_override or
@setter_override annotations. If the overridden setter has no @contract, the contract will still be
dynamically added. Note: this should be executed BEFORE @autoprops or autoprops_decorate().
:param func: the function on which to execute. Note that it won't be wrapped but simply annotated.
:param attribute: the attribute name. If None, the function name will be used
:param is_getter: True for a getter override, False for a setter override.
:return:
"""
# Simply annotate the fact that this is a function
attr_name = attribute or func.__name__
if is_getter:
if hasattr(func, __GETTER_OVERRIDE_ANNOTATION):
raise DuplicateOverrideError('Getter is overridden twice for attribute name : ' + attr_name)
else:
# func.__getter_override__ = attr_name
setattr(func, __GETTER_OVERRIDE_ANNOTATION, attr_name)
else:
if hasattr(func, __SETTER_OVERRIDE_ANNOTATION):
raise DuplicateOverrideError('Setter is overridden twice for attribute name : ' + attr_name)
else:
# func.__setter_override__ = attr_name
setattr(func, __SETTER_OVERRIDE_ANNOTATION, attr_name)
return func | python | def autoprops_override_decorate(func, # type: Callable
attribute=None, # type: str
is_getter=True # type: bool
):
# type: (...) -> Callable
"""
Used to decorate a function as an overridden getter or setter, without using the @getter_override or
@setter_override annotations. If the overridden setter has no @contract, the contract will still be
dynamically added. Note: this should be executed BEFORE @autoprops or autoprops_decorate().
:param func: the function on which to execute. Note that it won't be wrapped but simply annotated.
:param attribute: the attribute name. If None, the function name will be used
:param is_getter: True for a getter override, False for a setter override.
:return:
"""
# Simply annotate the fact that this is a function
attr_name = attribute or func.__name__
if is_getter:
if hasattr(func, __GETTER_OVERRIDE_ANNOTATION):
raise DuplicateOverrideError('Getter is overridden twice for attribute name : ' + attr_name)
else:
# func.__getter_override__ = attr_name
setattr(func, __GETTER_OVERRIDE_ANNOTATION, attr_name)
else:
if hasattr(func, __SETTER_OVERRIDE_ANNOTATION):
raise DuplicateOverrideError('Setter is overridden twice for attribute name : ' + attr_name)
else:
# func.__setter_override__ = attr_name
setattr(func, __SETTER_OVERRIDE_ANNOTATION, attr_name)
return func | Used to decorate a function as an overridden getter or setter, without using the @getter_override or
@setter_override annotations. If the overridden setter has no @contract, the contract will still be
dynamically added. Note: this should be executed BEFORE @autoprops or autoprops_decorate().
:param func: the function on which to execute. Note that it won't be wrapped but simply annotated.
:param attribute: the attribute name. If None, the function name will be used
:param is_getter: True for a getter override, False for a setter override.
:return: | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/autoprops_.py#L458-L489 |
smarie/python-autoclass | ci_tools/github_release.py | create_or_update_release | def create_or_update_release(user, pwd, secret, repo_slug, changelog_file, doc_url, data_file, tag):
"""
Creates or updates (TODO)
a github release corresponding to git tag <TAG>.
"""
# 1- AUTHENTICATION
if user is not None and secret is None:
# using username and password
# validate('user', user, instance_of=str)
assert isinstance(user, str)
# validate('pwd', pwd, instance_of=str)
assert isinstance(pwd, str)
g = Github(user, pwd)
elif user is None and secret is not None:
# or using an access token
# validate('secret', secret, instance_of=str)
assert isinstance(secret, str)
g = Github(secret)
else:
raise ValueError("You should either provide username/password OR an access token")
click.echo("Logged in as {user_name}".format(user_name=g.get_user()))
# 2- CHANGELOG VALIDATION
regex_pattern = "[\s\S]*[\n][#]+[\s]*(?P<title>[\S ]*%s[\S ]*)[\n]+?(?P<body>[\s\S]*?)[\n]*?(\n#|$)" % re.escape(tag)
changelog_section = re.compile(regex_pattern)
if changelog_file is not None:
# validate('changelog_file', changelog_file, custom=os.path.exists,
# help_msg="changelog file should be a valid file path")
assert os.path.exists(changelog_file), "changelog file should be a valid file path"
with open(changelog_file) as f:
contents = f.read()
match = changelog_section.match(contents).groupdict()
if match is None or len(match) != 2:
raise ValueError("Unable to find changelog section matching regexp pattern in changelog file.")
else:
title = match['title']
message = match['body']
else:
title = tag
message = ''
# append footer if doc url is provided
message += "\n\nSee [documentation page](%s) for details." % doc_url
# 3- REPOSITORY EXPLORATION
# validate('repo_slug', repo_slug, instance_of=str, min_len=1, help_msg="repo_slug should be a non-empty string")
assert isinstance(repo_slug, str) and len(repo_slug) > 0, "repo_slug should be a non-empty string"
repo = g.get_repo(repo_slug)
# -- Is there a tag with that name ?
try:
tag_ref = repo.get_git_ref("tags/" + tag)
except UnknownObjectException:
raise ValueError("No tag with name %s exists in repository %s" % (tag, repo.name))
# -- Is there already a release with that tag name ?
click.echo("Checking if release %s already exists in repository %s" % (tag, repo.name))
try:
release = repo.get_release(tag)
if release is not None:
raise ValueError("Release %s already exists in repository %s. Please set overwrite to True if you wish to "
"update the release (Not yet supported)" % (tag, repo.name))
except UnknownObjectException:
# Release does not exist: we can safely create it.
click.echo("Creating release %s on repo: %s" % (tag, repo.name))
click.echo("Release title: '%s'" % title)
click.echo("Release message:\n--\n%s\n--\n" % message)
repo.create_git_release(tag=tag, name=title,
message=message,
draft=False, prerelease=False)
# add the asset file if needed
if data_file is not None:
release = None
while release is None:
release = repo.get_release(tag)
release.upload_asset(path=data_file, label=path.split(data_file)[1], content_type="application/gzip") | python | def create_or_update_release(user, pwd, secret, repo_slug, changelog_file, doc_url, data_file, tag):
"""
Creates or updates (TODO)
a github release corresponding to git tag <TAG>.
"""
# 1- AUTHENTICATION
if user is not None and secret is None:
# using username and password
# validate('user', user, instance_of=str)
assert isinstance(user, str)
# validate('pwd', pwd, instance_of=str)
assert isinstance(pwd, str)
g = Github(user, pwd)
elif user is None and secret is not None:
# or using an access token
# validate('secret', secret, instance_of=str)
assert isinstance(secret, str)
g = Github(secret)
else:
raise ValueError("You should either provide username/password OR an access token")
click.echo("Logged in as {user_name}".format(user_name=g.get_user()))
# 2- CHANGELOG VALIDATION
regex_pattern = "[\s\S]*[\n][#]+[\s]*(?P<title>[\S ]*%s[\S ]*)[\n]+?(?P<body>[\s\S]*?)[\n]*?(\n#|$)" % re.escape(tag)
changelog_section = re.compile(regex_pattern)
if changelog_file is not None:
# validate('changelog_file', changelog_file, custom=os.path.exists,
# help_msg="changelog file should be a valid file path")
assert os.path.exists(changelog_file), "changelog file should be a valid file path"
with open(changelog_file) as f:
contents = f.read()
match = changelog_section.match(contents).groupdict()
if match is None or len(match) != 2:
raise ValueError("Unable to find changelog section matching regexp pattern in changelog file.")
else:
title = match['title']
message = match['body']
else:
title = tag
message = ''
# append footer if doc url is provided
message += "\n\nSee [documentation page](%s) for details." % doc_url
# 3- REPOSITORY EXPLORATION
# validate('repo_slug', repo_slug, instance_of=str, min_len=1, help_msg="repo_slug should be a non-empty string")
assert isinstance(repo_slug, str) and len(repo_slug) > 0, "repo_slug should be a non-empty string"
repo = g.get_repo(repo_slug)
# -- Is there a tag with that name ?
try:
tag_ref = repo.get_git_ref("tags/" + tag)
except UnknownObjectException:
raise ValueError("No tag with name %s exists in repository %s" % (tag, repo.name))
# -- Is there already a release with that tag name ?
click.echo("Checking if release %s already exists in repository %s" % (tag, repo.name))
try:
release = repo.get_release(tag)
if release is not None:
raise ValueError("Release %s already exists in repository %s. Please set overwrite to True if you wish to "
"update the release (Not yet supported)" % (tag, repo.name))
except UnknownObjectException:
# Release does not exist: we can safely create it.
click.echo("Creating release %s on repo: %s" % (tag, repo.name))
click.echo("Release title: '%s'" % title)
click.echo("Release message:\n--\n%s\n--\n" % message)
repo.create_git_release(tag=tag, name=title,
message=message,
draft=False, prerelease=False)
# add the asset file if needed
if data_file is not None:
release = None
while release is None:
release = repo.get_release(tag)
release.upload_asset(path=data_file, label=path.split(data_file)[1], content_type="application/gzip") | Creates or updates (TODO)
a github release corresponding to git tag <TAG>. | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/ci_tools/github_release.py#L23-L100 |
smarie/python-autoclass | autoclass/utils.py | validate_include_exclude | def validate_include_exclude(include, exclude):
"""
Common validator for include and exclude arguments
:param include:
:param exclude:
:return:
"""
if include is not None and exclude is not None:
raise ValueError("Only one of 'include' or 'exclude' argument should be provided.")
validate('include', include, instance_of=(str, Sequence), enforce_not_none=False)
validate('exclude', exclude, instance_of=(str, Sequence), enforce_not_none=False) | python | def validate_include_exclude(include, exclude):
"""
Common validator for include and exclude arguments
:param include:
:param exclude:
:return:
"""
if include is not None and exclude is not None:
raise ValueError("Only one of 'include' or 'exclude' argument should be provided.")
validate('include', include, instance_of=(str, Sequence), enforce_not_none=False)
validate('exclude', exclude, instance_of=(str, Sequence), enforce_not_none=False) | Common validator for include and exclude arguments
:param include:
:param exclude:
:return: | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/utils.py#L10-L20 |
smarie/python-autoclass | autoclass/utils.py | is_attr_selected | def is_attr_selected(attr_name, # type: str
include=None, # type: Union[str, Tuple[str]]
exclude=None # type: Union[str, Tuple[str]]
):
"""decide whether an action has to be performed on the attribute or not, based on its name"""
if include is not None and exclude is not None:
raise ValueError('Only one of \'include\' or \'exclude\' argument should be provided.')
# win time by not doing this
# check_var(include, var_name='include', var_types=[str, tuple], enforce_not_none=False)
# check_var(exclude, var_name='exclude', var_types=[str, tuple], enforce_not_none=False)
if attr_name is 'self':
return False
if exclude and attr_name in exclude:
return False
if not include or attr_name in include:
return True
else:
return False | python | def is_attr_selected(attr_name, # type: str
include=None, # type: Union[str, Tuple[str]]
exclude=None # type: Union[str, Tuple[str]]
):
"""decide whether an action has to be performed on the attribute or not, based on its name"""
if include is not None and exclude is not None:
raise ValueError('Only one of \'include\' or \'exclude\' argument should be provided.')
# win time by not doing this
# check_var(include, var_name='include', var_types=[str, tuple], enforce_not_none=False)
# check_var(exclude, var_name='exclude', var_types=[str, tuple], enforce_not_none=False)
if attr_name is 'self':
return False
if exclude and attr_name in exclude:
return False
if not include or attr_name in include:
return True
else:
return False | decide whether an action has to be performed on the attribute or not, based on its name | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/utils.py#L23-L43 |
smarie/python-autoclass | autoclass/utils.py | get_constructor | def get_constructor(typ,
allow_inheritance=False # type: bool
):
"""
Utility method to return the unique constructor (__init__) of a type
:param typ: a type
:param allow_inheritance: if True, the constructor will be returned even if it is not defined in this class
(inherited). By default this is set to False: an exception is raised when no constructor is explicitly defined in
the class
:return: the found constructor
"""
if allow_inheritance:
return typ.__init__
else:
# check that the constructor is really defined here
if '__init__' in typ.__dict__:
return typ.__init__
else:
raise Exception('No explicit constructor was found for class ' + str(typ)) | python | def get_constructor(typ,
allow_inheritance=False # type: bool
):
"""
Utility method to return the unique constructor (__init__) of a type
:param typ: a type
:param allow_inheritance: if True, the constructor will be returned even if it is not defined in this class
(inherited). By default this is set to False: an exception is raised when no constructor is explicitly defined in
the class
:return: the found constructor
"""
if allow_inheritance:
return typ.__init__
else:
# check that the constructor is really defined here
if '__init__' in typ.__dict__:
return typ.__init__
else:
raise Exception('No explicit constructor was found for class ' + str(typ)) | Utility method to return the unique constructor (__init__) of a type
:param typ: a type
:param allow_inheritance: if True, the constructor will be returned even if it is not defined in this class
(inherited). By default this is set to False: an exception is raised when no constructor is explicitly defined in
the class
:return: the found constructor | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/utils.py#L46-L65 |
smarie/python-autoclass | autoclass/utils.py | _check_known_decorators | def _check_known_decorators(typ, calling_decorator # type: str
):
# type: (...) -> bool
"""
Checks that a given type is not already decorated by known decorators that may cause trouble.
If so, it raises an Exception
:return:
"""
for member in typ.__dict__.values():
if hasattr(member, '__enforcer__'):
raise AutoclassDecorationException('It seems that @runtime_validation decorator was applied to type <'
+ str(typ) + '> BEFORE ' + calling_decorator + '. This is not supported '
'as it may lead to counter-intuitive behaviour, please change the order '
'of the decorators on <' + str(typ) + '>') | python | def _check_known_decorators(typ, calling_decorator # type: str
):
# type: (...) -> bool
"""
Checks that a given type is not already decorated by known decorators that may cause trouble.
If so, it raises an Exception
:return:
"""
for member in typ.__dict__.values():
if hasattr(member, '__enforcer__'):
raise AutoclassDecorationException('It seems that @runtime_validation decorator was applied to type <'
+ str(typ) + '> BEFORE ' + calling_decorator + '. This is not supported '
'as it may lead to counter-intuitive behaviour, please change the order '
'of the decorators on <' + str(typ) + '>') | Checks that a given type is not already decorated by known decorators that may cause trouble.
If so, it raises an Exception
:return: | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/utils.py#L72-L85 |
smarie/python-autoclass | autoclass/utils.py | method_already_there | def method_already_there(object_type, method_name, this_class_only=False):
"""
Returns True if method `method_name` is already implemented by object_type, that is, its implementation differs from
the one in `object`.
:param object_type:
:param method_name:
:param this_class_only:
:return:
"""
if this_class_only:
return method_name in vars(object_type) # or object_type.__dict__
else:
try:
method = getattr(object_type, method_name)
except AttributeError:
return False
else:
return method is not None and method is not getattr(object, method_name, None) | python | def method_already_there(object_type, method_name, this_class_only=False):
"""
Returns True if method `method_name` is already implemented by object_type, that is, its implementation differs from
the one in `object`.
:param object_type:
:param method_name:
:param this_class_only:
:return:
"""
if this_class_only:
return method_name in vars(object_type) # or object_type.__dict__
else:
try:
method = getattr(object_type, method_name)
except AttributeError:
return False
else:
return method is not None and method is not getattr(object, method_name, None) | Returns True if method `method_name` is already implemented by object_type, that is, its implementation differs from
the one in `object`.
:param object_type:
:param method_name:
:param this_class_only:
:return: | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/utils.py#L88-L106 |
smarie/python-autoclass | autoclass/autoargs_.py | autoargs | def autoargs(include=None, # type: Union[str, Tuple[str]]
exclude=None, # type: Union[str, Tuple[str]]
f=DECORATED
):
"""
Defines a decorator with parameters, to automatically assign the inputs of a function to self PRIOR to executing
the function. In other words:
```
@autoargs
def myfunc(a):
print('hello')
```
will create the equivalent of
```
def myfunc(a):
self.a = a
print('hello')
```
Initial code from http://stackoverflow.com/questions/3652851/what-is-the-best-way-to-do-automatic-attribute-assignment-in-python-and-is-it-a#answer-3653049
:param include: a tuple of attribute names to include in the auto-assignment. If None, all arguments will be
included by default
:param exclude: a tuple of attribute names to exclude from the auto-assignment. In such case, include should be None
:return:
"""
return autoargs_decorate(f, include=include, exclude=exclude) | python | def autoargs(include=None, # type: Union[str, Tuple[str]]
exclude=None, # type: Union[str, Tuple[str]]
f=DECORATED
):
"""
Defines a decorator with parameters, to automatically assign the inputs of a function to self PRIOR to executing
the function. In other words:
```
@autoargs
def myfunc(a):
print('hello')
```
will create the equivalent of
```
def myfunc(a):
self.a = a
print('hello')
```
Initial code from http://stackoverflow.com/questions/3652851/what-is-the-best-way-to-do-automatic-attribute-assignment-in-python-and-is-it-a#answer-3653049
:param include: a tuple of attribute names to include in the auto-assignment. If None, all arguments will be
included by default
:param exclude: a tuple of attribute names to exclude from the auto-assignment. In such case, include should be None
:return:
"""
return autoargs_decorate(f, include=include, exclude=exclude) | Defines a decorator with parameters, to automatically assign the inputs of a function to self PRIOR to executing
the function. In other words:
```
@autoargs
def myfunc(a):
print('hello')
```
will create the equivalent of
```
def myfunc(a):
self.a = a
print('hello')
```
Initial code from http://stackoverflow.com/questions/3652851/what-is-the-best-way-to-do-automatic-attribute-assignment-in-python-and-is-it-a#answer-3653049
:param include: a tuple of attribute names to include in the auto-assignment. If None, all arguments will be
included by default
:param exclude: a tuple of attribute names to exclude from the auto-assignment. In such case, include should be None
:return: | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/autoargs_.py#L22-L51 |
smarie/python-autoclass | autoclass/autoargs_.py | autoargs_decorate | def autoargs_decorate(func, # type: Callable
include=None, # type: Union[str, Tuple[str]]
exclude=None # type: Union[str, Tuple[str]]
):
# type: (...) -> Callable
"""
Defines a decorator with parameters, to automatically assign the inputs of a function to self PRIOR to executing
the function. This is the inline way to apply the decorator
```
myfunc2 = autoargs_decorate(myfunc)
```
See autoargs for details.
:param func: the function to wrap
:param include: a tuple of attribute names to include in the auto-assignment. If None, all arguments will be
included by default
:param exclude: a tuple of attribute names to exclude from the auto-assignment. In such case, include should be None
:return:
"""
# (0) first check parameters
validate_include_exclude(include, exclude)
# (1) then retrieve function signature
# attrs, varargs, varkw, defaults = getargspec(func)
func_sig = signature(func)
# check that include/exclude dont contain names that are incorrect
if include is not None:
incorrect = set([include] if isinstance(include, str) else include) - set(func_sig.parameters.keys())
if len(incorrect) > 0:
raise ValueError("@autoargs definition exception: include contains '%s' that is/are "
"not part of signature for %s" % (incorrect, func))
if exclude is not None:
incorrect = set([exclude] if isinstance(exclude, str) else exclude) - set(func_sig.parameters.keys())
if len(incorrect) > 0:
raise ValueError("@autoargs definition exception: exclude contains '%s' that is/are "
"not part of signature for %s" % (incorrect, func))
# TODO this should be in @autoslots decorator at class level, not here.
# (2) Optionally lock the class only for the provided fields
# Does not work for the moment. Besides locking fields seems to have issues with pickle serialization
# so we'd rather not propose this option.
#
# See 'attrs' project for this kind of advanced features https://github.com/python-attrs/attrs
#
# if lock_class_fields:
# if signature_varkw:
# raise Exception('cant lock field names with variable kwargs')
# else:
# object_type = get_class_that_defined_method(func)
# if include:
# fields = include
# else:
# fields = signature_attrs[1:]
# if signature_varargs:
# fields.append(signature_varargs)
# if exclude:
# for a in exclude:
# fields.remove(a)
#
# # right now, doesnot work
# _lock_fieldnames_class(object_type, field_names=tuple(fields))
# (3) Finally, create a wrapper around the function so that all attributes included/not excluded are
# set to self BEFORE executing the function.
@wraps(func)
def init_wrapper(self, *args, **kwargs):
# match the received arguments with the signature to know who is who, and add default values to get a full list
bound_values = func_sig.bind(self, *args, **kwargs)
apply_defaults(bound_values)
# Assign to self the ones that needs to
for att_name, att_value in bound_values.arguments.items():
if is_attr_selected(att_name, include=include, exclude=exclude):
# value = a normal value, or cur_kwargs as a whole
setattr(self, att_name, att_value)
# finally execute the constructor function
return func(self, *args, **kwargs)
# return wrapper
return init_wrapper | python | def autoargs_decorate(func, # type: Callable
include=None, # type: Union[str, Tuple[str]]
exclude=None # type: Union[str, Tuple[str]]
):
# type: (...) -> Callable
"""
Defines a decorator with parameters, to automatically assign the inputs of a function to self PRIOR to executing
the function. This is the inline way to apply the decorator
```
myfunc2 = autoargs_decorate(myfunc)
```
See autoargs for details.
:param func: the function to wrap
:param include: a tuple of attribute names to include in the auto-assignment. If None, all arguments will be
included by default
:param exclude: a tuple of attribute names to exclude from the auto-assignment. In such case, include should be None
:return:
"""
# (0) first check parameters
validate_include_exclude(include, exclude)
# (1) then retrieve function signature
# attrs, varargs, varkw, defaults = getargspec(func)
func_sig = signature(func)
# check that include/exclude dont contain names that are incorrect
if include is not None:
incorrect = set([include] if isinstance(include, str) else include) - set(func_sig.parameters.keys())
if len(incorrect) > 0:
raise ValueError("@autoargs definition exception: include contains '%s' that is/are "
"not part of signature for %s" % (incorrect, func))
if exclude is not None:
incorrect = set([exclude] if isinstance(exclude, str) else exclude) - set(func_sig.parameters.keys())
if len(incorrect) > 0:
raise ValueError("@autoargs definition exception: exclude contains '%s' that is/are "
"not part of signature for %s" % (incorrect, func))
# TODO this should be in @autoslots decorator at class level, not here.
# (2) Optionally lock the class only for the provided fields
# Does not work for the moment. Besides locking fields seems to have issues with pickle serialization
# so we'd rather not propose this option.
#
# See 'attrs' project for this kind of advanced features https://github.com/python-attrs/attrs
#
# if lock_class_fields:
# if signature_varkw:
# raise Exception('cant lock field names with variable kwargs')
# else:
# object_type = get_class_that_defined_method(func)
# if include:
# fields = include
# else:
# fields = signature_attrs[1:]
# if signature_varargs:
# fields.append(signature_varargs)
# if exclude:
# for a in exclude:
# fields.remove(a)
#
# # right now, doesnot work
# _lock_fieldnames_class(object_type, field_names=tuple(fields))
# (3) Finally, create a wrapper around the function so that all attributes included/not excluded are
# set to self BEFORE executing the function.
@wraps(func)
def init_wrapper(self, *args, **kwargs):
# match the received arguments with the signature to know who is who, and add default values to get a full list
bound_values = func_sig.bind(self, *args, **kwargs)
apply_defaults(bound_values)
# Assign to self the ones that needs to
for att_name, att_value in bound_values.arguments.items():
if is_attr_selected(att_name, include=include, exclude=exclude):
# value = a normal value, or cur_kwargs as a whole
setattr(self, att_name, att_value)
# finally execute the constructor function
return func(self, *args, **kwargs)
# return wrapper
return init_wrapper | Defines a decorator with parameters, to automatically assign the inputs of a function to self PRIOR to executing
the function. This is the inline way to apply the decorator
```
myfunc2 = autoargs_decorate(myfunc)
```
See autoargs for details.
:param func: the function to wrap
:param include: a tuple of attribute names to include in the auto-assignment. If None, all arguments will be
included by default
:param exclude: a tuple of attribute names to exclude from the auto-assignment. In such case, include should be None
:return: | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/autoargs_.py#L54-L140 |
planetarypy/pvl | pvl/_collections.py | OrderedMultiDict.append | def append(self, key, value):
"""Adds a (name, value) pair, doesn't overwrite the value if it already
exists."""
self.__items.append((key, value))
try:
dict_getitem(self, key).append(value)
except KeyError:
dict_setitem(self, key, [value]) | python | def append(self, key, value):
"""Adds a (name, value) pair, doesn't overwrite the value if it already
exists."""
self.__items.append((key, value))
try:
dict_getitem(self, key).append(value)
except KeyError:
dict_setitem(self, key, [value]) | Adds a (name, value) pair, doesn't overwrite the value if it already
exists. | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/_collections.py#L211-L219 |
planetarypy/pvl | pvl/_collections.py | OrderedMultiDict.extend | def extend(self, *args, **kwargs):
"""Add key value pairs for an iterable."""
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
iterable = args[0] if args else None
if iterable:
if isinstance(iterable, Mapping) or hasattr(iterable, 'items'):
for key, value in iterable.items():
self.append(key, value)
elif hasattr(iterable, 'keys'):
for key in iterable.keys():
self.append(key, iterable[key])
else:
for key, value in iterable:
self.append(key, value)
for key, value in kwargs.items():
self.append(key, value) | python | def extend(self, *args, **kwargs):
"""Add key value pairs for an iterable."""
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
iterable = args[0] if args else None
if iterable:
if isinstance(iterable, Mapping) or hasattr(iterable, 'items'):
for key, value in iterable.items():
self.append(key, value)
elif hasattr(iterable, 'keys'):
for key in iterable.keys():
self.append(key, iterable[key])
else:
for key, value in iterable:
self.append(key, value)
for key, value in kwargs.items():
self.append(key, value) | Add key value pairs for an iterable. | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/_collections.py#L221-L239 |
planetarypy/pvl | pvl/_collections.py | OrderedMultiDict.__insert_wrapper | def __insert_wrapper(func):
"""Make sure the arguments given to the insert methods are correct"""
def check_func(self, key, new_item, instance=0):
if key not in self.keys():
raise KeyError("%s not a key in label" % (key))
if not isinstance(new_item, (list, OrderedMultiDict)):
raise TypeError("The new item must be a list or PVLModule")
if isinstance(new_item, OrderedMultiDict):
new_item = list(new_item)
return func(self, key, new_item, instance)
return check_func | python | def __insert_wrapper(func):
"""Make sure the arguments given to the insert methods are correct"""
def check_func(self, key, new_item, instance=0):
if key not in self.keys():
raise KeyError("%s not a key in label" % (key))
if not isinstance(new_item, (list, OrderedMultiDict)):
raise TypeError("The new item must be a list or PVLModule")
if isinstance(new_item, OrderedMultiDict):
new_item = list(new_item)
return func(self, key, new_item, instance)
return check_func | Make sure the arguments given to the insert methods are correct | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/_collections.py#L265-L275 |
planetarypy/pvl | pvl/_collections.py | OrderedMultiDict._get_index_for_insert | def _get_index_for_insert(self, key, instance):
"""Get the index of the key to insert before or after"""
if instance == 0:
# Index method will return the first occurence of the key
index = self.keys().index(key)
else:
occurrence = -1
for index, k in enumerate(self.keys()):
if k == key:
occurrence += 1
if occurrence == instance:
# Found the key and the correct occurence of the key
break
if occurrence != instance:
# Gone through the entire list of keys and the instance number
# given is too high for the number of occurences of the key
raise ValueError(
(
"Cannot insert before/after the %d "
"instance of the key '%s' since there are "
"only %d occurences of the key" % (
instance, key, occurrence)
))
return index | python | def _get_index_for_insert(self, key, instance):
"""Get the index of the key to insert before or after"""
if instance == 0:
# Index method will return the first occurence of the key
index = self.keys().index(key)
else:
occurrence = -1
for index, k in enumerate(self.keys()):
if k == key:
occurrence += 1
if occurrence == instance:
# Found the key and the correct occurence of the key
break
if occurrence != instance:
# Gone through the entire list of keys and the instance number
# given is too high for the number of occurences of the key
raise ValueError(
(
"Cannot insert before/after the %d "
"instance of the key '%s' since there are "
"only %d occurences of the key" % (
instance, key, occurrence)
))
return index | Get the index of the key to insert before or after | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/_collections.py#L277-L301 |
planetarypy/pvl | pvl/_collections.py | OrderedMultiDict._insert_item | def _insert_item(self, key, new_item, instance, is_after):
"""Insert a new item before or after another item"""
index = self._get_index_for_insert(key, instance)
index = index + 1 if is_after else index
self.__items = self.__items[:index] + new_item + self.__items[index:]
# Make sure indexing works with new items
for new_key, new_value in new_item:
if new_key in self:
value_list = [val for k, val in self.__items if k == new_key]
dict_setitem(self, new_key, value_list)
else:
dict_setitem(self, new_key, [new_value]) | python | def _insert_item(self, key, new_item, instance, is_after):
"""Insert a new item before or after another item"""
index = self._get_index_for_insert(key, instance)
index = index + 1 if is_after else index
self.__items = self.__items[:index] + new_item + self.__items[index:]
# Make sure indexing works with new items
for new_key, new_value in new_item:
if new_key in self:
value_list = [val for k, val in self.__items if k == new_key]
dict_setitem(self, new_key, value_list)
else:
dict_setitem(self, new_key, [new_value]) | Insert a new item before or after another item | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/_collections.py#L303-L314 |
planetarypy/pvl | pvl/_collections.py | OrderedMultiDict.insert_after | def insert_after(self, key, new_item, instance=0):
"""Insert an item after a key"""
self._insert_item(key, new_item, instance, True) | python | def insert_after(self, key, new_item, instance=0):
"""Insert an item after a key"""
self._insert_item(key, new_item, instance, True) | Insert an item after a key | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/_collections.py#L317-L319 |
planetarypy/pvl | pvl/_collections.py | OrderedMultiDict.insert_before | def insert_before(self, key, new_item, instance=0):
"""Insert an item before a key"""
self._insert_item(key, new_item, instance, False) | python | def insert_before(self, key, new_item, instance=0):
"""Insert an item before a key"""
self._insert_item(key, new_item, instance, False) | Insert an item before a key | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/_collections.py#L322-L324 |
planetarypy/pvl | pvl/stream.py | BufferedStream.read | def read(self, n):
"""Read n bytes.
Returns exactly n bytes of data unless the underlying raw IO
stream reaches EOF.
"""
buf = self._read_buf
pos = self._read_pos
end = pos + n
if end <= len(buf):
# Fast path: the data to read is fully buffered.
self._read_pos += n
return self._update_pos(buf[pos:end])
# Slow path: read from the stream until enough bytes are read,
# or until an EOF occurs or until read() would block.
wanted = max(self.buffer_size, n)
while len(buf) < end:
chunk = self.raw.read(wanted)
if not chunk:
break
buf += chunk
self._read_buf = buf[end:] # Save the extra data in the buffer.
self._read_pos = 0
return self._update_pos(buf[pos:end]) | python | def read(self, n):
"""Read n bytes.
Returns exactly n bytes of data unless the underlying raw IO
stream reaches EOF.
"""
buf = self._read_buf
pos = self._read_pos
end = pos + n
if end <= len(buf):
# Fast path: the data to read is fully buffered.
self._read_pos += n
return self._update_pos(buf[pos:end])
# Slow path: read from the stream until enough bytes are read,
# or until an EOF occurs or until read() would block.
wanted = max(self.buffer_size, n)
while len(buf) < end:
chunk = self.raw.read(wanted)
if not chunk:
break
buf += chunk
self._read_buf = buf[end:] # Save the extra data in the buffer.
self._read_pos = 0
return self._update_pos(buf[pos:end]) | Read n bytes.
Returns exactly n bytes of data unless the underlying raw IO
stream reaches EOF. | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/stream.py#L45-L70 |
planetarypy/pvl | pvl/stream.py | ByteStream.read | def read(self, n):
"""Read n bytes.
Returns exactly n bytes of data unless the underlying raw IO
stream reaches EOF.
"""
pos = self._read_pos
self._read_pos = min(len(self.raw), pos + n)
return self.raw[pos:self._read_pos] | python | def read(self, n):
"""Read n bytes.
Returns exactly n bytes of data unless the underlying raw IO
stream reaches EOF.
"""
pos = self._read_pos
self._read_pos = min(len(self.raw), pos + n)
return self.raw[pos:self._read_pos] | Read n bytes.
Returns exactly n bytes of data unless the underlying raw IO
stream reaches EOF. | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/stream.py#L117-L124 |
planetarypy/pvl | pvl/stream.py | ByteStream.peek | def peek(self, n):
"""Returns buffered bytes without advancing the position.
The argument indicates a desired minimal number of bytes; we
do at most one raw read to satisfy it. We never return more
than self.buffer_size.
"""
pos = self._read_pos
end = pos + n
return self.raw[pos:end] | python | def peek(self, n):
"""Returns buffered bytes without advancing the position.
The argument indicates a desired minimal number of bytes; we
do at most one raw read to satisfy it. We never return more
than self.buffer_size.
"""
pos = self._read_pos
end = pos + n
return self.raw[pos:end] | Returns buffered bytes without advancing the position.
The argument indicates a desired minimal number of bytes; we
do at most one raw read to satisfy it. We never return more
than self.buffer_size. | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/stream.py#L126-L134 |
planetarypy/pvl | pvl/decoder.py | PVLDecoder.parse_block | def parse_block(self, stream, has_end):
"""
PVLModuleContents ::= (Statement | WSC)* EndStatement?
AggrObject ::= BeginObjectStmt AggrContents EndObjectStmt
AggrGroup ::= BeginGroupStmt AggrContents EndGroupStmt
AggrContents := WSC Statement (WSC | Statement)*
"""
statements = []
while 1:
self.skip_whitespace_or_comment(stream)
if has_end(stream):
return statements
statement = self.parse_statement(stream)
if isinstance(statement, EmptyValueAtLine):
if len(statements) == 0:
self.raise_unexpected(stream)
self.skip_whitespace_or_comment(stream)
value = self.parse_value(stream)
last_statement = statements.pop(-1)
fixed_last = (
last_statement[0],
statement
)
statements.append(fixed_last)
statements.append((last_statement[1], value))
else:
statements.append(statement) | python | def parse_block(self, stream, has_end):
"""
PVLModuleContents ::= (Statement | WSC)* EndStatement?
AggrObject ::= BeginObjectStmt AggrContents EndObjectStmt
AggrGroup ::= BeginGroupStmt AggrContents EndGroupStmt
AggrContents := WSC Statement (WSC | Statement)*
"""
statements = []
while 1:
self.skip_whitespace_or_comment(stream)
if has_end(stream):
return statements
statement = self.parse_statement(stream)
if isinstance(statement, EmptyValueAtLine):
if len(statements) == 0:
self.raise_unexpected(stream)
self.skip_whitespace_or_comment(stream)
value = self.parse_value(stream)
last_statement = statements.pop(-1)
fixed_last = (
last_statement[0],
statement
)
statements.append(fixed_last)
statements.append((last_statement[1], value))
else:
statements.append(statement) | PVLModuleContents ::= (Statement | WSC)* EndStatement?
AggrObject ::= BeginObjectStmt AggrContents EndObjectStmt
AggrGroup ::= BeginGroupStmt AggrContents EndGroupStmt
AggrContents := WSC Statement (WSC | Statement)* | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/decoder.py#L235-L264 |
planetarypy/pvl | pvl/decoder.py | PVLDecoder.skip_statement_delimiter | def skip_statement_delimiter(self, stream):
"""Ensure that a Statement Delimiter consists of one semicolon,
optionally preceded by multiple White Spaces and/or Comments, OR one or
more Comments and/or White Space sequences.
StatementDelim ::= WSC (SemiColon | WhiteSpace | Comment)
| EndProvidedOctetSeq
"""
self.skip_whitespace_or_comment(stream)
self.optional(stream, self.statement_delimiter) | python | def skip_statement_delimiter(self, stream):
"""Ensure that a Statement Delimiter consists of one semicolon,
optionally preceded by multiple White Spaces and/or Comments, OR one or
more Comments and/or White Space sequences.
StatementDelim ::= WSC (SemiColon | WhiteSpace | Comment)
| EndProvidedOctetSeq
"""
self.skip_whitespace_or_comment(stream)
self.optional(stream, self.statement_delimiter) | Ensure that a Statement Delimiter consists of one semicolon,
optionally preceded by multiple White Spaces and/or Comments, OR one or
more Comments and/or White Space sequences.
StatementDelim ::= WSC (SemiColon | WhiteSpace | Comment)
| EndProvidedOctetSeq | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/decoder.py#L278-L288 |
planetarypy/pvl | pvl/decoder.py | PVLDecoder.parse_statement | def parse_statement(self, stream):
"""
Statement ::= AggrGroup
| AggrObject
| AssignmentStmt
"""
if self.has_group(stream):
return self.parse_group(stream)
if self.has_object(stream):
return self.parse_object(stream)
if self.has_assignment(stream):
return self.parse_assignment(stream)
if self.has_assignment_symbol(stream):
return self.broken_assignment(stream.lineno - 1)
self.raise_unexpected(stream) | python | def parse_statement(self, stream):
"""
Statement ::= AggrGroup
| AggrObject
| AssignmentStmt
"""
if self.has_group(stream):
return self.parse_group(stream)
if self.has_object(stream):
return self.parse_object(stream)
if self.has_assignment(stream):
return self.parse_assignment(stream)
if self.has_assignment_symbol(stream):
return self.broken_assignment(stream.lineno - 1)
self.raise_unexpected(stream) | Statement ::= AggrGroup
| AggrObject
| AssignmentStmt | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/decoder.py#L290-L309 |
planetarypy/pvl | pvl/decoder.py | PVLDecoder.has_end | def has_end(self, stream):
"""
EndStatement ::=
EndKeyword (SemiColon | WhiteSpace | Comment | EndProvidedOctetSeq)
"""
for token in self.end_tokens:
if not self.has_next(token, stream):
continue
offset = len(token)
if self.has_eof(stream, offset):
return True
if self.has_whitespace(stream, offset):
return True
if self.has_comment(stream, offset):
return True
if self.has_next(self.statement_delimiter, stream, offset):
return True
return self.has_eof(stream) | python | def has_end(self, stream):
"""
EndStatement ::=
EndKeyword (SemiColon | WhiteSpace | Comment | EndProvidedOctetSeq)
"""
for token in self.end_tokens:
if not self.has_next(token, stream):
continue
offset = len(token)
if self.has_eof(stream, offset):
return True
if self.has_whitespace(stream, offset):
return True
if self.has_comment(stream, offset):
return True
if self.has_next(self.statement_delimiter, stream, offset):
return True
return self.has_eof(stream) | EndStatement ::=
EndKeyword (SemiColon | WhiteSpace | Comment | EndProvidedOctetSeq) | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/decoder.py#L352-L375 |
planetarypy/pvl | pvl/decoder.py | PVLDecoder.parse_group | def parse_group(self, stream):
"""Block Name must match Block Name in paired End Group Statement if
Block Name is present in End Group Statement.
BeginGroupStmt ::=
BeginGroupKeywd WSC AssignmentSymbol WSC BlockName StatementDelim
"""
self.expect_in(stream, self.begin_group_tokens)
self.ensure_assignment(stream)
name = self.next_token(stream)
self.skip_statement_delimiter(stream)
statements = self.parse_block(stream, self.has_end_group)
self.expect_in(stream, self.end_group_tokens)
self.parse_end_assignment(stream, name)
self.skip_statement_delimiter(stream)
return name.decode('utf-8'), PVLGroup(statements) | python | def parse_group(self, stream):
"""Block Name must match Block Name in paired End Group Statement if
Block Name is present in End Group Statement.
BeginGroupStmt ::=
BeginGroupKeywd WSC AssignmentSymbol WSC BlockName StatementDelim
"""
self.expect_in(stream, self.begin_group_tokens)
self.ensure_assignment(stream)
name = self.next_token(stream)
self.skip_statement_delimiter(stream)
statements = self.parse_block(stream, self.has_end_group)
self.expect_in(stream, self.end_group_tokens)
self.parse_end_assignment(stream, name)
self.skip_statement_delimiter(stream)
return name.decode('utf-8'), PVLGroup(statements) | Block Name must match Block Name in paired End Group Statement if
Block Name is present in End Group Statement.
BeginGroupStmt ::=
BeginGroupKeywd WSC AssignmentSymbol WSC BlockName StatementDelim | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/decoder.py#L402-L421 |
planetarypy/pvl | pvl/decoder.py | PVLDecoder.parse_object | def parse_object(self, stream):
"""Block Name must match Block Name in paired End Object Statement
if Block Name is present in End Object Statement StatementDelim.
BeginObjectStmt ::=
BeginObjectKeywd WSC AssignmentSymbol WSC BlockName StatementDelim
"""
self.expect_in(stream, self.begin_object_tokens)
self.ensure_assignment(stream)
name = self.next_token(stream)
self.skip_statement_delimiter(stream)
statements = self.parse_block(stream, self.has_end_object)
self.expect_in(stream, self.end_object_tokens)
self.parse_end_assignment(stream, name)
self.skip_statement_delimiter(stream)
return name.decode('utf-8'), PVLObject(statements) | python | def parse_object(self, stream):
"""Block Name must match Block Name in paired End Object Statement
if Block Name is present in End Object Statement StatementDelim.
BeginObjectStmt ::=
BeginObjectKeywd WSC AssignmentSymbol WSC BlockName StatementDelim
"""
self.expect_in(stream, self.begin_object_tokens)
self.ensure_assignment(stream)
name = self.next_token(stream)
self.skip_statement_delimiter(stream)
statements = self.parse_block(stream, self.has_end_object)
self.expect_in(stream, self.end_object_tokens)
self.parse_end_assignment(stream, name)
self.skip_statement_delimiter(stream)
return name.decode('utf-8'), PVLObject(statements) | Block Name must match Block Name in paired End Object Statement
if Block Name is present in End Object Statement StatementDelim.
BeginObjectStmt ::=
BeginObjectKeywd WSC AssignmentSymbol WSC BlockName StatementDelim | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/decoder.py#L433-L452 |
planetarypy/pvl | pvl/decoder.py | PVLDecoder.parse_assignment | def parse_assignment(self, stream):
"""
AssignmentStmt ::= Name WSC AssignmentSymbol WSC Value StatementDelim
"""
lineno = stream.lineno
name = self.next_token(stream)
self.ensure_assignment(stream)
at_an_end = any((
self.has_end_group(stream),
self.has_end_object(stream),
self.has_end(stream),
self.has_next(self.statement_delimiter, stream, 0)))
if at_an_end:
value = self.broken_assignment(lineno)
self.skip_whitespace_or_comment(stream)
else:
value = self.parse_value(stream)
self.skip_statement_delimiter(stream)
return name.decode('utf-8'), value | python | def parse_assignment(self, stream):
"""
AssignmentStmt ::= Name WSC AssignmentSymbol WSC Value StatementDelim
"""
lineno = stream.lineno
name = self.next_token(stream)
self.ensure_assignment(stream)
at_an_end = any((
self.has_end_group(stream),
self.has_end_object(stream),
self.has_end(stream),
self.has_next(self.statement_delimiter, stream, 0)))
if at_an_end:
value = self.broken_assignment(lineno)
self.skip_whitespace_or_comment(stream)
else:
value = self.parse_value(stream)
self.skip_statement_delimiter(stream)
return name.decode('utf-8'), value | AssignmentStmt ::= Name WSC AssignmentSymbol WSC Value StatementDelim | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/decoder.py#L469-L487 |
planetarypy/pvl | pvl/decoder.py | PVLDecoder.parse_value | def parse_value(self, stream):
"""
Value ::= (SimpleValue | Set | Sequence) WSC UnitsExpression?
"""
if self.has_sequence(stream):
value = self.parse_sequence(stream)
elif self.has_set(stream):
value = self.parse_set(stream)
else:
value = self.parse_simple_value(stream)
self.skip_whitespace_or_comment(stream)
if self.has_units(stream):
return Units(value, self.parse_units(stream))
return value | python | def parse_value(self, stream):
"""
Value ::= (SimpleValue | Set | Sequence) WSC UnitsExpression?
"""
if self.has_sequence(stream):
value = self.parse_sequence(stream)
elif self.has_set(stream):
value = self.parse_set(stream)
else:
value = self.parse_simple_value(stream)
self.skip_whitespace_or_comment(stream)
if self.has_units(stream):
return Units(value, self.parse_units(stream))
return value | Value ::= (SimpleValue | Set | Sequence) WSC UnitsExpression? | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/decoder.py#L489-L505 |
planetarypy/pvl | pvl/decoder.py | PVLDecoder.parse_iterable | def parse_iterable(self, stream, start, end):
"""
Sequence ::= SequenceStart WSC SequenceValue? WSC SequenceEnd
Set := SetStart WSC SequenceValue? WSC SetEnd
SequenceValue ::= Value (WSC SeparatorSymbol WSC Value)*
"""
values = []
self.expect(stream, start)
self.skip_whitespace_or_comment(stream)
if self.has_next(end, stream):
self.expect(stream, end)
return values
while 1:
self.skip_whitespace_or_comment(stream)
values.append(self.parse_value(stream))
self.skip_whitespace_or_comment(stream)
if self.has_next(end, stream):
self.expect(stream, end)
return values
self.expect(stream, self.seporator) | python | def parse_iterable(self, stream, start, end):
"""
Sequence ::= SequenceStart WSC SequenceValue? WSC SequenceEnd
Set := SetStart WSC SequenceValue? WSC SetEnd
SequenceValue ::= Value (WSC SeparatorSymbol WSC Value)*
"""
values = []
self.expect(stream, start)
self.skip_whitespace_or_comment(stream)
if self.has_next(end, stream):
self.expect(stream, end)
return values
while 1:
self.skip_whitespace_or_comment(stream)
values.append(self.parse_value(stream))
self.skip_whitespace_or_comment(stream)
if self.has_next(end, stream):
self.expect(stream, end)
return values
self.expect(stream, self.seporator) | Sequence ::= SequenceStart WSC SequenceValue? WSC SequenceEnd
Set := SetStart WSC SequenceValue? WSC SetEnd
SequenceValue ::= Value (WSC SeparatorSymbol WSC Value)* | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/decoder.py#L507-L531 |
planetarypy/pvl | pvl/decoder.py | PVLDecoder.parse_units | def parse_units(self, stream):
"""
UnitsExpression ::=
UnitsStart WhiteSpace* UnitsValue WhiteSpace* UnitsEnd
"""
value = b''
self.expect(stream, self.begin_units)
while not self.has_next(self.end_units, stream):
if self.has_eof(stream):
self.raise_unexpected_eof(stream)
value += stream.read(1)
self.expect(stream, self.end_units)
return value.strip(b''.join(self.whitespace)).decode('utf-8') | python | def parse_units(self, stream):
"""
UnitsExpression ::=
UnitsStart WhiteSpace* UnitsValue WhiteSpace* UnitsEnd
"""
value = b''
self.expect(stream, self.begin_units)
while not self.has_next(self.end_units, stream):
if self.has_eof(stream):
self.raise_unexpected_eof(stream)
value += stream.read(1)
self.expect(stream, self.end_units)
return value.strip(b''.join(self.whitespace)).decode('utf-8') | UnitsExpression ::=
UnitsStart WhiteSpace* UnitsValue WhiteSpace* UnitsEnd | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/decoder.py#L552-L566 |
planetarypy/pvl | pvl/decoder.py | PVLDecoder.parse_simple_value | def parse_simple_value(self, stream):
"""
SimpleValue ::= Integer
| FloatingPoint
| Exponential
| BinaryNum
| OctalNum
| HexadecimalNum
| DateTimeValue
| QuotedString
| UnquotedString
"""
if self.has_quoted_string(stream):
return self.parse_quoted_string(stream)
if self.has_binary_number(stream):
return self.parse_binary_number(stream)
if self.has_octal_number(stream):
return self.parse_octal_number(stream)
if self.has_decimal_number(stream):
return self.parse_decimal_number(stream)
if self.has_hex_number(stream):
return self.parse_hex_number(stream)
if self.has_unquoated_string(stream):
return self.parse_unquoated_string(stream)
if self.has_end(stream):
return self.broken_assignment(stream.lineno)
self.raise_unexpected(stream) | python | def parse_simple_value(self, stream):
"""
SimpleValue ::= Integer
| FloatingPoint
| Exponential
| BinaryNum
| OctalNum
| HexadecimalNum
| DateTimeValue
| QuotedString
| UnquotedString
"""
if self.has_quoted_string(stream):
return self.parse_quoted_string(stream)
if self.has_binary_number(stream):
return self.parse_binary_number(stream)
if self.has_octal_number(stream):
return self.parse_octal_number(stream)
if self.has_decimal_number(stream):
return self.parse_decimal_number(stream)
if self.has_hex_number(stream):
return self.parse_hex_number(stream)
if self.has_unquoated_string(stream):
return self.parse_unquoated_string(stream)
if self.has_end(stream):
return self.broken_assignment(stream.lineno)
self.raise_unexpected(stream) | SimpleValue ::= Integer
| FloatingPoint
| Exponential
| BinaryNum
| OctalNum
| HexadecimalNum
| DateTimeValue
| QuotedString
| UnquotedString | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/decoder.py#L568-L601 |
planetarypy/pvl | pvl/decoder.py | PVLDecoder.parse_radix | def parse_radix(self, radix, chars, stream):
"""
BinaryNum ::= [+-]? '2' RadixSymbol [0-1]+ RadixSymbol
OctalChar ::= [+-]? '8' RadixSymbol [0-7]+ RadixSymbol
HexadecimalNum ::= [+-]? '16' RadixSymbol [0-9a-zA-Z]+ RadixSymbol
"""
value = b''
sign = self.parse_sign(stream)
self.expect(stream, b(str(radix)) + self.radix_symbole)
sign *= self.parse_sign(stream)
while not self.has_next(self.radix_symbole, stream):
next = stream.read(1)
if not next:
self.raise_unexpected_eof(stream)
if next not in chars:
self.raise_unexpected(stream, next)
value += next
if not value:
self.raise_unexpected(stream, self.radix_symbole)
self.expect(stream, self.radix_symbole)
return sign * int(value, radix) | python | def parse_radix(self, radix, chars, stream):
"""
BinaryNum ::= [+-]? '2' RadixSymbol [0-1]+ RadixSymbol
OctalChar ::= [+-]? '8' RadixSymbol [0-7]+ RadixSymbol
HexadecimalNum ::= [+-]? '16' RadixSymbol [0-9a-zA-Z]+ RadixSymbol
"""
value = b''
sign = self.parse_sign(stream)
self.expect(stream, b(str(radix)) + self.radix_symbole)
sign *= self.parse_sign(stream)
while not self.has_next(self.radix_symbole, stream):
next = stream.read(1)
if not next:
self.raise_unexpected_eof(stream)
if next not in chars:
self.raise_unexpected(stream, next)
value += next
if not value:
self.raise_unexpected(stream, self.radix_symbole)
self.expect(stream, self.radix_symbole)
return sign * int(value, radix) | BinaryNum ::= [+-]? '2' RadixSymbol [0-1]+ RadixSymbol
OctalChar ::= [+-]? '8' RadixSymbol [0-7]+ RadixSymbol
HexadecimalNum ::= [+-]? '16' RadixSymbol [0-9a-zA-Z]+ RadixSymbol | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/decoder.py#L625-L650 |
BetterWorks/django-anonymizer | anonymizer/base.py | DjangoFaker.varchar | def varchar(self, field=None):
"""
Returns a chunk of text, of maximum length 'max_length'
"""
assert field is not None, "The field parameter must be passed to the 'varchar' method."
max_length = field.max_length
def source():
length = random.choice(range(1, max_length + 1))
return "".join(random.choice(general_chars) for i in xrange(length))
return self.get_allowed_value(source, field) | python | def varchar(self, field=None):
"""
Returns a chunk of text, of maximum length 'max_length'
"""
assert field is not None, "The field parameter must be passed to the 'varchar' method."
max_length = field.max_length
def source():
length = random.choice(range(1, max_length + 1))
return "".join(random.choice(general_chars) for i in xrange(length))
return self.get_allowed_value(source, field) | Returns a chunk of text, of maximum length 'max_length' | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/base.py#L80-L90 |
BetterWorks/django-anonymizer | anonymizer/base.py | DjangoFaker.simple_pattern | def simple_pattern(self, pattern, field=None):
"""
Use a simple pattern to make the field - # is replaced with a random number,
? with a random letter.
"""
return self.get_allowed_value(lambda: self.faker.bothify(pattern), field) | python | def simple_pattern(self, pattern, field=None):
"""
Use a simple pattern to make the field - # is replaced with a random number,
? with a random letter.
"""
return self.get_allowed_value(lambda: self.faker.bothify(pattern), field) | Use a simple pattern to make the field - # is replaced with a random number,
? with a random letter. | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/base.py#L92-L97 |
BetterWorks/django-anonymizer | anonymizer/base.py | DjangoFaker.datetime | def datetime(self, field=None, val=None):
"""
Returns a random datetime. If 'val' is passed, a datetime within two
years of that date will be returned.
"""
if val is None:
def source():
tzinfo = get_default_timezone() if settings.USE_TZ else None
return datetime.fromtimestamp(randrange(1, 2100000000),
tzinfo)
else:
def source():
tzinfo = get_default_timezone() if settings.USE_TZ else None
return datetime.fromtimestamp(int(val.strftime("%s")) +
randrange(-365*24*3600*2, 365*24*3600*2),
tzinfo)
return self.get_allowed_value(source, field) | python | def datetime(self, field=None, val=None):
"""
Returns a random datetime. If 'val' is passed, a datetime within two
years of that date will be returned.
"""
if val is None:
def source():
tzinfo = get_default_timezone() if settings.USE_TZ else None
return datetime.fromtimestamp(randrange(1, 2100000000),
tzinfo)
else:
def source():
tzinfo = get_default_timezone() if settings.USE_TZ else None
return datetime.fromtimestamp(int(val.strftime("%s")) +
randrange(-365*24*3600*2, 365*24*3600*2),
tzinfo)
return self.get_allowed_value(source, field) | Returns a random datetime. If 'val' is passed, a datetime within two
years of that date will be returned. | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/base.py#L117-L133 |
BetterWorks/django-anonymizer | anonymizer/base.py | DjangoFaker.date | def date(self, field=None, val=None):
"""
Like datetime, but truncated to be a date only
"""
return self.datetime(field=field, val=val).date() | python | def date(self, field=None, val=None):
"""
Like datetime, but truncated to be a date only
"""
return self.datetime(field=field, val=val).date() | Like datetime, but truncated to be a date only | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/base.py#L135-L139 |
BetterWorks/django-anonymizer | anonymizer/base.py | DjangoFaker.lorem | def lorem(self, field=None, val=None):
"""
Returns lorem ipsum text. If val is provided, the lorem ipsum text will
be the same length as the original text, and with the same pattern of
line breaks.
"""
if val == '':
return ''
if val is not None:
def generate(length):
# Get lorem ipsum of a specific length.
collect = ""
while len(collect) < length:
collect += ' %s' % self.faker.sentence()
collect = collect[:length]
return collect
# We want to match the pattern of the text - linebreaks
# in the same places.
def source():
parts = val.split("\n")
for i, p in enumerate(parts):
# Replace each bit with lorem ipsum of the same length
parts[i] = generate(len(p))
return "\n".join(parts)
else:
def source():
return ' '.join(self.faker.sentences())
return self.get_allowed_value(source, field) | python | def lorem(self, field=None, val=None):
"""
Returns lorem ipsum text. If val is provided, the lorem ipsum text will
be the same length as the original text, and with the same pattern of
line breaks.
"""
if val == '':
return ''
if val is not None:
def generate(length):
# Get lorem ipsum of a specific length.
collect = ""
while len(collect) < length:
collect += ' %s' % self.faker.sentence()
collect = collect[:length]
return collect
# We want to match the pattern of the text - linebreaks
# in the same places.
def source():
parts = val.split("\n")
for i, p in enumerate(parts):
# Replace each bit with lorem ipsum of the same length
parts[i] = generate(len(p))
return "\n".join(parts)
else:
def source():
return ' '.join(self.faker.sentences())
return self.get_allowed_value(source, field) | Returns lorem ipsum text. If val is provided, the lorem ipsum text will
be the same length as the original text, and with the same pattern of
line breaks. | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/base.py#L152-L181 |
BetterWorks/django-anonymizer | anonymizer/base.py | DjangoFaker.unique_lorem | def unique_lorem(self, field=None, val=None):
"""
Returns lorem ipsum text guaranteed to be unique. First uses lorem function
then adds a unique integer suffix.
"""
lorem_text = self.lorem(field, val)
max_length = getattr(field, 'max_length', None)
suffix_str = str(self.unique_suffixes[field])
unique_text = lorem_text + suffix_str
if max_length is not None:
# take the last max_length chars
unique_text = unique_text[-max_length:]
self.unique_suffixes[field] += 1
return unique_text | python | def unique_lorem(self, field=None, val=None):
"""
Returns lorem ipsum text guaranteed to be unique. First uses lorem function
then adds a unique integer suffix.
"""
lorem_text = self.lorem(field, val)
max_length = getattr(field, 'max_length', None)
suffix_str = str(self.unique_suffixes[field])
unique_text = lorem_text + suffix_str
if max_length is not None:
# take the last max_length chars
unique_text = unique_text[-max_length:]
self.unique_suffixes[field] += 1
return unique_text | Returns lorem ipsum text guaranteed to be unique. First uses lorem function
then adds a unique integer suffix. | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/base.py#L183-L197 |
BetterWorks/django-anonymizer | anonymizer/base.py | Anonymizer.alter_object | def alter_object(self, obj):
"""
Alters all the attributes in an individual object.
If it returns False, the object will not be saved
"""
for attname, field, replacer in self.replacers:
currentval = getattr(obj, attname)
replacement = replacer(self, obj, field, currentval)
setattr(obj, attname, replacement) | python | def alter_object(self, obj):
"""
Alters all the attributes in an individual object.
If it returns False, the object will not be saved
"""
for attname, field, replacer in self.replacers:
currentval = getattr(obj, attname)
replacement = replacer(self, obj, field, currentval)
setattr(obj, attname, replacement) | Alters all the attributes in an individual object.
If it returns False, the object will not be saved | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/base.py#L289-L298 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | uuid | def uuid(anon, obj, field, val):
"""
Returns a random uuid string
"""
return anon.faker.uuid(field=field) | python | def uuid(anon, obj, field, val):
"""
Returns a random uuid string
"""
return anon.faker.uuid(field=field) | Returns a random uuid string | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L4-L8 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | varchar | def varchar(anon, obj, field, val):
"""
Returns random data for a varchar field.
"""
return anon.faker.varchar(field=field) | python | def varchar(anon, obj, field, val):
"""
Returns random data for a varchar field.
"""
return anon.faker.varchar(field=field) | Returns random data for a varchar field. | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L11-L15 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | bool | def bool(anon, obj, field, val):
"""
Returns a random boolean value (True/False)
"""
return anon.faker.bool(field=field) | python | def bool(anon, obj, field, val):
"""
Returns a random boolean value (True/False)
"""
return anon.faker.bool(field=field) | Returns a random boolean value (True/False) | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L18-L22 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | integer | def integer(anon, obj, field, val):
"""
Returns a random integer (for a Django IntegerField)
"""
return anon.faker.integer(field=field) | python | def integer(anon, obj, field, val):
"""
Returns a random integer (for a Django IntegerField)
"""
return anon.faker.integer(field=field) | Returns a random integer (for a Django IntegerField) | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L25-L29 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | positive_integer | def positive_integer(anon, obj, field, val):
"""
Returns a random positive integer (for a Django PositiveIntegerField)
"""
return anon.faker.positive_integer(field=field) | python | def positive_integer(anon, obj, field, val):
"""
Returns a random positive integer (for a Django PositiveIntegerField)
"""
return anon.faker.positive_integer(field=field) | Returns a random positive integer (for a Django PositiveIntegerField) | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L32-L36 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | small_integer | def small_integer(anon, obj, field, val):
"""
Returns a random small integer (for a Django SmallIntegerField)
"""
return anon.faker.small_integer(field=field) | python | def small_integer(anon, obj, field, val):
"""
Returns a random small integer (for a Django SmallIntegerField)
"""
return anon.faker.small_integer(field=field) | Returns a random small integer (for a Django SmallIntegerField) | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L39-L43 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | positive_small_integer | def positive_small_integer(anon, obj, field, val):
"""
Returns a positive small random integer (for a Django PositiveSmallIntegerField)
"""
return anon.faker.positive_small_integer(field=field) | python | def positive_small_integer(anon, obj, field, val):
"""
Returns a positive small random integer (for a Django PositiveSmallIntegerField)
"""
return anon.faker.positive_small_integer(field=field) | Returns a positive small random integer (for a Django PositiveSmallIntegerField) | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L46-L50 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | datetime | def datetime(anon, obj, field, val):
"""
Returns a random datetime
"""
return anon.faker.datetime(field=field) | python | def datetime(anon, obj, field, val):
"""
Returns a random datetime
"""
return anon.faker.datetime(field=field) | Returns a random datetime | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L53-L57 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | date | def date(anon, obj, field, val):
"""
Returns a random date
"""
return anon.faker.date(field=field) | python | def date(anon, obj, field, val):
"""
Returns a random date
"""
return anon.faker.date(field=field) | Returns a random date | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L60-L64 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | decimal | def decimal(anon, obj, field, val):
"""
Returns a random decimal
"""
return anon.faker.decimal(field=field) | python | def decimal(anon, obj, field, val):
"""
Returns a random decimal
"""
return anon.faker.decimal(field=field) | Returns a random decimal | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L67-L71 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | postcode | def postcode(anon, obj, field, val):
"""
Generates a random postcode (not necessarily valid, but it will look like one).
"""
return anon.faker.postcode(field=field) | python | def postcode(anon, obj, field, val):
"""
Generates a random postcode (not necessarily valid, but it will look like one).
"""
return anon.faker.postcode(field=field) | Generates a random postcode (not necessarily valid, but it will look like one). | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L74-L78 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | country | def country(anon, obj, field, val):
"""
Returns a randomly selected country.
"""
return anon.faker.country(field=field) | python | def country(anon, obj, field, val):
"""
Returns a randomly selected country.
"""
return anon.faker.country(field=field) | Returns a randomly selected country. | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L81-L85 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | username | def username(anon, obj, field, val):
"""
Generates a random username
"""
return anon.faker.user_name(field=field) | python | def username(anon, obj, field, val):
"""
Generates a random username
"""
return anon.faker.user_name(field=field) | Generates a random username | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L88-L92 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | first_name | def first_name(anon, obj, field, val):
"""
Returns a random first name
"""
return anon.faker.first_name(field=field) | python | def first_name(anon, obj, field, val):
"""
Returns a random first name
"""
return anon.faker.first_name(field=field) | Returns a random first name | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L95-L99 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | last_name | def last_name(anon, obj, field, val):
"""
Returns a random second name
"""
return anon.faker.last_name(field=field) | python | def last_name(anon, obj, field, val):
"""
Returns a random second name
"""
return anon.faker.last_name(field=field) | Returns a random second name | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L102-L106 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | name | def name(anon, obj, field, val):
"""
Generates a random full name (using first name and last name)
"""
return anon.faker.name(field=field) | python | def name(anon, obj, field, val):
"""
Generates a random full name (using first name and last name)
"""
return anon.faker.name(field=field) | Generates a random full name (using first name and last name) | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L109-L113 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | email | def email(anon, obj, field, val):
"""
Generates a random email address.
"""
return anon.faker.email(field=field) | python | def email(anon, obj, field, val):
"""
Generates a random email address.
"""
return anon.faker.email(field=field) | Generates a random email address. | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L116-L120 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | similar_email | def similar_email(anon, obj, field, val):
"""
Generate a random email address using the same domain.
"""
return val if 'betterworks.com' in val else '@'.join([anon.faker.user_name(field=field), val.split('@')[-1]]) | python | def similar_email(anon, obj, field, val):
"""
Generate a random email address using the same domain.
"""
return val if 'betterworks.com' in val else '@'.join([anon.faker.user_name(field=field), val.split('@')[-1]]) | Generate a random email address using the same domain. | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L123-L127 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | full_address | def full_address(anon, obj, field, val):
"""
Generates a random full address, using newline characters between the lines.
Resembles a US address
"""
return anon.faker.address(field=field) | python | def full_address(anon, obj, field, val):
"""
Generates a random full address, using newline characters between the lines.
Resembles a US address
"""
return anon.faker.address(field=field) | Generates a random full address, using newline characters between the lines.
Resembles a US address | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L130-L135 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | phonenumber | def phonenumber(anon, obj, field, val):
"""
Generates a random US-style phone number
"""
return anon.faker.phone_number(field=field) | python | def phonenumber(anon, obj, field, val):
"""
Generates a random US-style phone number
"""
return anon.faker.phone_number(field=field) | Generates a random US-style phone number | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L138-L142 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | street_address | def street_address(anon, obj, field, val):
"""
Generates a random street address - the first line of a full address
"""
return anon.faker.street_address(field=field) | python | def street_address(anon, obj, field, val):
"""
Generates a random street address - the first line of a full address
"""
return anon.faker.street_address(field=field) | Generates a random street address - the first line of a full address | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L145-L149 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | city | def city(anon, obj, field, val):
"""
Generates a random city name. Resembles the name of US/UK city.
"""
return anon.faker.city(field=field) | python | def city(anon, obj, field, val):
"""
Generates a random city name. Resembles the name of US/UK city.
"""
return anon.faker.city(field=field) | Generates a random city name. Resembles the name of US/UK city. | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L152-L156 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | state | def state(anon, obj, field, val):
"""
Returns a randomly selected US state code
"""
return anon.faker.state(field=field) | python | def state(anon, obj, field, val):
"""
Returns a randomly selected US state code
"""
return anon.faker.state(field=field) | Returns a randomly selected US state code | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L159-L163 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | zip_code | def zip_code(anon, obj, field, val):
"""
Returns a randomly generated US zip code (not necessarily valid, but will look like one).
"""
return anon.faker.zipcode(field=field) | python | def zip_code(anon, obj, field, val):
"""
Returns a randomly generated US zip code (not necessarily valid, but will look like one).
"""
return anon.faker.zipcode(field=field) | Returns a randomly generated US zip code (not necessarily valid, but will look like one). | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L166-L170 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | company | def company(anon, obj, field, val):
"""
Generates a random company name
"""
return anon.faker.company(field=field) | python | def company(anon, obj, field, val):
"""
Generates a random company name
"""
return anon.faker.company(field=field) | Generates a random company name | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L173-L177 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | lorem | def lorem(anon, obj, field, val):
"""
Generates a paragraph of lorem ipsum text
"""
return ' '.join(anon.faker.sentences(field=field)) | python | def lorem(anon, obj, field, val):
"""
Generates a paragraph of lorem ipsum text
"""
return ' '.join(anon.faker.sentences(field=field)) | Generates a paragraph of lorem ipsum text | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L180-L184 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | unique_lorem | def unique_lorem(anon, obj, field, val):
"""
Generates a unique paragraph of lorem ipsum text
"""
return anon.faker.unique_lorem(field=field) | python | def unique_lorem(anon, obj, field, val):
"""
Generates a unique paragraph of lorem ipsum text
"""
return anon.faker.unique_lorem(field=field) | Generates a unique paragraph of lorem ipsum text | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L187-L191 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | similar_datetime | def similar_datetime(anon, obj, field, val):
"""
Returns a datetime that is within plus/minus two years of the original datetime
"""
return anon.faker.datetime(field=field, val=val) | python | def similar_datetime(anon, obj, field, val):
"""
Returns a datetime that is within plus/minus two years of the original datetime
"""
return anon.faker.datetime(field=field, val=val) | Returns a datetime that is within plus/minus two years of the original datetime | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L194-L198 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | similar_date | def similar_date(anon, obj, field, val):
"""
Returns a date that is within plus/minus two years of the original date
"""
return anon.faker.date(field=field, val=val) | python | def similar_date(anon, obj, field, val):
"""
Returns a date that is within plus/minus two years of the original date
"""
return anon.faker.date(field=field, val=val) | Returns a date that is within plus/minus two years of the original date | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L201-L205 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | similar_lorem | def similar_lorem(anon, obj, field, val):
"""
Generates lorem ipsum text with the same length and same pattern of linebreaks
as the original. If the original often takes a standard form (e.g. a single word
'yes' or 'no'), this could easily fail to hide the original data.
"""
return anon.faker.lorem(field=field, val=val) | python | def similar_lorem(anon, obj, field, val):
"""
Generates lorem ipsum text with the same length and same pattern of linebreaks
as the original. If the original often takes a standard form (e.g. a single word
'yes' or 'no'), this could easily fail to hide the original data.
"""
return anon.faker.lorem(field=field, val=val) | Generates lorem ipsum text with the same length and same pattern of linebreaks
as the original. If the original often takes a standard form (e.g. a single word
'yes' or 'no'), this could easily fail to hide the original data. | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L208-L214 |
BetterWorks/django-anonymizer | anonymizer/replacers.py | choice | def choice(anon, obj, field, val):
"""
Randomly chooses one of the choices set on the field.
"""
return anon.faker.choice(field=field) | python | def choice(anon, obj, field, val):
"""
Randomly chooses one of the choices set on the field.
"""
return anon.faker.choice(field=field) | Randomly chooses one of the choices set on the field. | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L217-L221 |
planetarypy/pvl | pvl/__init__.py | load | def load(stream, cls=PVLDecoder, strict=True, **kwargs):
"""Deserialize ``stream`` as a pvl module.
:param stream: a ``.read()``-supporting file-like object containing a
module. If ``stream`` is a string it will be treated as a filename
:param cls: the decoder class used to deserialize the pvl module. You may
use the default ``PVLDecoder`` class or provide a custom sublcass.
:param **kwargs: the keyword arguments to pass to the decoder class.
"""
decoder = __create_decoder(cls, strict, **kwargs)
if isinstance(stream, six.string_types):
with open(stream, 'rb') as fp:
return decoder.decode(fp)
return decoder.decode(stream) | python | def load(stream, cls=PVLDecoder, strict=True, **kwargs):
"""Deserialize ``stream`` as a pvl module.
:param stream: a ``.read()``-supporting file-like object containing a
module. If ``stream`` is a string it will be treated as a filename
:param cls: the decoder class used to deserialize the pvl module. You may
use the default ``PVLDecoder`` class or provide a custom sublcass.
:param **kwargs: the keyword arguments to pass to the decoder class.
"""
decoder = __create_decoder(cls, strict, **kwargs)
if isinstance(stream, six.string_types):
with open(stream, 'rb') as fp:
return decoder.decode(fp)
return decoder.decode(stream) | Deserialize ``stream`` as a pvl module.
:param stream: a ``.read()``-supporting file-like object containing a
module. If ``stream`` is a string it will be treated as a filename
:param cls: the decoder class used to deserialize the pvl module. You may
use the default ``PVLDecoder`` class or provide a custom sublcass.
:param **kwargs: the keyword arguments to pass to the decoder class. | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/__init__.py#L82-L97 |
planetarypy/pvl | pvl/__init__.py | loads | def loads(data, cls=PVLDecoder, strict=True, **kwargs):
"""Deserialize ``data`` as a pvl module.
:param data: a pvl module as a byte or unicode string
:param cls: the decoder class used to deserialize the pvl module. You may
use the default ``PVLDecoder`` class or provide a custom sublcass.
:param **kwargs: the keyword arguments to pass to the decoder class.
"""
decoder = __create_decoder(cls, strict, **kwargs)
if not isinstance(data, bytes):
data = data.encode('utf-8')
return decoder.decode(data) | python | def loads(data, cls=PVLDecoder, strict=True, **kwargs):
"""Deserialize ``data`` as a pvl module.
:param data: a pvl module as a byte or unicode string
:param cls: the decoder class used to deserialize the pvl module. You may
use the default ``PVLDecoder`` class or provide a custom sublcass.
:param **kwargs: the keyword arguments to pass to the decoder class.
"""
decoder = __create_decoder(cls, strict, **kwargs)
if not isinstance(data, bytes):
data = data.encode('utf-8')
return decoder.decode(data) | Deserialize ``data`` as a pvl module.
:param data: a pvl module as a byte or unicode string
:param cls: the decoder class used to deserialize the pvl module. You may
use the default ``PVLDecoder`` class or provide a custom sublcass.
:param **kwargs: the keyword arguments to pass to the decoder class. | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/__init__.py#L100-L113 |
planetarypy/pvl | pvl/__init__.py | dump | def dump(module, stream, cls=PVLEncoder, **kwargs):
"""Serialize ``module`` as a pvl module to the provided ``stream``.
:param module: a ```PVLModule``` or ```dict``` like object to serialize
:param stream: a ``.write()``-supporting file-like object to serialize the
module to. If ``stream`` is a string it will be treated as a filename
:param cls: the encoder class used to serialize the pvl module. You may use
the default ``PVLEncoder`` class or provided encoder formats such as the
```IsisCubeLabelEncoder``` and ```PDSLabelEncoder``` classes. You may
also provided a custom sublcass of ```PVLEncoder```
:param **kwargs: the keyword arguments to pass to the encoder class.
"""
if isinstance(stream, six.string_types):
with open(stream, 'wb') as fp:
return cls(**kwargs).encode(module, fp)
cls(**kwargs).encode(module, stream) | python | def dump(module, stream, cls=PVLEncoder, **kwargs):
"""Serialize ``module`` as a pvl module to the provided ``stream``.
:param module: a ```PVLModule``` or ```dict``` like object to serialize
:param stream: a ``.write()``-supporting file-like object to serialize the
module to. If ``stream`` is a string it will be treated as a filename
:param cls: the encoder class used to serialize the pvl module. You may use
the default ``PVLEncoder`` class or provided encoder formats such as the
```IsisCubeLabelEncoder``` and ```PDSLabelEncoder``` classes. You may
also provided a custom sublcass of ```PVLEncoder```
:param **kwargs: the keyword arguments to pass to the encoder class.
"""
if isinstance(stream, six.string_types):
with open(stream, 'wb') as fp:
return cls(**kwargs).encode(module, fp)
cls(**kwargs).encode(module, stream) | Serialize ``module`` as a pvl module to the provided ``stream``.
:param module: a ```PVLModule``` or ```dict``` like object to serialize
:param stream: a ``.write()``-supporting file-like object to serialize the
module to. If ``stream`` is a string it will be treated as a filename
:param cls: the encoder class used to serialize the pvl module. You may use
the default ``PVLEncoder`` class or provided encoder formats such as the
```IsisCubeLabelEncoder``` and ```PDSLabelEncoder``` classes. You may
also provided a custom sublcass of ```PVLEncoder```
:param **kwargs: the keyword arguments to pass to the encoder class. | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/__init__.py#L116-L134 |
planetarypy/pvl | pvl/__init__.py | dumps | def dumps(module, cls=PVLEncoder, **kwargs):
"""Serialize ``module`` as a pvl module formated byte string.
:param module: a ```PVLModule``` or ```dict``` like object to serialize
:param cls: the encoder class used to serialize the pvl module. You may use
the default ``PVLEncoder`` class or provided encoder formats such as the
```IsisCubeLabelEncoder``` and ```PDSLabelEncoder``` classes. You may
also provided a custom sublcass of ```PVLEncoder```
:param **kwargs: the keyword arguments to pass to the encoder class.
:returns: a byte string encoding of the pvl module
"""
stream = io.BytesIO()
cls(**kwargs).encode(module, stream)
return stream.getvalue() | python | def dumps(module, cls=PVLEncoder, **kwargs):
"""Serialize ``module`` as a pvl module formated byte string.
:param module: a ```PVLModule``` or ```dict``` like object to serialize
:param cls: the encoder class used to serialize the pvl module. You may use
the default ``PVLEncoder`` class or provided encoder formats such as the
```IsisCubeLabelEncoder``` and ```PDSLabelEncoder``` classes. You may
also provided a custom sublcass of ```PVLEncoder```
:param **kwargs: the keyword arguments to pass to the encoder class.
:returns: a byte string encoding of the pvl module
"""
stream = io.BytesIO()
cls(**kwargs).encode(module, stream)
return stream.getvalue() | Serialize ``module`` as a pvl module formated byte string.
:param module: a ```PVLModule``` or ```dict``` like object to serialize
:param cls: the encoder class used to serialize the pvl module. You may use
the default ``PVLEncoder`` class or provided encoder formats such as the
```IsisCubeLabelEncoder``` and ```PDSLabelEncoder``` classes. You may
also provided a custom sublcass of ```PVLEncoder```
:param **kwargs: the keyword arguments to pass to the encoder class.
:returns: a byte string encoding of the pvl module | https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/__init__.py#L137-L153 |
pycampers/zproc | zproc/state/_type.py | _create_remote_dict_method | def _create_remote_dict_method(dict_method_name: str):
"""
Generates a method for the State class,
that will call the "method_name" on the state (a ``dict``) stored on the server,
and return the result.
Glorified RPC.
"""
def remote_method(self, *args, **kwargs):
return self._s_request_reply(
{
Msgs.cmd: Cmds.run_dict_method,
Msgs.info: dict_method_name,
Msgs.args: args,
Msgs.kwargs: kwargs,
}
)
remote_method.__name__ = dict_method_name
return remote_method | python | def _create_remote_dict_method(dict_method_name: str):
"""
Generates a method for the State class,
that will call the "method_name" on the state (a ``dict``) stored on the server,
and return the result.
Glorified RPC.
"""
def remote_method(self, *args, **kwargs):
return self._s_request_reply(
{
Msgs.cmd: Cmds.run_dict_method,
Msgs.info: dict_method_name,
Msgs.args: args,
Msgs.kwargs: kwargs,
}
)
remote_method.__name__ = dict_method_name
return remote_method | Generates a method for the State class,
that will call the "method_name" on the state (a ``dict``) stored on the server,
and return the result.
Glorified RPC. | https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/state/_type.py#L21-L41 |
pycampers/zproc | zproc/state/server.py | StateServer.run_dict_method | def run_dict_method(self, request):
"""Execute a method on the state ``dict`` and reply with the result."""
state_method_name, args, kwargs = (
request[Msgs.info],
request[Msgs.args],
request[Msgs.kwargs],
)
# print(method_name, args, kwargs)
with self.mutate_safely():
self.reply(getattr(self.state, state_method_name)(*args, **kwargs)) | python | def run_dict_method(self, request):
"""Execute a method on the state ``dict`` and reply with the result."""
state_method_name, args, kwargs = (
request[Msgs.info],
request[Msgs.args],
request[Msgs.kwargs],
)
# print(method_name, args, kwargs)
with self.mutate_safely():
self.reply(getattr(self.state, state_method_name)(*args, **kwargs)) | Execute a method on the state ``dict`` and reply with the result. | https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/state/server.py#L72-L81 |
pycampers/zproc | zproc/state/server.py | StateServer.run_fn_atomically | def run_fn_atomically(self, request):
"""Execute a function, atomically and reply with the result."""
fn = serializer.loads_fn(request[Msgs.info])
args, kwargs = request[Msgs.args], request[Msgs.kwargs]
with self.mutate_safely():
self.reply(fn(self.state, *args, **kwargs)) | python | def run_fn_atomically(self, request):
"""Execute a function, atomically and reply with the result."""
fn = serializer.loads_fn(request[Msgs.info])
args, kwargs = request[Msgs.args], request[Msgs.kwargs]
with self.mutate_safely():
self.reply(fn(self.state, *args, **kwargs)) | Execute a function, atomically and reply with the result. | https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/state/server.py#L83-L88 |
pycampers/zproc | zproc/util.py | clean_process_tree | def clean_process_tree(*signal_handler_args):
"""Stop all Processes in the current Process tree, recursively."""
parent = psutil.Process()
procs = parent.children(recursive=True)
if procs:
print(f"[ZProc] Cleaning up {parent.name()!r} ({os.getpid()})...")
for p in procs:
with suppress(psutil.NoSuchProcess):
p.terminate()
_, alive = psutil.wait_procs(procs, timeout=0.5) # 0.5 seems to work
for p in alive:
with suppress(psutil.NoSuchProcess):
p.kill()
try:
signum = signal_handler_args[0]
except IndexError:
pass
else:
os._exit(signum) | python | def clean_process_tree(*signal_handler_args):
"""Stop all Processes in the current Process tree, recursively."""
parent = psutil.Process()
procs = parent.children(recursive=True)
if procs:
print(f"[ZProc] Cleaning up {parent.name()!r} ({os.getpid()})...")
for p in procs:
with suppress(psutil.NoSuchProcess):
p.terminate()
_, alive = psutil.wait_procs(procs, timeout=0.5) # 0.5 seems to work
for p in alive:
with suppress(psutil.NoSuchProcess):
p.kill()
try:
signum = signal_handler_args[0]
except IndexError:
pass
else:
os._exit(signum) | Stop all Processes in the current Process tree, recursively. | https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/util.py#L109-L129 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.