def inner_decorator(init_or_class): if _isclass(init_or_class): func = getattr(init_or_class, '__init__') elif _isfunction(init_or_class): func = init_or_class else: raise ValueError("autoinit decorator should be applied to class or its __init__ method") if (func.__name__ != '__init__' or func.__code__.co_name != '__init__') and not no_warn: _warn(AutoinitWarning("autoinit decorator intended to be applied only to __init__" " method (use autoinit(no_warn=True) to suppress this warning)")) args_names = func.__code__.co_varnames[1:func.__code__.co_argcount] @_wraps(func) def inner(self, *args, **kwargs): if reverse: func(self, *args, **kwargs) args_vals = args[:] if func.__defaults__: args_vals += func.__defaults__[len(args) - len(args_names):] for key, val in zip(args_names, args_vals): if key not in exclude: if (type(self.__class__).__name__ != 'classobj' and hasattr(self, '__slots__') and key not in self.__slots__): raise AttributeError("Can not assign attribute '%s': it is not " "listed in %s.__slots__" % (key, self.__class__)) setattr(self, key, val) if not reverse: func(self, *args, **kwargs) if _isclass(init_or_class): init_or_class.__init__ = inner return init_or_class return inner
def run__test__(self, d, name): """d, name -> Treat dict d like module.__test__. Return (#failures, #tries). See testmod.__doc__ for details. """ failures = tries = 0 prefix = name + "." savepvt = self.isprivate try: self.isprivate = lambda *args: 0 # Run the tests by alpha order of names, for consistency in # verbose-mode output. keys = d.keys() keys.sort() for k in keys: v = d[k] thisname = prefix + k if type(v) in _StringTypes: f, t = self.runstring(v, thisname) elif _isfunction(v) or _isclass(v): f, t = self.rundoc(v, thisname) else: raise TypeError("Tester.run__test__: values in " "dict must be strings, functions " "or classes; " + `v`) failures = failures + f tries = tries + t finally: self.isprivate = savepvt return failures, tries
def print_goals_for_tracked(tracked_id, achievement_or_iter=None, achieved=True, unachieved=False, only_current=False, level=False, category=None, keywords=[], indent=2, tracker=None): """ Prints goals for a specific ``tracked_id`` from as tracked by a ``tracker``. By default, this will print out all achieved goals for every achievement in the ``tracker``. Arguments: achievment_or_iter If ``None``, this will print goals for all achievements registered with the ``tracker``. Otherwise an ``Achievement`` or list of achievements can be given to show goals for. achieved If True, prints out goals that have allready been achieved. unachieved If True, prints out goals that have not been achieved. only_current If True, only prints the goal currently being worked on (next to be achieved). This will override the ``achieved`` and ``unachieved`` options. category Category to filter achievements from the tracker. keywords Keywords to filter achievements from the tracker. level If True, show the current level with the achievements tracker The tracker to use for getting information about achievements and ``tracked_id``. If ``tracker`` is ``None``, this will default to using the default tracker. """ from clint.textui import puts from clint.textui import indent as _indent from clint.textui.cols import console_width if tracker is None: tracker = _defaulttracker if achievement_or_iter is None: achievement_or_iter = tracker.achievements() elif _isclass(achievement_or_iter) and issubclass(achievement_or_iter, Achievement): achievement_or_iter = [achievement_or_iter] for achievement in achievement_or_iter: with _indent(indent): puts("{0}\n{1}\n".format(achievement.name, '='*(console_width({})-indent-2))) current = tracker.current(tracked_id, achievement) cl = None if not level else current[0] if only_current: print_goal(current[1], level=current[0], indent=indent) else: goals = tracker.achieved(tracked_id, achievement) if achieved else [] goals += tracker.unachieved(tracked_id, achievement) if unachieved else [] for goal in goals: print_goal(goal, current[0] >= goal['level'], level=cl, indent=indent) puts("\n")
def run__test__(self, d, name): """d, name -> Treat dict d like module.__test__. Return (#failures, #tries). See testmod.__doc__ for details. """ failures = tries = 0 prefix = name + "." savepvt = self.isprivate try: self.isprivate = lambda *args: 0 # Run the tests by alpha order of names, for consistency in # verbose-mode output. keys = d.keys() keys.sort() for k in keys: v = d[k] thisname = prefix + k if type(v) in _StringTypes: f, t = self.runstring(v, thisname) elif _isfunction(v) or _isclass(v): f, t = self.rundoc(v, thisname) else: raise TypeError("Tester.run__test__: values in " "dict must be strings, functions " "or classes; " + ` v `) failures = failures + f tries = tries + t finally: self.isprivate = savepvt return failures, tries
def unregister(self, achievement_or_iterable): """ Un-registers the given achievement(s). If an achievement isn't already registered, this will raise NotRegistered. """ if _isclass(achievement_or_iterable) and issubclass(achievement_or_iterable, Achievement): achievement_or_iterable = [achievement_or_iterable] for achievement in achievement_or_iterable: if achievement not in self._registry: raise NotRegistered('The achievement %s is not registered' % achievement.__name__) self._registry.remove(achievement)
def unregister(self, achievement_or_iterable): """ Un-registers the given achievement(s). If an achievement isn't already registered, this will raise NotRegistered. """ if _isclass(achievement_or_iterable) and issubclass( achievement_or_iterable, Achievement): achievement_or_iterable = [achievement_or_iterable] for achievement in achievement_or_iterable: if achievement not in self._registry: raise NotRegistered('The achievement %s is not registered' % achievement.__name__) self._registry.remove(achievement)
def register(self, achievement_or_iterable, **options): """ Registers the given achievement(s) to be tracked. """ if _isclass(achievement_or_iterable) and issubclass(achievement_or_iterable, Achievement): achievement_or_iterable = [achievement_or_iterable] for achievement in achievement_or_iterable: if not achievement.category: raise ValueError('Achievements must specify a category, could not register ' '%s' % achievement.__name__) if achievement in self._registry: raise AlreadyRegistered('The achievement %s is already ' 'registered' % achievement.__name__) if achievement is not Achievement: self._registry.append(achievement)
def __getattribute__(self, name): value = getattr(_original_module, name) # Allow specific names and resources if not (name[0] == '_' or name in _ALLOWED_ATTRIBUTES or _ismodule(value) or (_isclass(value) and issubclass(value, APIResource) and value is not APIResource)): _warnings.warn( 'Attribute `%s` is being moved out of the `stripe` module ' 'in version 2.0 of the Stripe bindings. Please access it ' 'in the appropriate submodule instead' % (name, ), DeprecationWarning, stacklevel=2) return value
def print_goals(achievement_or_iter, indent=2): """ Displays all of the available goals registered for the given achievement(s) """ from clint.textui import puts from clint.textui.cols import console_width from clint.textui import indent as _indent if _isclass(achievement_or_iter) and issubclass(achievement_or_iter, Achievement): achievement_or_iter = [achievement_or_iter] for achievement in achievement_or_iter: with _indent(indent): puts("{0}\n{1}\n".format(achievement.name, '='*(console_width({})-indent-2))) for goal in achievement.goals: print_goal(goal, True, indent=indent) puts("\n")
def __getattribute__(self, name): value = getattr(_original_module, name) # Allow specific names and resources if not (name[0] == '_' or name in _ALLOWED_ATTRIBUTES or _ismodule(value) or (_isclass(value) and issubclass(value, APIResource) and value is not APIResource)): _warnings.warn( 'Attribute `%s` is being moved out of the `stripe` module ' 'in version 2.0 of the Stripe bindings. Please access it ' 'in the appropriate submodule instead' % (name,), DeprecationWarning, stacklevel=2) return value
def achievement_for_id(self, user, achievement): """ Returns ``Achievement`` for a given ``tracked_id``. Achievement can be an ``Achievement`` class or a string of the name of an achievement class that has been registered with this tracker. Raises NotRegistered if the given achievement is not registered with the tracker. If ``tracked_id`` has not been tracked yet by this tracker, it will be created. """ if isinstance(achievement, Achievement): achievement = achievement.__class__.__name__ elif _isclass(achievement) and issubclass(achievement, Achievement): achievement = achievement.__name__ a = [_ for _ in self._registry if _.__name__ == achievement] if a: return self.backend.achievement_for_id(user, a[0]) raise NotRegistered('The achievement %s is not registered with this tracker' % achievement)
def register(self, achievement_or_iterable, **options): """ Registers the given achievement(s) to be tracked. """ if _isclass(achievement_or_iterable) and issubclass( achievement_or_iterable, Achievement): achievement_or_iterable = [achievement_or_iterable] for achievement in achievement_or_iterable: if not achievement.category: raise ValueError( 'Achievements must specify a category, could not register ' '%s' % achievement.__name__) if achievement in self._registry: raise AlreadyRegistered('The achievement %s is already ' 'registered' % achievement.__name__) if achievement is not Achievement: self._registry.append(achievement)
def print_goals(achievement_or_iter, indent=2): """ Displays all of the available goals registered for the given achievement(s) """ from clint.textui import puts from clint.textui.cols import console_width from clint.textui import indent as _indent if _isclass(achievement_or_iter) and issubclass(achievement_or_iter, Achievement): achievement_or_iter = [achievement_or_iter] for achievement in achievement_or_iter: with _indent(indent): puts("{0}\n{1}\n".format(achievement.name, '=' * (console_width({}) - indent - 2))) for goal in achievement.goals: print_goal(goal, True, indent=indent) puts("\n")
def achievement_for_id(self, tracked_id, achievement): """ Returns ``Achievement`` for a given ``tracked_id``. Achievement can be an ``Achievement`` class or a string of the name of an achievement class that has been registered with this tracker. Raises NotRegistered if the given achievement is not registered with the tracker. If ``tracked_id`` has not been tracked yet by this tracker, it will be created. """ if isinstance(achievement, Achievement): achievement = achievement.__class__.__name__ elif _isclass(achievement) and issubclass(achievement, Achievement): achievement = achievement.__name__ a = [_ for _ in self._registry if _.__name__ == achievement] if a: return self._backend.achievement_for_id(tracked_id, a[0]) raise NotRegistered( 'The achievement %s is not registered with this tracker' % achievement)
def isclass(x): from inspect import isclass as _isclass return _isclass(x)
def rundict(self, d, name, module=None): """ d, name, module=None -> search for docstring examples in d.values(). For k, v in d.items() such that v is a function or class, do self.rundoc(v, name + "." + k). Whether this includes objects with private names depends on the constructor's "isprivate" argument. If module is specified, functions and classes that are not defined in module are excluded. Return aggregate (#failures, #examples). Build and populate two modules with sample functions to test that exclusion of external functions and classes works. >>> import new >>> m1 = new.module('_m1') >>> m2 = new.module('_m2') >>> test_data = \""" ... def _f(): ... '''>>> assert 1 == 1 ... ''' ... def g(): ... '''>>> assert 2 != 1 ... ''' ... class H: ... '''>>> assert 2 > 1 ... ''' ... def bar(self): ... '''>>> assert 1 < 2 ... ''' ... \""" >>> exec test_data in m1.__dict__ >>> exec test_data in m2.__dict__ >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H}) Tests that objects outside m1 are excluded: >>> t = Tester(globs={}, verbose=0) >>> t.rundict(m1.__dict__, "rundict_test", m1) # _f, f2 and g2 and h2 skipped (0, 3) Again, but with a custom isprivate function allowing _f: >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0) >>> t.rundict(m1.__dict__, "rundict_test_pvt", m1) # Only f2, g2 and h2 skipped (0, 4) And once more, not excluding stuff outside m1: >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0) >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped. (0, 8) The exclusion of objects from outside the designated module is meant to be invoked automagically by testmod. >>> testmod(m1) (0, 3) """ if not hasattr(d, "items"): raise TypeError("Tester.rundict: d must support .items(); " + ` d `) f = t = 0 # Run the tests by alpha order of names, for consistency in # verbose-mode output. names = d.keys() names.sort() for thisname in names: value = d[thisname] if _isfunction(value) or _isclass(value): if module and not _from_module(module, value): continue f2, t2 = self.__runone(value, name + "." + thisname) f = f + f2 t = t + t2 return f, t
def rundoc(self, object, name=None): """ object, name=None -> search object.__doc__ for examples to run. Use optional string name as the key for logging the outcome; by default use object.__name__. Return (#failures, #examples). If object is a class object, search recursively for method docstrings too. object.__doc__ is examined regardless of name, but if object is a class, whether private names reached from object are searched depends on the constructor's "isprivate" argument. >>> t = Tester(globs={}, verbose=0) >>> def _f(): ... '''Trivial docstring example. ... >>> assert 2 == 2 ... ''' ... return 32 ... >>> t.rundoc(_f) # expect 0 failures in 1 example (0, 1) """ if name is None: try: name = object.__name__ except AttributeError: raise ValueError("Tester.rundoc: name must be given " "when object.__name__ doesn't exist; " + ` object `) if self.verbose: print "Running", name + ".__doc__" f, t = run_docstring_examples(object, self.globs, self.verbose, name, self.compileflags) if self.verbose: print f, "of", t, "examples failed in", name + ".__doc__" self.__record_outcome(name, f, t) if _isclass(object): # In 2.2, class and static methods complicate life. Build # a dict "that works", by hook or by crook. d = {} for tag, kind, homecls, value in _classify_class_attrs(object): if homecls is not object: # Only look at names defined immediately by the class. continue elif self.isprivate(name, tag): continue elif kind == "method": # value is already a function d[tag] = value elif kind == "static method": # value isn't a function, but getattr reveals one d[tag] = getattr(object, tag) elif kind == "class method": # Hmm. A classmethod object doesn't seem to reveal # enough. But getattr turns it into a bound method, # and from there .im_func retrieves the underlying # function. d[tag] = getattr(object, tag).im_func elif kind == "property": # The methods implementing the property have their # own docstrings -- but the property may have one too. if value.__doc__ is not None: d[tag] = str(value.__doc__) elif kind == "data": # Grab nested classes. if _isclass(value): d[tag] = value else: raise ValueError("teach doctest about %r" % kind) f2, t2 = self.run__test__(d, name) f += f2 t += t2 return f, t
def _from_module(module, object): if _isfunction(object): return module.__dict__ is object.func_globals if _isclass(object): return module.__name__ == object.__module__ raise ValueError("object must be a class or function")
def print_goals_for_tracked(tracked_id, achievement_or_iter=None, achieved=True, unachieved=False, only_current=False, level=False, category=None, keywords=[], indent=2, tracker=None): """ Prints goals for a specific ``tracked_id`` from as tracked by a ``tracker``. By default, this will print out all achieved goals for every achievement in the ``tracker``. Arguments: achievment_or_iter If ``None``, this will print goals for all achievements registered with the ``tracker``. Otherwise an ``Achievement`` or list of achievements can be given to show goals for. achieved If True, prints out goals that have allready been achieved. unachieved If True, prints out goals that have not been achieved. only_current If True, only prints the goal currently being worked on (next to be achieved). This will override the ``achieved`` and ``unachieved`` options. category Category to filter achievements from the tracker. keywords Keywords to filter achievements from the tracker. level If True, show the current level with the achievements tracker The tracker to use for getting information about achievements and ``tracked_id``. If ``tracker`` is ``None``, this will default to using the default tracker. """ from clint.textui import puts from clint.textui import indent as _indent from clint.textui.cols import console_width if tracker is None: tracker = _defaulttracker if achievement_or_iter is None: achievement_or_iter = tracker.achievements() elif _isclass(achievement_or_iter) and issubclass(achievement_or_iter, Achievement): achievement_or_iter = [achievement_or_iter] for achievement in achievement_or_iter: with _indent(indent): puts("{0}\n{1}\n".format(achievement.name, '=' * (console_width({}) - indent - 2))) current = tracker.current(tracked_id, achievement) cl = None if not level else current[0] if only_current: print_goal(current[1], level=current[0], indent=indent) else: goals = tracker.achieved(tracked_id, achievement) if achieved else [] goals += tracker.unachieved(tracked_id, achievement) if unachieved else [] for goal in goals: print_goal(goal, current[0] >= goal['level'], level=cl, indent=indent) puts("\n")
def autoinit(*decoargs, **decokwargs): ''' Decorator for automatic initialization instance attributes @autoinit def __init__(self, a, b=10): pass is equivalent to def __init__(self, a, b=10): self.a = a self.b = b The decorator can be equally applied to both the __init__ method and the entire class. Options: exclude: str or iterable of strs # skip specified attributes no_warn: bool = False # do not warn when decorator applied to not __init__, reverse: bool = False # call wrapped method before the assignment ''' reverse = decokwargs.get('reverse', False) no_warn = decokwargs.get('no_warn', False) exclude = decokwargs.get('exclude', []) if version_info.major > 2: unicode = str else: unicode = type(u"") acceptable_str_types = (str, unicode) if isinstance(exclude, acceptable_str_types): exclude = [exclude] def inner_decorator(init_or_class): if _isclass(init_or_class): func = getattr(init_or_class, '__init__') elif _isfunction(init_or_class): func = init_or_class else: raise ValueError("autoinit decorator should be applied to class or its __init__ method") if (func.__name__ != '__init__' or func.__code__.co_name != '__init__') and not no_warn: _warn(AutoinitWarning("autoinit decorator intended to be applied only to __init__" " method (use autoinit(no_warn=True) to suppress this warning)")) args_names = func.__code__.co_varnames[1:func.__code__.co_argcount] @_wraps(func) def inner(self, *args, **kwargs): if reverse: func(self, *args, **kwargs) args_vals = args[:] if func.__defaults__: args_vals += func.__defaults__[len(args) - len(args_names):] for key, val in zip(args_names, args_vals): if key not in exclude: if (type(self.__class__).__name__ != 'classobj' and hasattr(self, '__slots__') and key not in self.__slots__): raise AttributeError("Can not assign attribute '%s': it is not " "listed in %s.__slots__" % (key, self.__class__)) setattr(self, key, val) if not reverse: func(self, *args, **kwargs) if _isclass(init_or_class): init_or_class.__init__ = inner return init_or_class return inner if decoargs and (_isfunction(decoargs[0]) or _isclass(decoargs[0])): return inner_decorator(decoargs[0]) return inner_decorator
# Module doctest.
def rundict(self, d, name, module=None): """ d, name, module=None -> search for docstring examples in d.values(). For k, v in d.items() such that v is a function or class, do self.rundoc(v, name + "." + k). Whether this includes objects with private names depends on the constructor's "isprivate" argument. If module is specified, functions and classes that are not defined in module are excluded. Return aggregate (#failures, #examples). Build and populate two modules with sample functions to test that exclusion of external functions and classes works. >>> import new >>> m1 = new.module('_m1') >>> m2 = new.module('_m2') >>> test_data = \""" ... def _f(): ... '''>>> assert 1 == 1 ... ''' ... def g(): ... '''>>> assert 2 != 1 ... ''' ... class H: ... '''>>> assert 2 > 1 ... ''' ... def bar(self): ... '''>>> assert 1 < 2 ... ''' ... \""" >>> exec test_data in m1.__dict__ >>> exec test_data in m2.__dict__ >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H}) Tests that objects outside m1 are excluded: >>> t = Tester(globs={}, verbose=0) >>> t.rundict(m1.__dict__, "rundict_test", m1) # _f, f2 and g2 and h2 skipped (0, 3) Again, but with a custom isprivate function allowing _f: >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0) >>> t.rundict(m1.__dict__, "rundict_test_pvt", m1) # Only f2, g2 and h2 skipped (0, 4) And once more, not excluding stuff outside m1: >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0) >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped. (0, 8) The exclusion of objects from outside the designated module is meant to be invoked automagically by testmod. >>> testmod(m1) (0, 3) """ if not hasattr(d, "items"): raise TypeError("Tester.rundict: d must support .items(); " + `d`) f = t = 0 # Run the tests by alpha order of names, for consistency in # verbose-mode output. names = d.keys() names.sort() for thisname in names: value = d[thisname] if _isfunction(value) or _isclass(value): if module and not _from_module(module, value): continue f2, t2 = self.__runone(value, name + "." + thisname) f = f + f2 t = t + t2 return f, t
def rundoc(self, object, name=None): """ object, name=None -> search object.__doc__ for examples to run. Use optional string name as the key for logging the outcome; by default use object.__name__. Return (#failures, #examples). If object is a class object, search recursively for method docstrings too. object.__doc__ is examined regardless of name, but if object is a class, whether private names reached from object are searched depends on the constructor's "isprivate" argument. >>> t = Tester(globs={}, verbose=0) >>> def _f(): ... '''Trivial docstring example. ... >>> assert 2 == 2 ... ''' ... return 32 ... >>> t.rundoc(_f) # expect 0 failures in 1 example (0, 1) """ if name is None: try: name = object.__name__ except AttributeError: raise ValueError("Tester.rundoc: name must be given " "when object.__name__ doesn't exist; " + `object`) if self.verbose: print "Running", name + ".__doc__" f, t = run_docstring_examples(object, self.globs, self.verbose, name, self.compileflags) if self.verbose: print f, "of", t, "examples failed in", name + ".__doc__" self.__record_outcome(name, f, t) if _isclass(object): # In 2.2, class and static methods complicate life. Build # a dict "that works", by hook or by crook. d = {} for tag, kind, homecls, value in _classify_class_attrs(object): if homecls is not object: # Only look at names defined immediately by the class. continue elif self.isprivate(name, tag): continue elif kind == "method": # value is already a function d[tag] = value elif kind == "static method": # value isn't a function, but getattr reveals one d[tag] = getattr(object, tag) elif kind == "class method": # Hmm. A classmethod object doesn't seem to reveal # enough. But getattr turns it into a bound method, # and from there .im_func retrieves the underlying # function. d[tag] = getattr(object, tag).im_func elif kind == "property": # The methods implementing the property have their # own docstrings -- but the property may have one too. if value.__doc__ is not None: d[tag] = str(value.__doc__) elif kind == "data": # Grab nested classes. if _isclass(value): d[tag] = value else: raise ValueError("teach doctest about %r" % kind) f2, t2 = self.run__test__(d, name) f += f2 t += t2 return f, t
def _check_api_enabled(o: _EntityOrCls) -> _EntityOrCls: if (_isclass(o) and not issubclass(o, _model.HTTPAPIEntityMixin)) or not o.odm_http_api_enabled(): raise _errors.ForbidOperation('Usage of HTTP API is not allowed for this model') return o
def isclass(obj): '''Return C{True} if B{C{obj}} is a C{class}. @see: Python's C{inspect.isclass}. ''' return _isclass(obj)