# # Contributors: see CONTRIBUTORS and HISTORY file # # This is free software; you can redistribute it and/or modify it under the # terms of the LICENCE attached (see LICENCE file) in the distribution # package. # # Created on Feb 17, 2012 from __future__ import (division as _py3_division, print_function as _py3_print, unicode_literals as _py3_unicode, absolute_import as _py3_abs_imports) from xoutil.names import strlist as strs __all__ = strs('uuid', ) del strs def uuid(random=False): '''Return a "Global Unique ID" as a string. :param random: If True then a random uuid is generated (does not use host id). ''' from uuid import uuid1, uuid4 if not random: return '%s' % uuid1() else: return '%s' % uuid4()
from __future__ import (division as _py3_division, print_function as _py3_print, unicode_literals as _py3_unicode, absolute_import) import sys from functools import wraps from types import FunctionType as function from .meta import decorator as _decorator from xoutil.names import strlist as strs __all__ = strs('decorator', 'AttributeAlias', 'settle', 'namer', 'aliases', 'assignment_operator', 'instantiate', 'memoized_property', 'memoized_instancemethod', 'reset_memoized') del strs class AttributeAlias(object): '''Descriptor to create aliases for object attributes. This descriptor is mainly to be used internally by :func:`aliases` decorator. ''' def __init__(self, attr_name): super(AttributeAlias, self).__init__() self.attr_name = attr_name
''' from __future__ import (division as _py3_division, print_function as _py3_print, unicode_literals as _py3_unicode, absolute_import as _py3_abs_imports) from xoutil.modules import copy_members as _copy_members import pprint as _pm _copy_members(_pm) pprint = _pm.pprint # Avoid IDE complaints from xoutil.names import strlist as strs __all__ = strs('ppformat', *getattr(_pm, '__all__', dir(_pm))) del strs del _pm, _copy_members def ppformat(obj): '''Just like :func:`pprint` but always returns the result instead of writing it to a stream. :returns: The pretty formated text. :rtype: `unicode` in Python 2, `str` in Python 3. ''' import io from six import PY3, text_type if PY3:
""" from __future__ import ( division as _py3_division, print_function as _py3_print, unicode_literals as _py3_unicode, absolute_import as _py3_abs_imports, ) from xoutil.names import strlist as strs __all__ = strs( "PASS_PHRASE_LEVEL_BASIC", "PASS_PHRASE_LEVEL_MAPPED", "PASS_PHRASE_LEVEL_MAPPED_MIXED", "PASS_PHRASE_LEVEL_MAPPED_DATED", "PASS_PHRASE_LEVEL_STRICT", "generate_password", ) del strs #: The most basic level (less ) for the password generation. PASS_PHRASE_LEVEL_BASIC = 0 #: A level for simply mapping of several chars. PASS_PHRASE_LEVEL_MAPPED = 1 #: Another "stronger" mapping level. PASS_PHRASE_LEVEL_MAPPED_MIXED = 2
''' # TODO: consider use IoC to extend python json module from __future__ import (division as _py3_division, print_function as _py3_print, unicode_literals as _py3_unicode, absolute_import as _py3_abs_imports) from xoutil.modules import copy_members as _copy_python_module_members _pm = _copy_python_module_members() load = _pm.load from xoutil.names import strlist as strs __all__ = strs('file_load') __all__.extend(getattr(_pm, '__all__', dir(_pm))) del strs, _copy_python_module_members class JSONEncoder(_pm.JSONEncoder): __doc__ = (_pm.JSONEncoder.__doc__ + ''' We also support: - `datetime`, `date` and `time` values, which are translated to strings using ISO format. - `Decimal` values, which are represented as a string representation. - Iterables, which are represented as lists.
import inspect from functools import wraps, partial from types import FunctionType as function from six import string_types as _str_base, PY3 as _PY3 if _PY3: from inspect import getfullargspec as _getfullargspec else: from inspect import getargspec as _getfullargspec from xoutil.names import strlist as strs __all__ = strs('FunctionMaker', 'flat_decorator', 'decorator') del strs DEF = re.compile('\s*def\s*([_\w][_\w\d]*)\s*\(') # basic functionality class FunctionMaker(object): """ An object with the ability to create functions with a given signature. It has attributes name, doc, module, signature, defaults, dict and methods update and make. """ def __init__(self, func=None, name=None, signature=None, defaults=None, doc=None, module=None, funcdict=None):
An aspect can also make structural changes to other classes, like adding members or parents. ''' from __future__ import (division as _py3_division, print_function as _py3_print, unicode_literals as _py3_unicode, absolute_import as _py3_abs_imports) from types import MethodType, FunctionType from contextlib import contextmanager from xoutil.deprecation import deprecated as _deprecated from xoutil.names import strlist as strs __all__ = strs('complementor', 'contextualized', 'inject_dependencies', 'weaved') del strs def _update(attrs, *sources): ''' Updates attrs from sources: - Every source with a __name__ that is not a class is updated into attrs. - For every source that is a class, it's public attributes and all methods are updated into attrs. ''' from six import class_types, iteritems as iteritems_ attrs.update({str(f.__name__): f for f in sources if (not isinstance(f, class_types) and
# '''Utilities to inspect the CPython's stack.''' from __future__ import (division as _py3_division, print_function as _py3_print, unicode_literals as _py3_unicode) import inspect from xoutil.names import strlist as strs from six import PY3 as _py3k __all__ = strs('MAX_DEEP', 'getargvalues', 'error_info', 'object_info_finder', 'object_finder', 'track_value', 'iter_frames') del strs MAX_DEEP = 25 def getargvalues(frame): '''Inspects the given frame for arguments and returns a dictionary that maps parameters names to arguments values. If an `*` argument was passed then the key on the returning dictionary would be formatted as `<name-of-*-param>[index]`. For example in the function:: >>> def autocontained(a, limit, *margs, **ks):
FunctionType = _pm.FunctionType ModuleType = _pm.ModuleType del _pm, _copy_python_module_members from xoutil._values import Unset as _unset from collections import Mapping # FIXME: [med] Reintroduce UnsetType or deprecate it here. from xoutil._values import UnsetType # noqa from xoutil.names import strlist as strs __all__ = strs('mro_dict', 'UnsetType', 'DictProxyType', 'SlotWrapperType', 'is_iterable', 'is_collection', 'is_string_like', 'is_scalar', 'is_staticmethod', 'is_classmethod', 'is_instancemethod', 'is_slotwrapper', 'is_module', 'Required', 'NoneType', 'new_class', 'prepare_class') del strs #: The type of methods that are builtin in Python. #: #: This is roughly the type of the ``object.__getattribute__`` method. WrapperDescriptorType = SlotWrapperType = type(object.__getattribute__) #: A compatible Py2 and Py3k DictProxyType, since it does not exists in Py3k. DictProxyType = type(object.__dict__) import sys _pypy = hasattr(sys, 'pypy_version_info')
:mod:`os.path` standard module. ''' from __future__ import (division as _py3_division, print_function as _py3_print, unicode_literals as _py3_unicode) import sys from os.path import (abspath, expanduser, dirname, sep, normpath, join as _orig_join) from xoutil.functools import power as pow_ from xoutil.names import strlist as strs __all__ = strs('abspath', 'expanduser', 'dirname', 'sep', 'normpath', 'rtrim', 'fix_encoding', 'join', 'normalize_path', 'shorten_module_filename', 'shorten_user') del strs # TODO: import all in "from os.path import *" rtrim = lambda path, n=1: pow_(dirname, n)(normalize_path(path)) rtrim.__doc__ = """Trims the last `n` components of the pathname `path`. This basically applies `n` times the function `os.path.dirname` to `path`. `path` is normalized before proceeding (but not tested to exists). .. versionchanged:: 1.5.5 `n` defaults to 1. In this case rtrim is identical to :func:`os.path.dirname`.
''' from __future__ import (division as _py3_division, print_function as _py3_print, unicode_literals as _py3_unicode, absolute_import as _py3_abs_import) from xoutil._local import local as _local from xoutil.objects import metaclass from xoutil.collections import StackedDict from xoutil.names import strlist as strs __all__ = strs('Context', 'context', 'NulContext') del strs class LocalData(_local): def __init__(self): super(LocalData, self).__init__() self.contexts = {} _data = LocalData() class MetaContext(type(StackedDict)): def __len__(self): return len(_data.contexts)
# Author: Medardo Rodriguez # Contributors: see CONTRIBUTORS and HISTORY file # # This is free software; you can redistribute it and/or modify it under the # terms of the LICENCE attached (see LICENCE file) in the distribution # package. '''Tool to show a progress percent in the terminal.''' from __future__ import (division as _py3_division, print_function as _py3_print, unicode_literals as _py3_unicode) from xoutil.names import strlist as strs __all__ = strs('Progress') del strs _HELIX = '|/-\\' class Progress(object): ''' Print a progress percent to the console. Also the elapsed and the estimated times. To signal an increment in progress just call the instance and (optionally) pass a message like in:: progress = Progress(10)
Adds the ability to generate new passwords using a source pass-phrase and a secury strong level. ''' from __future__ import (division as _py3_division, print_function as _py3_print, unicode_literals as _py3_unicode, absolute_import as _py3_abs_imports) from xoutil.names import strlist as strs __all__ = strs('PASS_PHRASE_LEVEL_BASIC', 'PASS_PHRASE_LEVEL_MAPPED', 'PASS_PHRASE_LEVEL_MAPPED_MIXED', 'PASS_PHRASE_LEVEL_MAPPED_DATED', 'PASS_PHRASE_LEVEL_STRICT', 'generate_password') del strs #: The most basic level (less ) for the password generation. PASS_PHRASE_LEVEL_BASIC = 0 #: A level for simply mapping of several chars. PASS_PHRASE_LEVEL_MAPPED = 1 #: Another "stronger" mapping level. PASS_PHRASE_LEVEL_MAPPED_MIXED = 2 #: Appends the year after mapping.
from __future__ import (division as _py3_division, print_function as _py3_print, unicode_literals as _py3_unicode, absolute_import) from re import compile as _regex_compile from ast import parse as _ast_parse from six import string_types as _str_base from xoutil.functools import partial _ast_parse = partial(_ast_parse, filename="<annotations>", mode="eval") from xoutil.decorator.meta import decorator from xoutil.names import strlist as strs __all__ = strs('annotate') del strs _SIGNATURE = _regex_compile(r'''(?ixm) \( # Required opening for the argumens (?P<args>(.)*) \)\s* # Required close (?:->\s*(?P<return>.+))?$ ''') _ARG_SEP = _regex_compile(r'(?im)^\*{0,2}(?P<argname>[_\w\d]+)\s*:') def _split_signature(signature): signature = (signature.strip() if isinstance(signature, _str_base) else '')
# # This is free software; you can redistribute it and/or modify it under the # terms of the LICENCE attached (see LICENCE file) in the distribution # package. # # Created on Jun 28, 2011 '''Utils for Web applications.''' from __future__ import (division as _py3_division, print_function as _py3_print, unicode_literals as _py3_unicode) from xoutil.names import strlist as strs __all__ = strs('slugify') del strs def slugify(s, entities=True, decimal=True, hexadecimal=True): ''' Normalizes string, converts to lower-case, removes non-alpha characters, and converts spaces to hyphens. Parts from http://www.djangosnippets.org/snippets/369/ >>> slugify("Manuel Vázquez Acosta") # doctest: +SKIP 'manuel-vazquez-acosta' If `s` and `entities` is True (the default) all HTML entities are replaced by its equivalent character before normalization::
''' Regular expressions and validation functions for several identifiers. ''' from __future__ import (division as _py3_division, print_function as _py3_print, unicode_literals as _py3_unicode) from re import compile as _regex_compile from xoutil.eight import string_types from xoutil.names import strlist as strs __all__ = strs('is_valid_identifier', 'is_valid_full_identifier', 'is_valid_public_identifier', 'is_valid_slug') del strs # TODO: In Py3k "ña" is a valid identifier and this regex won't allow it _IDENTIFIER_REGEX = _regex_compile('(?i)^[_a-z][\w]*$') def is_valid_identifier(name): '''Returns True if `name` a valid Python identifier. .. note:: Only Python 2's version of valid identifier. This means that some Python 3 valid identifiers are not considered valid. This helps to keep things working the same in Python 2 and 3.
from __future__ import division as _py3_division, print_function as _py3_print, unicode_literals as _py3_unicode import sys from os.path import abspath, expanduser, dirname, sep, normpath, join as _orig_join from xoutil.functools import power as pow_ from xoutil.names import strlist as strs __all__ = strs( "abspath", "expanduser", "dirname", "sep", "normpath", "rtrim", "fix_encoding", "join", "normalize_path", "shorten_module_filename", "shorten_user", ) del strs # TODO: import all in "from os.path import *" rtrim = lambda path, n=1: pow_(dirname, n)(normalize_path(path)) rtrim.__doc__ = """Trims the last `n` components of the pathname `path`. This basically applies `n` times the function `os.path.dirname` to `path`.
'''Extensions the `subprocess` module in the standard library.''' from __future__ import (division as _py3_division, print_function as _py3_print, unicode_literals as _py3_unicode, absolute_import as _py3_abs_imports) import subprocess as _pm from xoutil.modules import copy_members as _copy_members _copy_members(_pm) Popen = _pm.Popen PIPE = _pm.PIPE from xoutil.names import strlist as strs __all__ = strs('call_and_check_output') __all__.extend(getattr(_pm, '__all__', dir(_pm))) del strs, _pm, _copy_members def call_and_check_output(*popenargs, **kwargs): '''Combines `call` and `check_output`. Returns a tuple ``(returncode, output, err_output)``. ''' if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') process = Popen(stdout=PIPE, *popenargs, **kwargs) output, err = process.communicate() retcode = process.poll() return (retcode, output, err)
'''An extension to :mod:`xoutil.aop.classical` that allows to hook *before* and *around* the :func:`~xoutil.aop.classical.weave` itself. ''' from __future__ import (division as _py3_division, print_function as _py3_print, unicode_literals as _py3_unicode, absolute_import) from xoutil.aop.classical import weave as classical_weave from xoutil.deprecation import deprecated as _deprecated from xoutil.names import strlist as strs __all__ = strs('weave') del strs @_deprecated('None', msg="This entire module is deprecated and will be " "removed.", removed_in_version='1.6.0') def weave(aspect, target): '''Similar to :func:`xoutil.aop.classical.weave` but introduces _before_weave and _around_weave hooks to the weaving process:: >>> class Foobar(object): ... def echo(self, what): ... return what >>> class FooAspect(object): ... @classmethod