Python builtins.property() Examples
The following are 24
code examples of builtins.property().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
builtins
, or try the search function
.
Example #1
Source File: entities.py From python-mip with Eclipse Public License 2.0 | 6 votes |
def violation(self): """Amount that current solution violates this constraint If a solution is available, than this property indicates how much the current solution violates this constraint. """ lhs = sum(coef * var.x for (var, coef) in self.__expr.items()) rhs = -self.const if self.sense == "=": viol = abs(lhs - rhs) elif self.sense == "<": viol = max(lhs - rhs, 0.0) elif self.sense == ">": viol = max(rhs - lhs, 0.0) else: raise ValueError("Invalid sense {}".format(self.sense)) return viol
Example #2
Source File: __init__.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 6 votes |
def clone_properties(self, src, proplist=None): '''Clone properties from other object. :param PropertyHolder src: source object :param iterable proplist: list of properties \ (:py:obj:`None` or omit for all properties except those with \ :py:attr:`property.clone` set to :py:obj:`False`) ''' if proplist is None: proplist = [prop for prop in self.property_list() if prop.clone] else: proplist = [prop for prop in self.property_list() if prop.__name__ in proplist or prop in proplist] for prop in proplist: try: # pylint: disable=protected-access self._property_init(prop, getattr(src, prop._attr_name)) except AttributeError: continue self.fire_event('clone-properties', src=src, proplist=proplist)
Example #3
Source File: __init__.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 6 votes |
def load_properties(self, load_stage=None): '''Load properties from immediate children of XML node. ``property-set`` events are not fired for each individual property. :param int load_stage: Stage of loading. ''' if self.xml is None: return all_names = set( prop.__name__ for prop in self.property_list(load_stage)) for node in self.xml.xpath('./properties/property'): name = node.get('name') value = node.get('ref') or node.text if not name in all_names: continue setattr(self, name, value)
Example #4
Source File: __init__.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 6 votes |
def property_get_def(cls, prop): '''Return property definition object. If prop is already :py:class:`qubes.property` instance, return the same object. :param prop: property object or name :type prop: qubes.property or str :rtype: qubes.property ''' if isinstance(prop, qubes.property): return prop props = cls.property_dict() if prop in props: return props[prop] raise AttributeError('No property {!r} found in {!r}'.format( prop, cls))
Example #5
Source File: __init__.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 6 votes |
def property_is_default(self, prop): '''Check whether property is in it's default value. Properties when unset may return some default value, so ``hasattr(vm, prop.__name__)`` is wrong in some circumstances. This method allows for checking if the value returned is in fact it's default value. :param qubes.property prop: property object of particular interest :rtype: bool ''' # pylint: disable=protected-access # both property_get_def() and ._attr_name may throw AttributeError, # which we don't want to catch attrname = self.property_get_def(prop)._attr_name return not hasattr(self, attrname)
Example #6
Source File: __init__.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 6 votes |
def __init__(self, name, setter=None, saver=None, type=None, default=_NO_DEFAULT, write_once=False, load_stage=2, order=0, save_via_ref=False, clone=True, doc=None): # pylint: disable=redefined-builtin self.__name__ = name if setter is None and type is bool: setter = qubes.property.bool self._setter = setter self._saver = saver if saver is not None else ( lambda self, prop, value: str(value)) self.type = type self._default = default self._default_function = None if isinstance(default, collections.abc.Callable): self._default_function = default self._write_once = write_once self.order = order self.load_stage = load_stage self.save_via_ref = save_via_ref self.clone = clone self.__doc__ = doc self._attr_name = '_qubesprop_' + name
Example #7
Source File: __init__.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 5 votes |
def property_dict(cls, load_stage=None): '''List all properties attached to this VM's class :param load_stage: Filter by load stage :type load_stage: :py:func:`int` or :py:obj:`None` ''' # use cls.__dict__ since we must not look at parent classes if "_property_dict" not in cls.__dict__: cls._property_dict = {} memo = cls._property_dict if load_stage not in memo: props = dict() if load_stage is None: for class_ in cls.__mro__: for name in class_.__dict__: # don't overwrite props with those from base classes if name not in props: prop = class_.__dict__[name] if isinstance(prop, property): assert name == prop.__name__ props[name] = prop else: for prop in cls.property_dict().values(): if prop.load_stage == load_stage: props[prop.__name__] = prop memo[load_stage] = props return memo[load_stage]
Example #8
Source File: compile.py From citrix-adc-ansible-modules with GNU General Public License v3.0 | 5 votes |
def produce_immutables_list(json_doc): immutables_list = [] for property in json_doc: # Add only readonly attributes if not property['is_updateable']: immutables_list.append(property['option_name']) return immutables_list
Example #9
Source File: compile.py From citrix-adc-ansible-modules with GNU General Public License v3.0 | 5 votes |
def produce_readwrite_attrs_list(json_doc): readwrite_attrs = list() for property in json_doc: readwrite_attrs .append(property['option_name']) return readwrite_attrs
Example #10
Source File: compile.py From citrix-adc-ansible-modules with GNU General Public License v3.0 | 5 votes |
def produce_module_arguments_from_json_schema(json_doc, skip_attrs): module_arguments = list() for property in json_doc: # Skip attributes in skip_attrs if property['option_name'] in skip_attrs: continue key = property['option_name'] entry = {} entry['key'] = key entry['transforms'] = [] # Convert json type to ansible module argument type declaration entry['type'] = property['type'] # Add choices if applicable if 'choices' in property: choice_set = frozenset([choice.lower() for choice in property['choices']]) if choice_set == frozenset(['yes', 'no']): # Overwrite type to bool entry['type'] = 'bool' entry['transforms'] = ['bool_yes_no'] elif choice_set == frozenset(['on', 'off']): # Overwrite type to bool entry['type'] = 'bool' entry['transforms'] = ['bool_on_off'] elif choice_set == frozenset(['enabled', 'disabled']): entry['choices'] = ['enabled', 'disabled'] else: entry['choices'] = property['choices'] # Add to ansible modules argument module_arguments.append(entry) return module_arguments
Example #11
Source File: __init__.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 5 votes |
def property_require(self, prop, allow_none=False, hard=False): '''Complain badly when property is not set. :param prop: property name or object :type prop: qubes.property or str :param bool allow_none: if :py:obj:`True`, don't complain if \ :py:obj:`None` is found :param bool hard: if :py:obj:`True`, raise :py:class:`AssertionError`; \ if :py:obj:`False`, log warning instead ''' if isinstance(prop, qubes.property): prop = prop.__name__ try: value = getattr(self, prop) if value is None and not allow_none: msg = 'Property {!r} cannot be None'.format(prop) if hard: raise ValueError(msg) self.log.fatal(msg) except AttributeError: # pylint: disable=no-member msg = 'Required property {!r} not set on {!r}'.format(prop, self) if hard: raise ValueError(msg) # pylint: disable=no-member self.log.fatal(msg)
Example #12
Source File: __init__.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 5 votes |
def xml_properties(self, with_defaults=False): '''Iterator that yields XML nodes representing set properties. :param bool with_defaults: If :py:obj:`True`, then it also includes \ properties which were not set explicite, but have default values \ filled. ''' properties = lxml.etree.Element('properties') for prop in self.property_list(): # pylint: disable=protected-access try: value = getattr( self, (prop.__name__ if with_defaults else prop._attr_name)) except AttributeError: continue try: value = prop._saver(self, prop, value) except property.DontSave: continue element = lxml.etree.Element('property', name=prop.__name__) if prop.save_via_ref: element.set('ref', value) else: element.text = value properties.append(element) return properties # this was clone_attrs
Example #13
Source File: __init__.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 5 votes |
def _property_init(self, prop, value): '''Initialise property to a given value, without side effects. :param qubes.property prop: property object of particular interest :param value: value ''' # pylint: disable=protected-access setattr(self, self.property_get_def(prop)._attr_name, value)
Example #14
Source File: __init__.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 5 votes |
def __init__(self, xml, **kwargs): self.xml = xml propvalues = {} all_names = self.property_dict() for key in list(kwargs): if not key in all_names: continue propvalues[key] = kwargs.pop(key) super(PropertyHolder, self).__init__(**kwargs) for key, value in propvalues.items(): setattr(self, key, value) if self.xml is not None: # check if properties are appropriate for node in self.xml.xpath('./properties/property'): name = node.get('name') if name not in all_names: raise TypeError( 'property {!r} not applicable to {!r}'.format( name, self.__class__.__name__)) # pylint: disable=too-many-nested-blocks
Example #15
Source File: __init__.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 5 votes |
def stateless_property(func): '''Decorator similar to :py:class:`builtins.property`, but for properties exposed through management API (including qvm-prefs etc)''' return property(func.__name__, setter=property.forbidden, saver=property.dontsave, default=func, doc=func.__doc__)
Example #16
Source File: __init__.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 5 votes |
def forbidden(self, prop, value): '''Property setter that forbids loading a property. This is used to effectively disable property in classes which inherit unwanted property. When someone attempts to load such a property, it :throws AttributeError: always ''' # pylint: disable=bad-staticmethod-argument,unused-argument raise AttributeError( 'setting {} property on {} instance is forbidden'.format( prop.__name__, self.__class__.__name__))
Example #17
Source File: __init__.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 5 votes |
def dontsave(self, prop, value): '''Dummy saver that never saves anything.''' # pylint: disable=bad-staticmethod-argument,unused-argument raise property.DontSave() # # some setters provided #
Example #18
Source File: __init__.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 5 votes |
def sanitize(self, *, untrusted_newvalue): '''Coarse sanitization of value to be set, before sending it to a setter. Can raise QubesValueError if the value is invalid. :param untrusted_newvalue: value to be validated :return: sanitized value :raises: qubes.exc.QubesValueError ''' # do not treat type='str' as sufficient validation if self.type is not None and self.type is not str: # assume specific type will preform enough validation try: untrusted_newvalue = untrusted_newvalue.decode('ascii', errors='strict') except UnicodeDecodeError: raise qubes.exc.QubesValueError if self.type is bool: return self.bool(None, None, untrusted_newvalue) try: return self.type(untrusted_newvalue) except ValueError: raise qubes.exc.QubesValueError else: # 'str' or not specified type try: untrusted_newvalue = untrusted_newvalue.decode('ascii', errors='strict') except UnicodeDecodeError: raise qubes.exc.QubesValueError allowed_set = string.printable if not all(x in allowed_set for x in untrusted_newvalue): raise qubes.exc.QubesValueError( 'Invalid characters in property value') return untrusted_newvalue # # exceptions #
Example #19
Source File: __init__.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 5 votes |
def _enforce_write_once(self, instance): if self._write_once and not instance.property_is_default(self): raise AttributeError( 'property {!r} is write-once and already set'.format( self.__name__))
Example #20
Source File: __init__.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 5 votes |
def __eq__(self, other): if isinstance(other, str): return self.__name__ == other return isinstance(other, property) and self.__name__ == other.__name__
Example #21
Source File: __init__.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 5 votes |
def __delete__(self, instance): self._enforce_write_once(instance) try: oldvalue = getattr(instance, self.__name__) has_oldvalue = True except AttributeError: has_oldvalue = False if has_oldvalue: instance.fire_event('property-pre-reset:' + self.__name__, pre_event=True, name=self.__name__, oldvalue=oldvalue) # deprecated, to be removed in Qubes 5.0 instance.fire_event('property-pre-del:' + self.__name__, pre_event=True, name=self.__name__, oldvalue=oldvalue) try: delattr(instance, self._attr_name) except AttributeError: pass instance.fire_event('property-reset:' + self.__name__, name=self.__name__, oldvalue=oldvalue) # deprecated, to be removed in Qubes 5.0 instance.fire_event('property-del:' + self.__name__, name=self.__name__, oldvalue=oldvalue) else: instance.fire_event('property-pre-reset:' + self.__name__, pre_event=True, name=self.__name__) # deprecated, to be removed in Qubes 5.0 instance.fire_event('property-pre-del:' + self.__name__, pre_event=True, name=self.__name__) instance.fire_event('property-reset:' + self.__name__, name=self.__name__) # deprecated, to be removed in Qubes 5.0 instance.fire_event('property-del:' + self.__name__, name=self.__name__)
Example #22
Source File: __init__.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 5 votes |
def __set__(self, instance, value): self._enforce_write_once(instance) if value is self.__class__.DEFAULT: self.__delete__(instance) return try: oldvalue = getattr(instance, self.__name__) has_oldvalue = True except AttributeError: has_oldvalue = False if self._setter is not None: value = self._setter(instance, self, value) if self.type not in (None, type(value)): value = self.type(value) if has_oldvalue: instance.fire_event('property-pre-set:' + self.__name__, pre_event=True, name=self.__name__, newvalue=value, oldvalue=oldvalue) else: instance.fire_event('property-pre-set:' + self.__name__, pre_event=True, name=self.__name__, newvalue=value) instance._property_init(self, value) # pylint: disable=protected-access if has_oldvalue: instance.fire_event('property-set:' + self.__name__, name=self.__name__, newvalue=value, oldvalue=oldvalue) else: instance.fire_event('property-set:' + self.__name__, name=self.__name__, newvalue=value)
Example #23
Source File: __init__.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 5 votes |
def get_default(self, instance): if self._default is self._NO_DEFAULT: raise AttributeError( 'property {!r} have no default'.format(self.__name__)) if self._default_function: return self._default_function(instance) return self._default
Example #24
Source File: __init__.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 5 votes |
def __get__(self, instance, owner): if instance is None: return self # XXX this violates duck typing, shall we keep it? if not isinstance(instance, PropertyHolder): raise AttributeError('qubes.property should be used on ' 'qubes.PropertyHolder instances only') try: return getattr(instance, self._attr_name) except AttributeError: return self.get_default(instance)