sys._getframe.f_globals

Here are the examples of the python api sys._getframe.f_globals taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

55 Examples 7

Page 1 Selected Page 2

Example 1

def register_func(name, func):
    if name not in __all__:
        raise ValueError("%s not a dual function." % name)
    f = sys._getframe(0).f_globals
    _restore_dict[name] = f[name]
    f[name] = func

Example 2

Project: pluginbase
License: View license
Source File: pluginbase.py
Function: plugin_import
    def plugin_import(self, name, globals=None, locals=None,
                      fromlist=None, level=None):
        if level is None:
            # set the level to the default value specific to this python version
            level = -1 if PY2 else 0
        import_name = name
        if self.enabled:
            ref_globals = globals
            if ref_globals is None:
                ref_globals = sys._getframe(1).f_globals
            space = _discover_space(name, ref_globals)
            if space is not None:
                actual_name = space._rewrite_module_path(name)
                if actual_name is not None:
                    import_name = actual_name

        return self._system_import(import_name, globals, locals,
                                   fromlist, level)

Example 3

Project: robothon
License: View license
Source File: dual.py
Function: register_func
def register_func(name, func):
    if name not in __all__:
        raise ValueError, "%s not a dual function." % name
    f = sys._getframe(0).f_globals
    _restore_dict[name] = f[name]
    f[name] = func

Example 4

Project: cgstudiomap
License: View license
Source File: utils.py
def zipImported(ldr=None):
    try:
        if not ldr:
            ldr = sys._getframe(1).f_globals['__loader__']
        from zipimport import zipimporter
        return ldr if isinstance(ldr,zipimporter) else None
    except:
        return None

Example 5

Project: django-dbsettings
License: View license
Source File: group.py
Function: add
    def __add__(self, other):
        if not isinstance(other, Group):
            raise NotImplementedError('Groups may only be added to other groups.')

        attrs = dict(self._settings + other._settings)
        attrs['__module__'] = sys._getframe(1).f_globals['__name__']
        return type('Group', (Group,), attrs)(copy=False)

Example 6

Project: NimLime
License: View license
Source File: configuration.py
Function: debug_print
def debug_print(*args):
    """
    Print when debugging.
    :type args: Any
    """
    if in_debug_mode:
        module_name = sys._getframe(0).f_globals['__name__']
        res = []
        for o in args:
            if isinstance(o, str):
                res.append(o)
            else:
                res.append(pformat(o))
        print(module_name, ':', ' '.join(res))

Example 7

Project: PyIB
License: View license
Source File: tenjin.py
Function: read_template_file
    def read_template_file(self, filename, _context, _globals):
        if not self.preprocess:
            return open(filename).read()
        if _context is None:
            _context = {}
        if not _context.has_key('_engine'):
            self.hook_context(_context)
        if _globals is None:
            _globals = sys._getframe(2).f_globals
        preprocessor = Preprocessor(filename)
        return preprocessor.render(_context, globals=_globals)

Example 8

Project: robothon
License: View license
Source File: dual.py
Function: restore_func
def restore_func(name):
    if name not in __all__:
        raise ValueError, "%s not a dual function." % name
    try:
        val = _restore_dict[name]
    except KeyError:
        return
    else:
        sys._getframe(0).f_globals[name] = val

Example 9

Project: morepath
License: View license
Source File: autosetup.py
Function: caller_module
def caller_module(level=2):
    """Give module where calling function is defined.

    :level: levels deep to look up the stack frame
    :return: a Python module
    """
    module_globals = sys._getframe(level).f_globals
    module_name = module_globals.get('__name__') or '__main__'
    module = sys.modules[module_name]
    return module

Example 10

Project: neomodel
License: View license
Source File: relationship_manager.py
Function: init
    def __init__(self, relation_type, cls_name, direction, manager=RelationshipManager, model=None):
        self.module_name = sys._getframe(4).f_globals['__name__']
        if '__file__' in sys._getframe(4).f_globals:
            self.module_file = sys._getframe(4).f_globals['__file__']
        self._raw_class = cls_name
        self.manager = manager
        self.definition = {}
        self.definition['relation_type'] = relation_type
        self.definition['direction'] = direction
        self.definition['model'] = model

Example 11

Project: rst2pdf
License: View license
Source File: tenjin.py
Function: get_template
    def get_template(self, template_name, _context=None, _globals=None):
        """Return template object.
           If template object has not registered, template engine creates
           and registers template object automatically.
        """
        template = self.templates.get(template_name)
        t = template
        if t is None or t.timestamp and t.filename and t.timestamp < os.path.getmtime(t.filename):
            filename = self.find_template_file(template_name)
            # context and globals are passed only for preprocessing
            if _globals is None:
                _globals = sys._getframe(1).f_globals
            template = self.create_template(filename, _context, _globals)
            self.register_template(template_name, template)
        return template

Example 12

Project: jogging
License: View license
Source File: __init__.py
Function: log
    def log(self, level, msg, source=None, *args, **kwargs):
        import sys
        
        if not source:
            source = sys._getframe(1).f_globals['__name__']

        logger = self.get_logger(source)

        
        if sys.version_info >= (2, 5):
            kwargs.update(source=source)
            logger.log(level=self.LOGGING_LEVELS[level], msg=msg, extra=kwargs, *args)
        else:
            logger.log(level=self.LOGGING_LEVELS[level], msg=msg, *args, **kwargs)

Example 13

Project: multiversion
License: View license
Source File: multiversion.py
def get_actual_module(name, stacklevel=1):
    """From the caller's view this returns the actual module that was
    requested for a given name.
    """
    globals = sys._getframe(stacklevel).f_globals
    cache_key = get_cache_key(name, globals)
    if cache_key is not None:
        full_name = '%s.%s' % (get_internal_name(cache_key), name)
        return sys.modules[full_name]

Example 14

Project: AWS-Lambda-ML-Microservice-Skeleton
License: View license
Source File: dual.py
Function: restore_func
def restore_func(name):
    if name not in __all__:
        raise ValueError("%s not a dual function." % name)
    try:
        val = _restore_dict[name]
    except KeyError:
        return
    else:
        sys._getframe(0).f_globals[name] = val

Example 15

Project: PFramer
License: View license
Source File: pluginbase.py
Function: plugin_import
    def plugin_import(self, name, globals=None, locals=None,
                      fromlist=None, level=0):
        import_name = name
        if self.enabled:
            ref_globals = globals
            if ref_globals is None:
                ref_globals = sys._getframe(1).f_globals
            space = _discover_space(name, ref_globals)
            if space is not None:
                actual_name = space._rewrite_module_path(name)
                if actual_name is not None:
                    import_name = actual_name

        return self._system_import(import_name, globals, locals,
                                   fromlist, level)

Example 16

Project: python-gflags
License: View license
Source File: __init__.py
def DISCLAIM_key_flags():  # pylint: disable=g-bad-name
  """Declares that the current module will not define any more key flags.

  Normally, the module that calls the DEFINE_xxx functions claims the
  flag to be its key flag.  This is undesirable for modules that
  define additional DEFINE_yyy functions with its own flag parsers and
  serializers, since that module will accidentally claim flags defined
  by DEFINE_yyy as its key flags.  After calling this function, the
  module disclaims flag definitions thereafter, so the key flags will
  be correctly attributed to the caller of DEFINE_yyy.

  After calling this function, the module will not be able to define
  any more flags.  This function will affect all FlagValues objects.
  """
  globals_for_caller = sys._getframe(1).f_globals  # pylint: disable=protected-access
  module, _ = _helpers.GetModuleObjectAndName(globals_for_caller)
  _helpers.disclaim_module_ids.add(id(module))

Example 17

Project: rst2pdf
License: View license
Source File: tenjin.py
Function: read_template_file
    def read_template_file(self, filename, _context, _globals):
        if not self.preprocess:
            return open(filename).read()
        if _context is None:
            _context = {}
        if '_engine' not in _context:
            self.hook_context(_context)
        if _globals is None:
            _globals = sys._getframe(2).f_globals
        preprocessor = Preprocessor(filename)
        return preprocessor.render(_context, globals=_globals)

Example 18

Project: Rhetoric
License: View license
Source File: path.py
Function: caller_module
def caller_module(level=2, sys=sys):
    """This function is taken from Pyramid Web Framework - ``pyramid.path.caller_module``."""
    module_globals = sys._getframe(level).f_globals
    module_name = module_globals.get('__name__') or '__main__'
    module = sys.modules[module_name]
    return module

Example 19

Project: numexpr
License: View license
Source File: necompiler.py
def getContext(kwargs, frame_depth=1):
    d = kwargs.copy()
    context = {}
    for name, allowed, default in context_info:
        value = d.pop(name, default)
        if value in allowed:
            context[name] = value
        else:
            raise ValueError("'%s' must be one of %s" % (name, allowed))

    if d:
        raise ValueError("Unknown keyword argument '%s'" % d.popitem()[0])
    if context['truediv'] == 'auto':
        caller_globals = sys._getframe(frame_depth + 1).f_globals
        context['truediv'] = \
            caller_globals.get('division', None) == __future__.division

    return context

Example 20

Project: mdcs-py
License: View license
Source File: Base.py
    def isUser_Function(self, name):
        try:
            frame = sys._getframe(0).f_globals

            module = frame[self.CMODULE_NAME]
            cls = getattr(module, self.CCLASS_NAME)
            instance = cls()
            fnc = getattr(instance, name)
        except:
            return False

        return True

Example 21

Project: mdcs-py
License: View license
Source File: Base.py
    def invoke_user_function(self, name, data):       # MDCS is always passed on which is the MD Configuration Script XML DOM
        ret = False
        try:
            frame = sys._getframe(0).f_globals  # default to first stack.

            module = frame[self.CMODULE_NAME]
            cls = getattr(module, self.CCLASS_NAME)
            instance = cls()
            fnc = getattr(instance, name)
            try:
                ret = fnc(data)
            except Exception as inf:
                self.log('Executing user defined function (%s)' % (name), self.const_critical_text)
                self.log(str(inf), self.const_critical_text)
                return False
        except Exception as inf:
            self.log('Error: please check if user function (%s) is found in class (%s) of MDCS_UC module.' % (name, CCLASS_NAME), self.const_critical_text)
            self.log(str(inf), self.const_critical_text)
            return False

        return ret

Example 22

Project: graphene
License: View license
Source File: enum.py
Function: create
    def _create_(cls, class_name, names=None, module=None, type=None, start=1):
        """Convenience method to create a new Enum class.

        `names` can be:

        * A string containing member names, separated either with spaces or
          commas.  Values are auto-numbered from 1.
        * An iterable of member names.  Values are auto-numbered from 1.
        * An iterable of (member name, value) pairs.
        * A mapping of member name -> value.

        """
        if pyver < 3.0:
            # if class_name is unicode, attempt a conversion to ASCII
            if isinstance(class_name, unicode):
                try:
                    class_name = class_name.encode('ascii')
                except UnicodeEncodeError:
                    raise TypeError('%r is not representable in ASCII' % class_name)
        metacls = cls.__class__
        if type is None:
            bases = (cls, )
        else:
            bases = (type, cls)
        classdict = metacls.__prepare__(class_name, bases)
        _order_ = []

        # special processing needed for names?
        if isinstance(names, basestring):
            names = names.replace(',', ' ').split()
        if isinstance(names, (tuple, list)) and isinstance(names[0], basestring):
            names = [(e, i + start) for (i, e) in enumerate(names)]

        # Here, names is either an iterable of (name, value) or a mapping.
        item = None  # in case names is empty
        for item in names:
            if isinstance(item, basestring):
                member_name, member_value = item, names[item]
            else:
                member_name, member_value = item
            classdict[member_name] = member_value
            _order_.append(member_name)
        # only set _order_ in classdict if name/value was not from a mapping
        if not isinstance(item, basestring):
            classdict['_order_'] = ' '.join(_order_)
        enum_class = metacls.__new__(metacls, class_name, bases, classdict)

        # TODO: replace the frame hack if a blessed way to know the calling
        # module is ever developed
        if module is None:
            try:
                module = _sys._getframe(2).f_globals['__name__']
            except (AttributeError, ValueError):
                pass
        if module is None:
            _make_class_unpicklable(enum_class)
        else:
            enum_class.__module__ = module

        return enum_class

Example 23

Project: fatoptimizer
License: View license
Source File: benchmark.py
def bench(stmt, *, setup='', repeat=10**5, number=10):
    caller_globals = sys._getframe(1).f_globals
    timer = timeit.Timer(stmt, setup=setup, globals=caller_globals)
    return min(timer.repeat(repeat=repeat, number=number)) / number

Example 24

Project: fwlite
License: View license
Source File: __init__.py
Function: create
    def _create_(cls, class_name, names=None, module=None, type=None, start=1):
        """Convenience method to create a new Enum class.

        `names` can be:

        * A string containing member names, separated either with spaces or
          commas.  Values are auto-numbered from 1.
        * An iterable of member names.  Values are auto-numbered from 1.
        * An iterable of (member name, value) pairs.
        * A mapping of member name -> value.

        """
        if pyver < 3.0:
            # if class_name is unicode, attempt a conversion to ASCII
            if isinstance(class_name, unicode):
                try:
                    class_name = class_name.encode('ascii')
                except UnicodeEncodeError:
                    raise TypeError('%r is not representable in ASCII' % class_name)
        metacls = cls.__class__
        if type is None:
            bases = (cls, )
        else:
            bases = (type, cls)
        classdict = metacls.__prepare__(class_name, bases)
        __order__ = []

        # special processing needed for names?
        if isinstance(names, basestring):
            names = names.replace(',', ' ').split()
        if isinstance(names, (tuple, list)) and isinstance(names[0], basestring):
            names = [(e, i+start) for (i, e) in enumerate(names)]

        # Here, names is either an iterable of (name, value) or a mapping.
        item = None  # in case names is empty
        for item in names:
            if isinstance(item, basestring):
                member_name, member_value = item, names[item]
            else:
                member_name, member_value = item
            classdict[member_name] = member_value
            __order__.append(member_name)
        # only set __order__ in classdict if name/value was not from a mapping
        if not isinstance(item, basestring):
            classdict['__order__'] = ' '.join(__order__)
        enum_class = metacls.__new__(metacls, class_name, bases, classdict)

        # TODO: replace the frame hack if a blessed way to know the calling
        # module is ever developed
        if module is None:
            try:
                module = _sys._getframe(2).f_globals['__name__']
            except (AttributeError, ValueError):
                pass
        if module is None:
            _make_class_unpicklable(enum_class)
        else:
            enum_class.__module__ = module

        return enum_class

Example 25

Project: zipline
License: View license
Source File: sentinel.py
Function: sentinel
def sentinel(name, doc=None):
    try:
        value = sentinel._cache[name]  # memoized
    except KeyError:
        pass
    else:
        if doc == value.__doc__:
            return value

        raise ValueError(dedent(
            """\
            New sentinel value %r conflicts with an existing sentinel of the
            same name.
            Old sentinel docstring: %r
            New sentinel docstring: %r
            Resolve this conflict by changing the name of one of the sentinels.
            """,
        ) % (name, value.__doc__, doc))

    @object.__new__   # bind a single instance to the name 'Sentinel'
    class Sentinel(object):
        __doc__ = doc
        __slots__ = ('__weakref__',)
        __name__ = name

        def __new__(cls):
            raise TypeError('cannot create %r instances' % name)

        def __repr__(self):
            return 'sentinel(%r)' % name

        def __reduce__(self):
            return sentinel, (name, doc)

        def __deepcopy__(self, _memo):
            return self

        def __copy__(self):
            return self

    cls = type(Sentinel)
    try:
        # traverse up one frame to find the module where this is defined
        cls.__module__ = sys._getframe(1).f_globals['__name__']
    except (ValueError, KeyError):
        # Couldn't get the name from the calling scope, just use None.
        cls.__module__ = None

    sentinel._cache[name] = Sentinel  # cache result
    return Sentinel

Example 26

Project: trac-git-plugin
License: View license
Source File: future27.py
Function: namedtuple
  def namedtuple(typename, field_names, verbose=False):
    """Returns a new subclass of tuple with named fields.

    >>> Point = namedtuple('Point', 'x y')
    >>> Point.__doc__                   # docstring for the new class
    'Point(x, y)'
    >>> p = Point(11, y=22)             # instantiate with positional args or keywords
    >>> p[0] + p[1]                     # indexable like a plain tuple
    33
    >>> x, y = p                        # unpack like a regular tuple
    >>> x, y
    (11, 22)
    >>> p.x + p.y                       # fields also accessable by name
    33
    >>> d = p._asdict()                 # convert to a dictionary
    >>> d['x']
    11
    >>> Point(**d)                      # convert from a dictionary
    Point(x=11, y=22)
    >>> p._replace(x=100)               # _replace() is like str.replace() but targets named fields
    Point(x=100, y=22)

    """

    # Parse and validate the field names.  Validation serves two purposes,
    # generating informative error messages and preventing template injection attacks.
    if isinstance(field_names, basestring):
        field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
    field_names = tuple(map(str, field_names))
    for name in (typename,) + field_names:
        if not all(c.isalnum() or c=='_' for c in name):
            raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
        if _iskeyword(name):
            raise ValueError('Type names and field names cannot be a keyword: %r' % name)
        if name[0].isdigit():
            raise ValueError('Type names and field names cannot start with a number: %r' % name)
    seen_names = set()
    for name in field_names:
        if name.startswith('_'):
            raise ValueError('Field names cannot start with an underscore: %r' % name)
        if name in seen_names:
            raise ValueError('Encountered duplicate field name: %r' % name)
        seen_names.add(name)

    # Create and fill-in the class template
    numfields = len(field_names)
    argtxt = repr(field_names).replace("'", "")[1:-1]   # tuple repr without parens or quotes
    reprtxt = ', '.join('%s=%%r' % name for name in field_names)
    dicttxt = ', '.join('%r: t[%d]' % (name, pos) for pos, name in enumerate(field_names))
    template = '''class %(typename)s(tuple):
        '%(typename)s(%(argtxt)s)' \n
        __slots__ = () \n
        _fields = %(field_names)r \n
        def __new__(cls, %(argtxt)s):
            return tuple.__new__(cls, (%(argtxt)s)) \n
        @classmethod
        def _make(cls, iterable, new=tuple.__new__, len=len):
            'Make a new %(typename)s object from a sequence or iterable'
            result = new(cls, iterable)
            if len(result) != %(numfields)d:
                raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
            return result \n
        def __repr__(self):
            return '%(typename)s(%(reprtxt)s)' %% self \n
        def _asdict(t):
            'Return a new dict which maps field names to their values'
            return {%(dicttxt)s} \n
        def _replace(self, **kwds):
            'Return a new %(typename)s object replacing specified fields with new values'
            result = self._make(map(kwds.pop, %(field_names)r, self))
            if kwds:
                raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
            return result \n
        def __getnewargs__(self):
            return tuple(self) \n\n''' % locals()
    for i, name in enumerate(field_names):
        template += '        %s = property(itemgetter(%d))\n' % (name, i)
    if verbose:
        print template

    # Execute the template string in a temporary namespace and
    # support tracing utilities by setting a value for frame.f_globals['__name__']
    namespace = dict(itemgetter=_itemgetter, __name__='namedtuple_%s' % typename)
    try:
        exec template in namespace
    except SyntaxError, e:
        raise SyntaxError(e.message + ':\n' + template)
    result = namespace[typename]

    # For pickling to work, the __module__ variable needs to be set to the frame
    # where the named tuple is created.  Bypass this step in enviroments where
    # sys._getframe is not defined (Jython for example).
    if hasattr(_sys, '_getframe'):
        result.__module__ = _sys._getframe(1).f_globals['__name__']

    return result

Example 27

Project: ironpython3
License: View license
Source File: enum.py
Function: create
    def _create_(cls, class_name, names=None, *, module=None, qualname=None, type=None):
        """Convenience method to create a new Enum class.

        `names` can be:

        * A string containing member names, separated either with spaces or
          commas.  Values are auto-numbered from 1.
        * An iterable of member names.  Values are auto-numbered from 1.
        * An iterable of (member name, value) pairs.
        * A mapping of member name -> value.

        """
        metacls = cls.__class__
        bases = (cls, ) if type is None else (type, cls)
        classdict = metacls.__prepare__(class_name, bases)

        # special processing needed for names?
        if isinstance(names, str):
            names = names.replace(',', ' ').split()
        if isinstance(names, (tuple, list)) and isinstance(names[0], str):
            names = [(e, i) for (i, e) in enumerate(names, 1)]

        # Here, names is either an iterable of (name, value) or a mapping.
        for item in names:
            if isinstance(item, str):
                member_name, member_value = item, names[item]
            else:
                member_name, member_value = item
            classdict[member_name] = member_value
        enum_class = metacls.__new__(metacls, class_name, bases, classdict)

        # TODO: replace the frame hack if a blessed way to know the calling
        # module is ever developed
        if module is None:
            try:
                module = sys._getframe(2).f_globals['__name__']
            except (AttributeError, ValueError) as exc:
                pass
        if module is None:
            _make_class_unpicklable(enum_class)
        else:
            enum_class.__module__ = module
        if qualname is not None:
            enum_class.__qualname__ = qualname

        return enum_class

Example 28

Project: PyIB
License: View license
Source File: tenjin.py
Function: render
    def render(self, context=None, globals=None, _buf=None):
        """Evaluate python code with context dictionary.
           If _buf is None then return the result of evaluation as str,
           else return None.

           context:dict (=None)
             Context object to evaluate. If None then new dict is created.
           globals:dict (=None)
             Global object. If None then globals() is used.
           _buf:list (=None)
             If None then new list is created.

           ex.
             >>> import tenjin
             >>> from tenjin.helpers import escape, to_str
             >>> template = tenjin.Template('example.pyhtml')
             >>> context = {'items': ['foo','bar','baz'], 'title': 'example'}
             >>> output = template.evaluate(context)
             >>> print output,
        """
        if context is None:
            locals = context = {}
        elif self.args is None:
            locals = context.copy()
        else:
            locals = {}
            if context.has_key('_engine'):
                context.get('_engine').hook_context(locals)
        locals['_context'] = context
        if globals is None:
            globals = sys._getframe(1).f_globals
        bufarg = _buf
        if _buf is None:
            _buf = []
        locals['_buf'] = _buf
        if not self.bytecode:
            self.compile()
        exec self.bytecode in globals, locals
        if bufarg is None:
            s = ''.join(_buf)
            #if self.encoding:
            #    s = s.encode(self.encoding)
            return s
        else:
            return None

Example 29

Project: rst2pdf
License: View license
Source File: tenjin.py
Function: render
    def render(self, context=None, globals=None, _buf=None):
        """Evaluate python code with context dictionary.
           If _buf is None then return the result of evaluation as str,
           else return None.

           context:dict (=None)
             Context object to evaluate. If None then new dict is created.
           globals:dict (=None)
             Global object. If None then globals() is used.
           _buf:list (=None)
             If None then new list is created.

           ex.
             >>> import tenjin
             >>> from tenjin.helpers import escape, to_str
             >>> template = tenjin.Template('example.pyhtml')
             >>> context = {'items': ['foo','bar','baz'], 'title': 'example'}
             >>> output = template.evaluate(context)
             >>> print output,
        """
        if context is None:
            locals = context = {}
        elif self.args is None:
            locals = context.copy()
        else:
            locals = {}
            if '_engine' in context:
                context.get('_engine').hook_context(locals)
        locals['_context'] = context
        if globals is None:
            globals = sys._getframe(1).f_globals
        bufarg = _buf
        if _buf is None:
            _buf = []
        locals['_buf'] = _buf
        if not self.bytecode:
            self.compile()
        exec(self.bytecode, globals, locals)
        if bufarg is None:
            s = ''.join(_buf)
            #if self.encoding:
            #    s = s.encode(self.encoding)
            return s
        else:
            return None

Example 30

Project: mythbox
License: View license
Source File: interface.py
Function: init
    def __init__(self, name, bases=(), attrs=None, __doc__=None,
                 __module__=None):

        if attrs is None:
            attrs = {}

        if __module__ is None:
            __module__ = attrs.get('__module__')
            if isinstance(__module__, str):
                del attrs['__module__']
            else:
                try:
                    # Figure out what module defined the interface.
                    # This is how cPython figures out the module of
                    # a class, but of course it does it in C. :-/
                    __module__ = sys._getframe(1).f_globals['__name__']
                except (AttributeError, KeyError):
                    pass

        self.__module__ = __module__

        d = attrs.get('__doc__')
        if d is not None:
            if not isinstance(d, Attribute):
                if __doc__ is None:
                    __doc__ = d
                del attrs['__doc__']

        if __doc__ is None:
            __doc__ = ''

        Element.__init__(self, name, __doc__)

        tagged_data = attrs.pop(TAGGED_DATA, None)
        if tagged_data is not None:
            for key, val in tagged_data.items():
                self.setTaggedValue(key, val)

        for base in bases:
            if not isinstance(base, InterfaceClass):
                raise TypeError('Expected base interfaces')

        Specification.__init__(self, bases)

        # Make sure that all recorded attributes (and methods) are of type
        # `Attribute` and `Method`
        for name, attr in attrs.items():
            if isinstance(attr, Attribute):
                attr.interface = self
                if not attr.__name__:
                    attr.__name__ = name
            elif isinstance(attr, FunctionType):
                attrs[name] = fromFunction(attr, self, name=name)
            elif attr is _decorator_non_return:
                del attrs[name]
            else:
                raise InvalidInterface("Concrete attribute, " + name)

        self.__attrs = attrs

        self.__identifier__ = "%s.%s" % (self.__module__, self.__name__)

Example 31

Project: jogging
License: View license
Source File: __init__.py
Function: info
    def info(self, msg, *args, **kwargs):
        caller = sys._getframe(1).f_globals['__name__']
        self.log('info', msg, caller, *args, **kwargs)

Example 32

Project: TwistedBot
License: View license
Source File: interface.py
Function: init
    def __init__(self, name, bases=(), attrs=None, __doc__=None,
                 __module__=None):

        if attrs is None:
            attrs = {}

        if __module__ is None:
            __module__ = attrs.get('__module__')
            if isinstance(__module__, str):
                del attrs['__module__']
            else:
                try:
                    # Figure out what module defined the interface.
                    # This is how cPython figures out the module of
                    # a class, but of course it does it in C. :-/
                    __module__ = sys._getframe(1).f_globals['__name__']
                except (AttributeError, KeyError): #pragma NO COVERAGE
                    pass

        self.__module__ = __module__

        d = attrs.get('__doc__')
        if d is not None:
            if not isinstance(d, Attribute):
                if __doc__ is None:
                    __doc__ = d
                del attrs['__doc__']

        if __doc__ is None:
            __doc__ = ''

        Element.__init__(self, name, __doc__)

        tagged_data = attrs.pop(TAGGED_DATA, None)
        if tagged_data is not None:
            for key, val in tagged_data.items():
                self.setTaggedValue(key, val)

        for base in bases:
            if not isinstance(base, InterfaceClass):
                raise TypeError('Expected base interfaces')

        Specification.__init__(self, bases)

        # Make sure that all recorded attributes (and methods) are of type
        # `Attribute` and `Method`
        for name, attr in list(attrs.items()):
            if name in ('__locals__', '__qualname__'):
                # __locals__: Python 3 sometimes adds this.
                # __qualname__: PEP 3155 (Python 3.3+)
                del attrs[name]
                continue
            if isinstance(attr, Attribute):
                attr.interface = self
                if not attr.__name__:
                    attr.__name__ = name
            elif isinstance(attr, FunctionType):
                attrs[name] = fromFunction(attr, self, name=name)
            elif attr is _decorator_non_return:
                del attrs[name]
            else:
                raise InvalidInterface("Concrete attribute, " + name)

        self.__attrs = attrs

        self.__identifier__ = "%s.%s" % (self.__module__, self.__name__)

Example 33

Project: badideas
License: View license
Source File: assname.py
Function: namedtuple
    def namedtuple(*names):
        rv = collections.namedtuple(assigned_name(), names)
        rv.__module__ = sys._getframe(1).f_globals['__name__']
        return rv

Example 34

Project: headphones
License: View license
Source File: enum.py
Function: create
    def _create_(cls, class_name, names=None, module=None, type=None):
        """Convenience method to create a new Enum class.

        `names` can be:

        * A string containing member names, separated either with spaces or
          commas.  Values are auto-numbered from 1.
        * An iterable of member names.  Values are auto-numbered from 1.
        * An iterable of (member name, value) pairs.
        * A mapping of member name -> value.

        """
        if pyver < 3.0:
            # if class_name is unicode, attempt a conversion to ASCII
            if isinstance(class_name, unicode):
                try:
                    class_name = class_name.encode('ascii')
                except UnicodeEncodeError:
                    raise TypeError('%r is not representable in ASCII' % class_name)
        metacls = cls.__class__
        if type is None:
            bases = (cls, )
        else:
            bases = (type, cls)
        classdict = metacls.__prepare__(class_name, bases)
        __order__ = []

        # special processing needed for names?
        if isinstance(names, basestring):
            names = names.replace(',', ' ').split()
        if isinstance(names, (tuple, list)) and isinstance(names[0], basestring):
            names = [(e, i+1) for (i, e) in enumerate(names)]

        # Here, names is either an iterable of (name, value) or a mapping.
        for item in names:
            if isinstance(item, basestring):
                member_name, member_value = item, names[item]
            else:
                member_name, member_value = item
            classdict[member_name] = member_value
            __order__.append(member_name)
        # only set __order__ in classdict if name/value was not from a mapping
        if not isinstance(item, basestring):
            classdict['__order__'] = ' '.join(__order__)
        enum_class = metacls.__new__(metacls, class_name, bases, classdict)

        # TODO: replace the frame hack if a blessed way to know the calling
        # module is ever developed
        if module is None:
            try:
                module = _sys._getframe(2).f_globals['__name__']
            except (AttributeError, ValueError):
                pass
        if module is None:
            _make_class_unpicklable(enum_class)
        else:
            enum_class.__module__ = module

        return enum_class

Example 35

Project: rst2pdf
License: View license
Source File: tenjin.py
Function: render
    def render(self, template_name, context=None, globals=None, layout=True):
        """Evaluate template with layout file and return result of evaluation.

           template_name:str
             Filename (ex. 'user_list.pyhtml') or short name (ex. ':list') of template.
           context:dict (=None)
             Context object to evaluate. If None then new dict is used.
           globals:dict (=None)
             Global context to evaluate. If None then globals() is used.
           layout:str or Bool(=True)
             If True, the default layout name specified in constructor is used.
             If False, no layout template is used.
             If str, it is regarded as layout template name.

           If temlate object related with the 'template_name' argument is not exist,
           engine generates a template object and register it automatically.
        """
        if context is None:
            context = {}
        if globals is None:
            globals = sys._getframe(1).f_globals
        self.hook_context(context)
        while True:
            # context and globals are passed to get_template() only for preprocessing
            template = self.get_template(template_name,  context, globals)
            content  = template.render(context, globals)
            layout   = context.pop('_layout', layout)
            if layout is True or layout is None:
                layout = self.layout
            if not layout:
                break
            template_name = layout
            layout = False
            context['_content'] = content
        context.pop('_content', None)
        return content

Example 36

Project: jogging
License: View license
Source File: __init__.py
Function: error
    def error(self, msg, *args, **kwargs):
        caller = sys._getframe(1).f_globals['__name__']
        self.log('error', msg, caller, *args, **kwargs)

Example 37

Project: pyxmpp
License: View license
Source File: interface_micro_impl.py
Function: init
    def __init__(self, name, bases = (), attrs = None, __doc__ = None, __module__ = None):
        if __module__ is None:
            if (attrs is not None and ('__module__' in attrs) and isinstance(attrs['__module__'], str)):
                __module__ = attrs['__module__']
                del attrs['__module__']
            else:
                __module__ = sys._getframe(1).f_globals['__name__']
        if __doc__ is not None:
            self.__doc__ = __doc__
        if attrs is not None and "__doc__" in attrs:
            del attrs["__doc__"]
        self.__module__ = __module__
        for base in bases:
            if not isinstance(base, InterfaceClass):
                raise TypeError, 'Interface bases must be Interfaces'
        if attrs is not None:
            for aname, attr in attrs.items():
                if not isinstance(attr, Attribute) and type(attr) is not FunctionType:
                    raise TypeError, 'Interface attributes must be Attributes o functions (%r found in %s)' % (attr, aname)
        self.__bases__ = bases
        self.__attrs = attrs
        self.__name__ = name
        self.__identifier__ = "%s.%s" % (self.__module__, self.__name__)

Example 38

Project: jogging
License: View license
Source File: __init__.py
Function: debug
    def debug(self, msg, *args, **kwargs):
        caller = sys._getframe(1).f_globals['__name__']
        self.log('debug', msg, caller, *args, **kwargs)

Example 39

Project: mprop
License: View license
Source File: mprop.py
def init(glbls=None):
    '''
    Initialize the module-level properties/descriptors for the module that
    this function is being called from. Or, if a globals dictionary is passed,
    initialize the module-level properties/descriptors for the module that
    those globals came from.

    See the readme for more docuementation.
    '''
    # Pull the module context in which the init function was called.
    init = glbls is None
    if init:
        glbls = sys._getframe(1).f_globals
    name = glbls['__name__']

    module = sys.modules[name]
    if isinstance(sys.modules[name], types.ModuleType):
        # Every module must have a new class to ensure that the module itself
        # has its own unique properties.
        class Module(object):
            def __repr__(self):
                return "<Module %r>"%(self.__name__,)

        module = Module()

        # Give the Module object and the Python module the same namespace.
        module.__dict__ = glbls

        # Keep a reference to the Module so that non-module properties can
        # reference properties via _pmodule.PROPERTY .
        module._pmodule = module

        # Keep a reference to the original module so the original module isn't
        # cleaned up after we've replaced the sys.modules entry (cleanup
        # mangles the module globals).
        module._module = sys.modules[name]

        # Replace the original module with this one.
        sys.modules[name] = module
    else:
        # Assume that module is one of our Module classes, fetch it here just
        # in case someone is using both init() and @mproperty together
        Module = type(module)

    if init:
        # Handle property assignment and global namespace cleanup
        _cleanup(Module, glbls)

    return module

Example 40

Project: pymel
License: View license
Source File: namedtuple.py
def namedtuple(typename, field_names, docAppend="", verbose=False):
    """ Returns a new subclass of tuple with named fields.

    >>> Point = namedtuple('Point', 'x, y')
    >>> Point.__doc__                   # docstring for the new class
    'Point(x, y)'
    >>> p = Point(11, y=22)             # instantiate with positional args or keywords
    >>> p[0] + p[1]                     # indexable like a plain tuple
    33
    >>> x, y = p                        # unpack like a regular tuple
    >>> x, y
    (11, 22)
    >>> p.x + p.y                       # fields also accessible by name
    33
    >>> d = p._asdict()                 # convert to a dictionary
    >>> d['x']
    11
    >>> Point(**d)                      # convert from a dictionary
    Point(x=11, y=22)
    >>> p._replace(x=100)               # _replace() is like str.replace() but targets named fields
    Point(x=100, y=22)

    """

    docAppend = docAppend.encode('string_escape')

    # Parse and validate the field names.  Validation serves two purposes,
    # generating informative error messages and preventing template injection attacks.
    if isinstance(field_names, basestring):
        field_names = field_names.replace(',', ' ').split()  # names separated by whitespace and/or commas
    field_names = tuple(field_names)
    for name in (typename,) + field_names:
        if not min(c.isalnum() or c == '_' for c in name):
            raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
        if _iskeyword(name):
            raise ValueError('Type names and field names cannot be a keyword: %r' % name)
        if name[0].isdigit():
            raise ValueError('Type names and field names cannot start with a number: %r' % name)
    seen_names = set()
    for name in field_names:
        if name.startswith('_'):
            raise ValueError('Field names cannot start with an underscore: %r' % name)
        if name in seen_names:
            raise ValueError('Encountered duplicate field name: %r' % name)
        seen_names.add(name)

    # Create and fill-in the class template
    # note in 2.6 collections use
    # def __getnewargs__(self):
    # return tuple(self)
    # instead of __reduce__ to provide unpickling capabilities

    numfields = len(field_names)
    argtxt = repr(field_names).replace("'", "")[1:-1]   # tuple repr without parens or quotes
    reprtxt = ', '.join('%s=%%r' % name for name in field_names)
    dicttxt = ', '.join('%r: t[%d]' % (name, pos) for pos, name in enumerate(field_names))
    template = '''class %(typename)s(tuple):
        '%(typename)s(%(argtxt)s)%(docAppend)s' \n
        __slots__ = () \n
        _fields = %(field_names)r \n
        def __new__(cls, %(argtxt)s):
            return tuple.__new__(cls, (%(argtxt)s)) \n
        @classmethod
        def _make(cls, iterable, new=tuple.__new__, len=len):
            'Make a new %(typename)s object from a sequence or iterable'
            result = new(cls, iterable)
            if len(result) != %(numfields)d:
                raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
            return result \n
        def __repr__(self):
            return '%(typename)s(%(reprtxt)s)' %% self \n
        def _asdict(t):
            'Return a new dict which maps field names to their values'
            return {%(dicttxt)s} \n
        def _replace(self, **kwds):
            'Return a new %(typename)s object replacing specified fields with new values'
            result = self._make(map(kwds.pop, %(field_names)r, self))
            if kwds:
                raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
            return result \n
        def __reduce__(self) :
            return ( self.__class__, tuple(self) ) \n\n''' % locals()
    for i, name in enumerate(field_names):
        template += '        %s = property(itemgetter(%d))\n' % (name, i)
    if verbose:
        print template

    # Execute the template string in a temporary namespace
    namespace = dict(itemgetter=_itemgetter)
    try:
        exec template in namespace
    except SyntaxError, e:
        raise SyntaxError(e.message + ':\n' + template)
    result = namespace[typename]

    # For pickling to work, the __module__ variable needs to be set to the frame
    # where the named tuple is created.  Bypass this step in enviroments where
    # sys._getframe is not defined (Jython for example).
    if hasattr(_sys, '_getframe'):
        result.__module__ = _sys._getframe(1).f_globals['__name__']

    return result

Example 41

Project: jogging
License: View license
Source File: __init__.py
Function: warning
    def warning(self, msg, *args, **kwargs):
        caller = sys._getframe(1).f_globals['__name__']
        self.log('warning', msg, caller, *args, **kwargs)

Example 42

Project: django-dbsettings
License: View license
Source File: group.py
    def __new__(cls, verbose_name=None, copy=True, app_label=None):
        # If not otherwise provided, set the module to where it was executed
        if '__module__' in cls.__dict__:
            module_name = cls.__dict__['__module__']
        else:
            module_name = sys._getframe(1).f_globals['__name__']

        attrs = [(k, v) for (k, v) in cls.__dict__.items() if isinstance(v, Value)]
        if copy:
            attrs = [(k, v.copy()) for (k, v) in attrs]
        attrs.sort(key=lambda a: a[1])

        for _, attr in attrs:
            attr.creation_counter = Value.creation_counter
            Value.creation_counter += 1
            if not hasattr(attr, 'verbose_name'):
                attr.verbose_name = verbose_name
            if app_label:
                attr._app = app_label
            register_setting(attr)

        attr_dict = dict(attrs + [('__module__', module_name)])

        # A new class is created so descriptors work properly
        # object.__new__ is necessary here to avoid recursion
        group = object.__new__(type('Group', (cls,), attr_dict))
        group._settings = attrs

        return group

Example 43

Project: jogging
License: View license
Source File: __init__.py
Function: critical
    def critical(self, msg, *args, **kwargs):
        caller = sys._getframe(1).f_globals['__name__']
        self.log('critical', msg, caller, *args, **kwargs)

Example 44

Project: pydgin
License: View license
Source File: sim.py
def init_sim( sim ):

  # this is a bit hacky: we get the global variables of the caller from
  # the stack frame to determine if this is being run top level and add
  # target function required by rpython toolchain

  caller_globals = sys._getframe(1).f_globals
  caller_name    = caller_globals[ "__name__" ]

  # add target function to top level

  caller_globals[ "target" ] = sim.target

  #-----------------------------------------------------------------------
  # main
  #-----------------------------------------------------------------------
  # Enables CPython simulation of our interpreter.
  if caller_name == "__main__":
    # enable debug flags in interpreted mode
    Debug.global_enabled = True
    sys.exit(sim.get_entry_point()( sys.argv ))

Example 45

Project: PipelineConstructionSet
License: View license
Source File: namedtuple.py
Function: namedtuple
def namedtuple(typename, field_names, docAppend="", verbose=False):
    """ Returns a new subclass of tuple with named fields.

    >>> Point = namedtuple('Point', 'x, y')
    >>> Point.__doc__                   # docstring for the new class
    'Point(x, y)'
    >>> p = Point(11, y=22)             # instantiate with positional args or keywords
    >>> p[0] + p[1]                     # indexable like a plain tuple
    33
    >>> x, y = p                        # unpack like a regular tuple
    >>> x, y
    (11, 22)
    >>> p.x + p.y                       # fields also accessible by name
    33
    >>> d = p._asdict()                 # convert to a dictionary
    >>> d['x']
    11
    >>> Point(**d)                      # convert from a dictionary
    Point(x=11, y=22)
    >>> p._replace(x=100)               # _replace() is like str.replace() but targets named fields
    Point(x=100, y=22)

    """

    docAppend = docAppend.encode('string_escape')

    # Parse and validate the field names.  Validation serves two purposes,
    # generating informative error messages and preventing template injection attacks.
    if isinstance(field_names, basestring):
        field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
    field_names = tuple(field_names)
    for name in (typename,) + field_names:
        if not min(c.isalnum() or c=='_' for c in name):
            raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
        if _iskeyword(name):
            raise ValueError('Type names and field names cannot be a keyword: %r' % name)
        if name[0].isdigit():
            raise ValueError('Type names and field names cannot start with a number: %r' % name)
    seen_names = set()
    for name in field_names:
        if name.startswith('_'):
            raise ValueError('Field names cannot start with an underscore: %r' % name)
        if name in seen_names:
            raise ValueError('Encountered duplicate field name: %r' % name)
        seen_names.add(name)

    # Create and fill-in the class template
    # note in 2.6 collections use
    # def __getnewargs__(self):
    # return tuple(self)
    # instead of __reduce__ to provide unpickling capabilities

    numfields = len(field_names)
    argtxt = repr(field_names).replace("'", "")[1:-1]   # tuple repr without parens or quotes
    reprtxt = ', '.join('%s=%%r' % name for name in field_names)
    dicttxt = ', '.join('%r: t[%d]' % (name, pos) for pos, name in enumerate(field_names))
    template = '''class %(typename)s(tuple):
        '%(typename)s(%(argtxt)s)%(docAppend)s' \n
        __slots__ = () \n
        _fields = %(field_names)r \n
        def __new__(cls, %(argtxt)s):
            return tuple.__new__(cls, (%(argtxt)s)) \n
        @classmethod
        def _make(cls, iterable, new=tuple.__new__, len=len):
            'Make a new %(typename)s object from a sequence or iterable'
            result = new(cls, iterable)
            if len(result) != %(numfields)d:
                raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
            return result \n
        def __repr__(self):
            return '%(typename)s(%(reprtxt)s)' %% self \n
        def _asdict(t):
            'Return a new dict which maps field names to their values'
            return {%(dicttxt)s} \n
        def _replace(self, **kwds):
            'Return a new %(typename)s object replacing specified fields with new values'
            result = self._make(map(kwds.pop, %(field_names)r, self))
            if kwds:
                raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
            return result \n
        def __reduce__(self) :
            return ( self.__class__, tuple(self) ) \n\n''' % locals()
    for i, name in enumerate(field_names):
        template += '        %s = property(itemgetter(%d))\n' % (name, i)
    if verbose:
        print template

    # Execute the template string in a temporary namespace
    namespace = dict(itemgetter=_itemgetter)
    try:
        exec template in namespace
    except SyntaxError, e:
        raise SyntaxError(e.message + ':\n' + template)
    result = namespace[typename]

    # For pickling to work, the __module__ variable needs to be set to the frame
    # where the named tuple is created.  Bypass this step in enviroments where
    # sys._getframe is not defined (Jython for example).
    if hasattr(_sys, '_getframe'):
        result.__module__ = _sys._getframe(1).f_globals['__name__']

    return result

Example 46

Project: flowy
License: View license
Source File: utils.py
Function: caller_module
def caller_module(level=2, sys=sys):
    module_globals = sys._getframe(level).f_globals
    module_name = module_globals.get('__name__') or '__main__'
    module = sys.modules[module_name]
    return module

Example 47

Project: databus
License: View license
Source File: collections.py
Function: namedtuple
def namedtuple(typename, field_names, verbose=False):
    """Returns a new subclass of tuple with named fields.

    >>> Point = namedtuple('Point', 'x y')
    >>> Point.__doc__                   # docstring for the new class
    'Point(x, y)'
    >>> p = Point(11, y=22)             # instantiate with positional args or keywords
    >>> p[0] + p[1]                     # indexable like a plain tuple
    33
    >>> x, y = p                        # unpack like a regular tuple
    >>> x, y
    (11, 22)
    >>> p.x + p.y                       # fields also accessable by name
    33
    >>> d = p._asdict()                 # convert to a dictionary
    >>> d['x']
    11
    >>> Point(**d)                      # convert from a dictionary
    Point(x=11, y=22)
    >>> p._replace(x=100)               # _replace() is like str.replace() but targets named fields
    Point(x=100, y=22)

    """

    # Parse and validate the field names.  Validation serves two purposes,
    # generating informative error messages and preventing template injection attacks.
    if isinstance(field_names, basestring):
        field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
    field_names = tuple(map(str, field_names))
    for name in (typename,) + field_names:
        if not all(c.isalnum() or c=='_' for c in name):
            raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
        if _iskeyword(name):
            raise ValueError('Type names and field names cannot be a keyword: %r' % name)
        if name[0].isdigit():
            raise ValueError('Type names and field names cannot start with a number: %r' % name)
    seen_names = set()
    for name in field_names:
        if name.startswith('_'):
            raise ValueError('Field names cannot start with an underscore: %r' % name)
        if name in seen_names:
            raise ValueError('Encountered duplicate field name: %r' % name)
        seen_names.add(name)

    # Create and fill-in the class template
    numfields = len(field_names)
    argtxt = repr(field_names).replace("'", "")[1:-1]   # tuple repr without parens or quotes
    reprtxt = ', '.join('%s=%%r' % name for name in field_names)
    dicttxt = ', '.join('%r: t[%d]' % (name, pos) for pos, name in enumerate(field_names))
    template = '''class %(typename)s(tuple):
        '%(typename)s(%(argtxt)s)' \n
        __slots__ = () \n
        _fields = %(field_names)r \n
        def __new__(cls, %(argtxt)s):
            return tuple.__new__(cls, (%(argtxt)s)) \n
        @classmethod
        def _make(cls, iterable, new=tuple.__new__, len=len):
            'Make a new %(typename)s object from a sequence or iterable'
            result = new(cls, iterable)
            if len(result) != %(numfields)d:
                raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
            return result \n
        def __repr__(self):
            return '%(typename)s(%(reprtxt)s)' %% self \n
        def _asdict(t):
            'Return a new dict which maps field names to their values'
            return {%(dicttxt)s} \n
        def _replace(self, **kwds):
            'Return a new %(typename)s object replacing specified fields with new values'
            result = self._make(map(kwds.pop, %(field_names)r, self))
            if kwds:
                raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
            return result \n
        def __getnewargs__(self):
            return tuple(self) \n\n''' % locals()
    for i, name in enumerate(field_names):
        template += '        %s = property(itemgetter(%d))\n' % (name, i)
    if verbose:
        print template

    # Execute the template string in a temporary namespace and
    # support tracing utilities by setting a value for frame.f_globals['__name__']
    namespace = dict(itemgetter=_itemgetter, __name__='namedtuple_%s' % typename)
    try:
        exec template in namespace
    except SyntaxError, e:
        raise SyntaxError(e.message + ':\n' + template)
    result = namespace[typename]

    # For pickling to work, the __module__ variable needs to be set to the frame
    # where the named tuple is created.  Bypass this step in enviroments where
    # sys._getframe is not defined (Jython for example).
    if hasattr(_sys, '_getframe'):
        result.__module__ = _sys._getframe(1).f_globals['__name__']

    return result

Example 48

Project: Medusa
License: View license
Source File: __init__.py
Function: create
    def _create_(cls, class_name, names=None, module=None, type=None, start=1):
        """Convenience method to create a new Enum class.

        `names` can be:

        * A string containing member names, separated either with spaces or
          commas.  Values are auto-numbered from 1.
        * An iterable of member names.  Values are auto-numbered from 1.
        * An iterable of (member name, value) pairs.
        * A mapping of member name -> value.

        """
        if pyver < 3.0:
            # if class_name is unicode, attempt a conversion to ASCII
            if isinstance(class_name, unicode):
                try:
                    class_name = class_name.encode('ascii')
                except UnicodeEncodeError:
                    raise TypeError('%r is not representable in ASCII' % class_name)
        metacls = cls.__class__
        if type is None:
            bases = (cls, )
        else:
            bases = (type, cls)
        classdict = metacls.__prepare__(class_name, bases)
        _order_ = []

        # special processing needed for names?
        if isinstance(names, basestring):
            names = names.replace(',', ' ').split()
        if isinstance(names, (tuple, list)) and isinstance(names[0], basestring):
            names = [(e, i+start) for (i, e) in enumerate(names)]

        # Here, names is either an iterable of (name, value) or a mapping.
        item = None  # in case names is empty
        for item in names:
            if isinstance(item, basestring):
                member_name, member_value = item, names[item]
            else:
                member_name, member_value = item
            classdict[member_name] = member_value
            _order_.append(member_name)
        # only set _order_ in classdict if name/value was not from a mapping
        if not isinstance(item, basestring):
            classdict['_order_'] = ' '.join(_order_)
        enum_class = metacls.__new__(metacls, class_name, bases, classdict)

        # TODO: replace the frame hack if a blessed way to know the calling
        # module is ever developed
        if module is None:
            try:
                module = _sys._getframe(2).f_globals['__name__']
            except (AttributeError, ValueError):
                pass
        if module is None:
            _make_class_unpicklable(enum_class)
        else:
            enum_class.__module__ = module

        return enum_class

Example 49

Project: babble
License: View license
Source File: __init__.py
Function: namedtuple
def namedtuple(typename, field_names, verbose=False):
    """Returns a new subclass of tuple with named fields.

    >>> Point = namedtuple('Point', 'x y')
    >>> Point.__doc__                   # docstring for the new class
    'Point(x, y)'
    >>> p = Point(11, y=22)             # instantiate with positional args or keywords
    >>> p[0] + p[1]                     # indexable like a plain tuple
    33
    >>> x, y = p                        # unpack like a regular tuple
    >>> x, y
    (11, 22)
    >>> p.x + p.y                       # fields also accessable by name
    33
    >>> d = p._asdict()                 # convert to a dictionary
    >>> d['x']
    11
    >>> Point(**d)                      # convert from a dictionary
    Point(x=11, y=22)
    >>> p._replace(x=100)               # _replace() is like str.replace() but targets named fields
    Point(x=100, y=22)

    """

    # Parse and validate the field names.  Validation serves two purposes,
    # generating informative error messages and preventing template injection attacks.
    if isinstance(field_names, basestring):
        field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
    field_names = tuple(field_names)
    for name in (typename,) + field_names:
        if not min(c.isalnum() or c=='_' for c in name):
            raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
        if _iskeyword(name):
            raise ValueError('Type names and field names cannot be a keyword: %r' % name)
        if name[0].isdigit():
            raise ValueError('Type names and field names cannot start with a number: %r' % name)
    seen_names = set()
    for name in field_names:
        if name.startswith('_'):
            raise ValueError('Field names cannot start with an underscore: %r' % name)
        if name in seen_names:
            raise ValueError('Encountered duplicate field name: %r' % name)
        seen_names.add(name)

    # Create and fill-in the class template
    numfields = len(field_names)
    argtxt = repr(field_names).replace("'", "")[1:-1]   # tuple repr without parens or quotes
    reprtxt = ', '.join('%s=%%r' % name for name in field_names)
    dicttxt = ', '.join('%r: t[%d]' % (name, pos) for pos, name in enumerate(field_names))
    template = '''class %(typename)s(tuple):
        '%(typename)s(%(argtxt)s)' \n
        __slots__ = () \n
        _fields = %(field_names)r \n
        def __new__(cls, %(argtxt)s):
            return tuple.__new__(cls, (%(argtxt)s)) \n
        @classmethod
        def _make(cls, iterable, new=tuple.__new__, len=len):
            'Make a new %(typename)s object from a sequence or iterable'
            result = new(cls, iterable)
            if len(result) != %(numfields)d:
                raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
            return result \n
        def __repr__(self):
            return '%(typename)s(%(reprtxt)s)' %% self \n
        def _asdict(t):
            'Return a new dict which maps field names to their values'
            return {%(dicttxt)s} \n
        def _replace(self, **kwds):
            'Return a new %(typename)s object replacing specified fields with new values'
            result = self._make(map(kwds.pop, %(field_names)r, self))
            if kwds:
                raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
            return result \n\n''' % locals()
    for i, name in enumerate(field_names):
        template += '        %s = property(itemgetter(%d))\n' % (name, i)
    if verbose:
        print template

    # Execute the template string in a temporary namespace
    namespace = dict(itemgetter=_itemgetter)
    try:
        exec template in namespace
    except SyntaxError, e:
        raise SyntaxError(e.message + ':\n' + template)
    result = namespace[typename]

    # For pickling to work, the __module__ variable needs to be set to the frame
    # where the named tuple is created.  Bypass this step in enviroments where
    # sys._getframe is not defined (Jython for example).
    if hasattr(_sys, '_getframe'):
        result.__module__ = _sys._getframe(1).f_globals['__name__']

    return result

Example 50

Project: pystan
License: View license
Source File: enum.py
Function: create
    def _create_(cls, class_name, names=None, module=None, type=None):
        """Convenience method to create a new Enum class.

        `names` can be:

        * A string containing member names, separated either with spaces or
          commas.  Values are auto-numbered from 1.
        * An iterable of member names.  Values are auto-numbered from 1.
        * An iterable of (member name, value) pairs.
        * A mapping of member name -> value.

        """
        metacls = cls.__class__
        if type is None:
            bases = (cls, )
        else:
            bases = (type, cls)
        classdict = metacls.__prepare__(class_name, bases)
        __order__ = []

        # special processing needed for names?
        if isinstance(names, str):
            names = names.replace(',', ' ').split()
        if isinstance(names, (tuple, list)) and isinstance(names[0], str):
            names = [(e, i+1) for (i, e) in enumerate(names)]

        # Here, names is either an iterable of (name, value) or a mapping.
        for item in names:
            if isinstance(item, str):
                member_name, member_value = item, names[item]
            else:
                member_name, member_value = item
            classdict[member_name] = member_value
            __order__.append(member_name)
        # only set __order__ in classdict if name/value was not from a mapping
        if not isinstance(item, str):
            classdict['__order__'] = ' '.join(__order__)
        enum_class = metacls.__new__(metacls, class_name, bases, classdict)

        # TODO: replace the frame hack if a blessed way to know the calling
        # module is ever developed
        if module is None:
            try:
                module = _sys._getframe(2).f_globals['__name__']
            except (AttributeError, ValueError):
                pass
        if module is None:
            _make_class_unpicklable(enum_class)
        else:
            enum_class.__module__ = module

        return enum_class
See More Examples - Go to Next Page
Page 1 Selected Page 2