def _settle_cache(target, source, recursed=None): '''`target` is a mapping to store result commands''' if recursed is None: recursed = set() # TODO: Convert check based in argument "recursed" in a decorator from xoutil.names import nameof name = nameof(source, inner=True, full=True) if name not in recursed: recursed.add(name) sub_commands = type.__subclasses__(source) sub_commands.extend(getattr(source, '_abc_registry', ())) cmds = getattr(source, '__commands__', None) if cmds: from collections import Iterable if not isinstance(cmds, Iterable): cmds = cmds() sub_commands.extend(cmds) if sub_commands: for cmd in sub_commands: Command._settle_cache(target, cmd, recursed=recursed) else: # Only branch commands are OK to execute from types import MethodType assert isinstance(source.run, MethodType) target[command_name(source)] = source else: raise ValueError('Reused class "%s"!' % name)
def __repr__(self): from xoutil.names import nameof name = getattr(self, 'name', None) if name: return str("<%s '%s'>" % (nameof(type(self), inner=True, full=True), name.encode('ascii', 'replace'))) else: return super(Entity, self).__repr__()
def __repr__(self): from xoutil.names import nameof name = getattr(self, 'name', None) if name: return str("<%s '%s'>" % ( nameof(type(self), inner=True, full=True), safe_encode(name))) else: return super().__repr__()
def __new__(cls, definition, name=None): from types import FunctionType if not isinstance(definition, FunctionType): raise TypeError('"definition" must be a function') if not name: from xoutil.names import nameof name = nameof(definition, inner=True, full=True) result = super(BoundaryCondition, cls).__new__(cls) result.name = name # needs to be set here or it'll be None return result
def _handle_fingerprint(self, record): from xoutil.names import nameof exc_info = record.exc_info if exc_info: _type, value, _tb = exc_info exc = nameof(_type, inner=True, full=True) if exc.startswith("psycopg2."): fingerprint = [exc] else: fingerprint = getattr(value, "_sentry_fingerprint", None) if fingerprint: if not isinstance(fingerprint, list): fingerprint = [fingerprint] record.fingerprint = fingerprint
def get_object_module(obj, typed=False): """Return the name of the OpenERP addon the `obj` has been defined. If the `obj` is not defined (imported) from the "openerp.addons." namespace, return None. """ from xoutil.names import nameof name = nameof(obj, inner=True, full=True, typed=typed) match = _ADDONS_NAMESPACE.match(name) if match: module = match.groupdict()["module"] return module else: return None
def __parse_arguments(self, *args, **kwargs): '''Assign parsed arguments to the just created instance.''' from xoutil.validators import (is_valid_identifier, predicate) self.attr_name = Unset self.init = Unset self.default = Unset self.do_assigning = True self.validator = True for i, arg in enumerate(args): if self.attr_name is Unset and is_valid_identifier(arg): self.attr_name = arg elif self.init is Unset and callable(arg): self.init = arg else: msg = ('Invalid positional arguments: %s at %s\n' 'Valid arguments are the attribute name and a ' 'callable constructor for initial value.') raise ValueError(msg % (args[i:], i)) bads = {} for key in kwargs: value = kwargs[key] if (self.default is Unset and self.init is Unset and key in ('default', 'value', 'initial_value')): self.default = value elif (self.validator is True and key in ('validator', 'checker', 'check')): self.validator = value elif (self.do_assigning is True and key == 'do_assigning' and value is False): self.do_assigning = False else: bads[key] = value self.validator = predicate(self.validator) if bads: msg = ('Invalid keyword arguments: %s\n' 'See constructor documentation for more info.') raise ValueError(msg % bads) if self.attr_name is Unset: from xoutil.names import nameof if self.init is not Unset: if isinstance(self.init, type): self.attr_name = str('_%s' % self.init.__name__) else: self.attr_name = nameof(self.init, safe=True) else: self.attr_name = self._unique_name() self.inner_name = str('__%s__' % self.attr_name.strip('_'))
def unstable(target, msg=None): '''Declares that a method, class or interface is unstable. This has the side-effect of issuing a warning the first time the `target` is invoked. The `msg` parameter, if given, should be string that contains, at most, two positional replacement fields ({0} and {1}). The first replacement field will be the type of `target` (interface, class or function) and the second matches `target's` full name. ''' import warnings from xoutil.names import nameof from xoutil.eight import class_types if msg is None: msg = ('The {0} `{1}` is declared unstable. ' 'It may change in the future or be removed.') try: from zope.interface import Interface except ImportError: from xoutil import Ignored as Interface if isinstance(target, type(Interface)): objtype = 'interface' elif isinstance(target, class_types): objtype = 'class' else: objtype = 'function or method' message = msg.format(objtype, nameof(target, inner=True, full=True)) if isinstance(target, class_types) or issubclass(type(target), type(Interface)): class meta(type(target)): pass def new(*args, **kwargs): warnings.warn(message, stacklevel=2) return target.__new__(*args, **kwargs) klass = meta(target.__name__, (target,), {'__new__': new}) return klass else: def _unstable(*args, **kwargs): message = msg.format(objtype, nameof(target, inner=True, full=True)) warnings.warn(message, stacklevel=2) return target(*args, **kwargs) return _unstable
def add_symbols_to_xmls(*objs, **symbols): """Allow to use the provided symbols in XMLs. Technically this replaces the function `safe_eval` in module `odoo.tools.convert` to include the symbols in the context. We keep a global dict of symbols, and only replace the `safe_eval` function once and update the global dict :param objs: Objects to be made available under its `proper name <xoutil.names.nameof>`:func:. :param symbols: Objects to be made available under the keyword argument. .. versionadded:: 0.42.0 .. versionchanged:: 0.43.0 Added the `objs` variable positional arguments. """ if objs: symbols.update({nameof(obj, inner=True, full=False): obj for obj in objs}) _SAFE_EVAL_SYMBOLS.update(symbols)
def __init__(self, name, bases, attrs): from xoutil.names import nameof from xoutil.functools import compose OperatorType.operators.append(self) _PROVIDES = (' This {which} directly provides ' ':class:`xotl.ql.interfaces.{interface}`.\n\n') doc = '' for attr, trans in (('arity', lambda x: nameof(x, inner=True)), ('_method_name', repr), ('_format', compose(str, repr))): value = getattr(self, attr, None) if value: v = trans(value).replace('_', r'\_') v = v.replace("'", '"') doc += ('\n\n - **{attr}:** {v}'.format(attr=attr, v=v)) if doc: self.__doc__ = ((self.__doc__ if self.__doc__ else '') + '\n\n **Attributes**:' + doc) doc = '' interfaces = (IOperator, ) if getattr(self, '_rmethod_name', False): interfaces += (ISyntacticallyReversibleOperation, ) if 'ISyntacticallyReversibleOperation' not in self.__doc__: doc += _PROVIDES.format( which='class', interface='ISyntacticallyReversibleOperation') if getattr(self, 'equivalence_test', False): interfaces += (ISynctacticallyCommutativeOperation, ) if 'ISynctacticallyCommutativeOperation' not in self.__doc__: doc += _PROVIDES.format( which='class', interface='ISynctacticallyCommutativeOperation') if doc: self.__doc__ += '\n\n **Interface(s)**:\n\n' + doc directlyProvides(self, *interfaces)
def __init__(self, validator, error): self.validator = validator self.validator_name = nameof(validator, inner=True) self.error = error or "This value is incorrect"
def use_name(self): return nameof(self.use, inner=True)
def __init__(self, type): self.type = type self.type_name = nameof(self.type, inner=True)
def _unstable(*args, **kwargs): message = msg.format(objtype, nameof(target, inner=True, full=True)) warnings.warn(message, stacklevel=2) return target(*args, **kwargs)
def __call__(self, func): from xoutil.names import nameof name = nameof(func, inner=True, full=False) self._registry[name] = func return func
def __hash__(self): from xoutil.names import nameof return hash(nameof(self, inner=True, full=True))