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.

90 Examples 7

Example 1

Project: Rhetoric
Source File: path.py
View license
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 2

Project: rst2pdf
Source File: tenjin.py
View license
    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 3

Project: python-gflags
Source File: __init__.py
View license
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 4

Project: jogging
Source File: __init__.py
View license
    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 5

Project: NimLime
Source File: configuration.py
View license
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 6

Project: cgstudiomap
Source File: utils.py
View license
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 7

Project: PyIB
Source File: tenjin.py
View license
    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: rst2pdf
Source File: tenjin.py
View license
    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 9

View license
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 10

View license
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 11

View license
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 12

Project: django-dbsettings
Source File: group.py
View license
    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 13

Project: numexpr
Source File: necompiler.py
View license
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 14

View license
    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 15

Project: multiversion
Source File: multiversion.py
View license
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 16

Project: PFramer
Source File: pluginbase.py
View license
    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 17

Project: mdcs-py
Source File: Base.py
View license
    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 18

Project: PyIB
Source File: tenjin.py
View license
    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 19

Project: multiversion
Source File: multiversion.py
View license
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 20

Project: robothon
Source File: dual.py
View license
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 21

Project: morepath
Source File: autosetup.py
View license
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 22

View license
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 23

Project: morepath
Source File: autosetup.py
View license
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 24

Project: pluginbase
Source File: pluginbase.py
View license
    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 25

Project: robothon
Source File: dual.py
View license
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 26

Project: neomodel
Source File: relationship_manager.py
View license
    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 27

Project: SickRage
Source File: enum.py
View license
    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 28

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

Example 29

Project: babble
Source File: __init__.py
View license
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 30

Project: SickRage
Source File: __init__.py
View license
    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 31

Project: certitude
Source File: enum.py
View license
    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

Example 32

Project: nzbToMedia
Source File: __init__.py
View license
    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 33

Project: pystan
Source File: enum.py
View license
    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

Example 34

Project: pydgin
Source File: sim.py
View license
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 35

View license
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 36

Project: zipline
Source File: sentinel.py
View license
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 37

Project: rst2pdf
Source File: tenjin.py
View license
    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 38

Project: pystan
Source File: __init__.py
View license
    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

Example 39

View license
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 40

Project: PyIB
Source File: tenjin.py
View license
    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 41

Project: databus
Source File: collections.py
View license
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 42

Project: mdcs-py
Source File: Base.py
View license
    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 43

View license
    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 44

Project: headphones
Source File: enum.py
View license
    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 45

Project: PyIB
Source File: tenjin.py
View license
    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 46

Project: graphene
Source File: enum.py
View license
    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 47

Project: pick
Source File: enum.py
View license
    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 48

Project: fatoptimizer
Source File: benchmark.py
View license
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 49

Project: rst2pdf
Source File: tenjin.py
View license
    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 50

Project: pick
Source File: __init__.py
View license
    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