Here are the examples of the python api sys._getframe.f_locals taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
37 Examples
3
Example 1
def setter(self, fset):
cls_ns = sys._getframe(1).f_locals
for key, value in cls_ns.iteritems():
if value == self:
propname = key
break
cls_ns[propname] = property(self.fget, fset,
self.fdel, self.__doc__)
return cls_ns[propname]
3
Example 2
def dump(obj=missing):
"""Print the object details to stdout._write (for the interactive
console of the web debugger.
"""
gen = DebugReprGenerator()
if obj is missing:
rv = gen.dump_locals(sys._getframe(1).f_locals)
else:
rv = gen.dump_object(obj)
sys.stdout._write(rv)
3
Example 3
Project: PyFITS Source File: util.py
def __ter(self, f, arg):
args = [self._fget, self._fset, self._fdel, self.__doc__]
args[arg] = f
cls_ns = sys._getframe(1).f_locals
for k, v in iteritems(cls_ns):
if v is self:
property_name = k
break
cls_ns[property_name] = lazyproperty(*args)
return cls_ns[property_name]
3
Example 4
def setter(self, fset):
ns = sys._getframe(1).f_locals
for k, v in ns.iteritems():
if v == self:
propname = k
break
ns[propname] = property(self.fget, fset, self.fdel, self.__doc__)
return ns[propname]
3
Example 5
def find_locals(func,depth=0):
'''apply func to the locals at each stack frame till func returns a non false value'''
while 1:
_ = func(sys._getframe(depth).f_locals)
if _: return _
depth += 1
3
Example 6
Project: extdbg Source File: watcher.py
def add_watcher_attribute(name, watch_get=False):
def attr_watch_get(self):
value = getattr(self, '_add_watcher_' + name, 'unset')
if watch_get:
pprint(from_where_called(), name, 'is', value)
return value
def attr_watch_set(self, value):
pprint(from_where_called(), name, 'set to', value)
setattr(self, '_add_watcher_' + name, value)
sys._getframe(1).f_locals[name] = property(attr_watch_get, attr_watch_set)
3
Example 7
Project: PythonUtils Source File: misc.py
def explicitly(name, stackadd=0):
"""
This is an alias for adding to '__all__'. Less error-prone than using
__all__ itself, since setting __all__ directly is prone to stomping on
things implicitly exported via L{alias}.
@note Taken from PyExport (which could turn out pretty cool):
@li @a http://codebrowse.launchpad.net/~glyph/
@li @a http://glyf.livejournal.com/74356.html
"""
packageVars = sys._getframe(1+stackadd).f_locals
globalAll = packageVars.setdefault('__all__', [])
globalAll.append(name)
3
Example 8
Project: music-player Source File: __init__.py
def NSDictionaryOfVariableBindings(*names):
"""
Return a dictionary with the given names and there values.
"""
import sys
variables = sys._getframe(1).f_locals
return {
nm: variables[nm]
for nm in names
}
3
Example 9
Project: protocyt Source File: meta.py
def __new__(mcs, name, bases, internals):
doc = internals.get('__doc__')
if doc is not None:
scope = sys._getframe(1).f_locals
module_name = internals.get('__module__')
protocol_name = '_'.join(
(module_name.replace('_', '').replace('.', '_'), name)
)
module = sys.modules[module_name]
output_dir = Path.from_file(module.__file__).up()
from_source(inspect.cleandoc(doc), protocol_name, output_dir, True)
protocol = __import__(protocol_name, scope, scope, [], -1)
base = getattr(protocol, name)
return type.__new__(mcs, name, bases + (base,), internals)
else:
return type.__new__(mcs, name, bases, internals)
3
Example 10
Project: flypy Source File: entrypoints.py
def scoping_decorator(decorator):
@wraps(decorator)
def decorator_wrapper(*args, **kwargs):
scope = kwargs.pop('scope', sys._getframe(1).f_locals)
if applyable(args, kwargs):
return decorator(*args, scope=scope)
return lambda f: decorator(f, *args, scope=scope, **kwargs)
return decorator_wrapper
3
Example 11
def invariant(call):
f_locals = sys._getframe(1).f_locals
tags = f_locals.setdefault(TAGGED_DATA, {})
invariants = tags.setdefault('invariants', [])
invariants.append(call)
return _decorator_non_return
3
Example 12
@staticmethod
def define(rmatch):
def wrapper(fn):
f_locals = sys._getframe(1).f_locals
mapping = f_locals.setdefault('_mapping', [])
mapping.append((re.compile(rmatch), fn.__name__))
return fn
return wrapper
3
Example 13
def setter(self, fset):
cls_ns = sys._getframe(1).f_locals
for k, v in cls_ns.iteritems():
if v == self:
propname = k
break
cls_ns[propname] = property(self.fget, fset, self.fdel, self.__doc__)
return cls_ns[propname]
3
Example 14
def deleter(self, fdel):
cls_ns = sys._getframe(1).f_locals
for k, v in cls_ns.iteritems():
if v == self:
propname = k
break
cls_ns[propname] = property(self.fget, self.fset, fdel, self.__doc__)
return cls_ns[propname]
3
Example 15
Project: TwistedBot Source File: interface.py
def taggedValue(key, value):
"""Attaches a tagged value to an interface at definition time."""
f_locals = sys._getframe(1).f_locals
tagged_values = f_locals.setdefault(TAGGED_DATA, {})
tagged_values[key] = value
return _decorator_non_return
3
Example 16
def setter(self, value):
cls_ns = sys._getframe(1).f_locals
for k, v in cls_ns.iteritems():
if v == self:
name = k
break
cls_ns[name] = property(self.fget, value, self.fdel, self.__doc__)
return cls_ns[name]
0
Example 17
Project: pytest Source File: pytester.py
def assert_contains(self, entries):
__tracebackhide__ = True
i = 0
entries = list(entries)
backlocals = sys._getframe(1).f_locals
while entries:
name, check = entries.pop(0)
for ind, call in enumerate(self.calls[i:]):
if call._name == name:
print_("NAMEMATCH", name, call)
if eval(check, backlocals, call.__dict__):
print_("CHECKERMATCH", repr(check), "->", call)
else:
print_("NOCHECKERMATCH", repr(check), "-", call)
continue
i += ind + 1
break
print_("NONAMEMATCH", name, "with", call)
else:
pytest.fail("could not find %r check %r" % (name, check))
0
Example 18
Project: ra Source File: utils.py
def caller_scope(back=1):
import sys
return sys._getframe(back + 1).f_locals
0
Example 19
def expose(func=None, alias=None):
"""Expose the function, optionally providing an alias or set of aliases."""
def expose_(func):
func.exposed = True
if alias is not None:
if isinstance(alias, basestring):
parents[alias.replace(".", "_")] = func
else:
for a in alias:
parents[a.replace(".", "_")] = func
return func
import sys
import types
if isinstance(func, (types.FunctionType, types.MethodType)):
if alias is None:
# @expose
func.exposed = True
return func
else:
# func = expose(func, alias)
parents = sys._getframe(1).f_locals
return expose_(func)
elif func is None:
if alias is None:
# @expose()
parents = sys._getframe(1).f_locals
return expose_
else:
# @expose(alias="alias") or
# @expose(alias=["alias1", "alias2"])
parents = sys._getframe(1).f_locals
return expose_
else:
# @expose("alias") or
# @expose(["alias1", "alias2"])
parents = sys._getframe(1).f_locals
alias = func
return expose_
0
Example 20
def expose(func=None, alias=None):
"""Expose the function, optionally providing an alias or set of aliases."""
def expose_(func):
func.exposed = True
if alias is not None:
if isinstance(alias, basestring):
parents[alias.replace(".", "_")] = func
else:
for a in alias:
parents[a.replace(".", "_")] = func
return func
import sys, types
if isinstance(func, (types.FunctionType, types.MethodType)):
if alias is None:
# @expose
func.exposed = True
return func
else:
# func = expose(func, alias)
parents = sys._getframe(1).f_locals
return expose_(func)
elif func is None:
if alias is None:
# @expose()
parents = sys._getframe(1).f_locals
return expose_
else:
# @expose(alias="alias") or
# @expose(alias=["alias1", "alias2"])
parents = sys._getframe(1).f_locals
return expose_
else:
# @expose("alias") or
# @expose(["alias1", "alias2"])
parents = sys._getframe(1).f_locals
alias = func
return expose_
0
Example 21
def run(namespace=None, action_prefix='action_', args=None):
"""Run the script. Participating actions are looked up in the caller's
namespace if no namespace is given, otherwise in the dict provided.
Only items that start with action_prefix are processed as actions. If
you want to use all items in the namespace provided as actions set
action_prefix to an empty string.
:param namespace: An optional dict where the functions are looked up in.
By default the local namespace of the caller is used.
:param action_prefix: The prefix for the functions. Everything else
is ignored.
:param args: the arguments for the function. If not specified
:data:`sys.argv` without the first argument is used.
"""
if namespace is None:
namespace = sys._getframe(1).f_locals
actions = find_actions(namespace, action_prefix)
if args is None:
args = sys.argv[1:]
if not args or args[0] in ('-h', '--help'):
return print_usage(actions)
elif args[0] not in actions:
fail('Unknown action \'%s\'' % args[0])
arguments = {}
types = {}
key_to_arg = {}
long_options = []
formatstring = ''
func, doc, arg_def = actions[args.pop(0)]
for idx, (arg, shortcut, default, option_type) in enumerate(arg_def):
real_arg = arg.replace('-', '_')
if shortcut:
formatstring += shortcut
if not isinstance(default, bool):
formatstring += ':'
key_to_arg['-' + shortcut] = real_arg
long_options.append(isinstance(default, bool) and arg or arg + '=')
key_to_arg['--' + arg] = real_arg
key_to_arg[idx] = real_arg
types[real_arg] = option_type
arguments[real_arg] = default
try:
optlist, posargs = getopt.gnu_getopt(args, formatstring, long_options)
except getopt.GetoptError, e:
fail(str(e))
specified_arguments = set()
for key, value in enumerate(posargs):
try:
arg = key_to_arg[key]
except IndexError:
fail('Too many parameters')
specified_arguments.add(arg)
try:
arguments[arg] = converters[types[arg]](value)
except ValueError:
fail('Invalid value for argument %s (%s): %s' % (key, arg, value))
for key, value in optlist:
arg = key_to_arg[key]
if arg in specified_arguments:
fail('Argument \'%s\' is specified twice' % arg)
if types[arg] == 'boolean':
if arg.startswith('no_'):
value = 'no'
else:
value = 'yes'
try:
arguments[arg] = converters[types[arg]](value)
except ValueError:
fail('Invalid value for \'%s\': %s' % (key, value))
newargs = {}
for k, v in arguments.iteritems():
newargs[k.startswith('no_') and k[3:] or k] = v
arguments = newargs
return func(**arguments)
0
Example 22
def compile_func(func, tree):
def wrap_func(func_tree, arg_names):
return FunctionDef(
name = func_tree.name + '__wrapped',
args = make_arguments(lmap(A, arg_names)),
decorator_list = [],
body = [
func_tree,
Return(value=N(func_tree.name))
]
)
context = sys._getframe(2).f_locals
if getattr(func, '__closure__', None) or getattr(func, 'func_closure', None):
kwargs = context.copy()
tree.body[0] = wrap_func(tree.body[0], kwargs.keys())
_compile_func(func, tree, context)
func.__code__ = context[func.__name__ + '__wrapped'](**kwargs).__code__
return func
else:
_compile_func(func, tree, context)
return context[func.__name__]
0
Example 23
def expose(func=None, alias=None):
"""Expose the function, optionally providing an alias or set of aliases."""
def expose_(func):
func.exposed = True
if alias is not None:
if isinstance(alias, basestring):
parents[alias.replace(".", "_")] = func
else:
for a in alias:
parents[a.replace(".", "_")] = func
return func
import sys, types
if isinstance(func, (types.FunctionType, types.MethodType)):
if alias is None:
# @expose
func.exposed = True
return func
else:
# func = expose(func, alias)
parents = sys._getframe(1).f_locals
return expose_(func)
elif func is None:
if alias is None:
# @expose()
parents = sys._getframe(1).f_locals
return expose_
else:
# @expose(alias="alias") or
# @expose(alias=["alias1", "alias2"])
parents = sys._getframe(1).f_locals
return expose_
else:
# @expose("alias") or
# @expose(["alias1", "alias2"])
parents = sys._getframe(1).f_locals
alias = func
return expose_
0
Example 24
def run(namespace=None, action_prefix='action_', args=None):
"""Run the script. Participating actions are looked up in the caller's
namespace if no namespace is given, otherwise in the dict provided.
Only items that start with action_prefix are processed as actions. If
you want to use all items in the namespace provided as actions set
action_prefix to an empty string.
:param namespace: An optional dict where the functions are looked up in.
By default the local namespace of the caller is used.
:param action_prefix: The prefix for the functions. Everything else
is ignored.
:param args: the arguments for the function. If not specified
:data:`sys.argv` without the first argument is used.
"""
if namespace is None:
namespace = sys._getframe(1).f_locals
actions = find_actions(namespace, action_prefix)
if args is None:
args = sys.argv[1:]
if not args or args[0] in ('-h', '--help'):
return print_usage(actions)
elif args[0] not in actions:
fail('Unknown action \'%s\'' % args[0])
arguments = {}
types = {}
key_to_arg = {}
long_options = []
formatstring = ''
func, doc, arg_def = actions[args.pop(0)]
for idx, (arg, shortcut, default, option_type) in enumerate(arg_def):
real_arg = arg.replace('-', '_')
if shortcut:
formatstring += shortcut
if not isinstance(default, bool):
formatstring += ':'
key_to_arg['-' + shortcut] = real_arg
long_options.append(isinstance(default, bool) and arg or arg + '=')
key_to_arg['--' + arg] = real_arg
key_to_arg[idx] = real_arg
types[real_arg] = option_type
arguments[real_arg] = default
try:
optlist, posargs = getopt.gnu_getopt(args, formatstring, long_options)
except getopt.GetoptError as e:
fail(str(e))
specified_arguments = set()
for key, value in enumerate(posargs):
try:
arg = key_to_arg[key]
except IndexError:
fail('Too many parameters')
specified_arguments.add(arg)
try:
arguments[arg] = converters[types[arg]](value)
except ValueError:
fail('Invalid value for argument %s (%s): %s' % (key, arg, value))
for key, value in optlist:
arg = key_to_arg[key]
if arg in specified_arguments:
fail('Argument \'%s\' is specified twice' % arg)
if types[arg] == 'boolean':
if arg.startswith('no_'):
value = 'no'
else:
value = 'yes'
try:
arguments[arg] = converters[types[arg]](value)
except ValueError:
fail('Invalid value for \'%s\': %s' % (key, value))
newargs = {}
for k, v in iteritems(arguments):
newargs[k.startswith('no_') and k[3:] or k] = v
arguments = newargs
return func(**arguments)
0
Example 25
def expose(func=None, alias=None):
"""
Expose the function or class, optionally providing an alias or set of aliases.
"""
def expose_(func):
func.exposed = True
if alias is not None:
if isinstance(alias, basestring):
parents[alias.replace(".", "_")] = func
else:
for a in alias:
parents[a.replace(".", "_")] = func
return func
import sys
import types
decoratable_types = types.FunctionType, types.MethodType, type,
if not IS_PY3:
# Old-style classes are type types.ClassType.
decoratable_types += types.ClassType,
if isinstance(func, decoratable_types):
if alias is None:
# @expose
func.exposed = True
return func
else:
# func = expose(func, alias)
parents = sys._getframe(1).f_locals
return expose_(func)
elif func is None:
if alias is None:
# @expose()
parents = sys._getframe(1).f_locals
return expose_
else:
# @expose(alias="alias") or
# @expose(alias=["alias1", "alias2"])
parents = sys._getframe(1).f_locals
return expose_
else:
# @expose("alias") or
# @expose(["alias1", "alias2"])
parents = sys._getframe(1).f_locals
alias = func
return expose_
0
Example 26
def run_test(rep, msg, func=None, previous={}, results={}):
## items = [None] * rep
if func is None:
locals = sys._getframe(1).f_locals
func = eval("lambda: %s" % msg, locals)
items = xrange(rep)
from time import clock
start = clock()
for i in items:
func(); func(); func(); func(); func()
stop = clock()
duration = (stop-start)*1e6/5/rep
try:
prev = previous[msg]
except KeyError:
print >> sys.stderr, "%40s: %7.1f us" % (msg, duration)
delta = 0.0
else:
delta = duration / prev * 100.0
print >> sys.stderr, "%40s: %7.1f us, time = %5.1f%%" % (msg, duration, delta)
results[msg] = duration
return delta
0
Example 27
def synthesize(name, copy=False, readwrite=True, type=_C_ID, ivarName=None):
"""
Use this in a class dictionary to syntheze simple setting/setter methods.
Note: this is only necessary to get propper behaviour when Key-Value coding
is used and special features (like copying) are needed
usage::
class MyClass (NSObject):
objc.synthesize('someTitle', copy=True)
"""
if not name:
raise ValueError("Empty property name")
if ivarName is None:
ivarName = '_' + name
classDict = sys._getframe(1).f_locals
setterName = 'set%s%s_'%(name[0].upper(), name[1:])
if copy:
setter = textwrap.dedent('''
def %(name)s(self, value):
self.%(ivar)s = value.copy()
''' % dict(name=setterName, ivar=ivarName))
else:
setter = textwrap.dedent('''
def %(name)s(self, value):
self.%(ivar)s = value
''' % dict(name=setterName, ivar=ivarName))
getter = textwrap.dedent('''
def %(name)s(self):
return self.%(ivar)s
''' % dict(name=name, ivar=ivarName))
if readwrite:
exec(setter, globals(), classDict)
exec(getter, globals(), classDict)
classDict[ivarName] = ivar(type=type)
0
Example 28
def jit(f=None, *args, **kwds):
"""
@jit entry point:
@jit
def myfunc(a, b): return a + b
@jit('a -> b')
def myfunc(a, b): return a + b
@jit
class Foo(object): pass
@jit('Foo[a]')
class Foo(object): pass
"""
kwds['scope'] = kwds.pop('scope', sys._getframe(1).f_locals)
if isinstance(f, (type, types.FunctionType, types.ClassType)):
return _jit(f, *args, **kwds)
arg = f
return lambda f: _jit(f, arg, *args, **kwds)
0
Example 29
def __call__(self, *args, **kwargs):
class_locals = sys._getframe(1).f_locals
modifiers = class_locals.setdefault(MODIFIERS, [])
modifiers.append((self, args, kwargs))
0
Example 30
def __init__(self,name):
self.name = name
sys._getframe(1).f_locals[name] = self
0
Example 31
def __init__( self, *args, **kwargs ):
# jam this mutator into the class's mutator list
class_locals = sys._getframe(1).f_locals
mutators = class_locals.setdefault( MUTATORS, [] )
mutators.append( (self, args, kwargs) )
0
Example 32
def f():
print("Func locals", sys._getframe().f_locals)
print("Func flags", sys._getframe().f_code.co_flags)
0
Example 33
def g():
yield("Generator object locals", sys._getframe().f_locals)
yield("Generator object flags", sys._getframe().f_code.co_flags)
0
Example 34
def implements(*interfaces):
cls_scope = sys._getframe(1).f_locals
metacls = cls_scope.get('__metaclass__')
metafactory = make_meta_factory(metacls, interfaces)
cls_scope['__metaclass__'] = metafactory
0
Example 35
def __enter__(self):
locals_ = sys._getframe(1).f_locals
self.__dict__["locals"] = locals_.copy()
return self
0
Example 36
def __exit__(self, *args):
# find what's changed
updates = {}
d = self.__dict__
locals_ = sys._getframe(1).f_locals
self_locals = d["locals"]
for k, v in locals_.iteritems():
if not (k.startswith("__") and k.endswith("__")) \
and (k not in self_locals or v != self_locals[k]) \
and not isinstance(v, _Scope):
updates[k] = v
# merge updated local vars with attributes
self.update(updates)
# restore upper scope
locals_.clear()
locals_.update(self_locals)
self_context = d["context"]
if self_context:
self_context._scope_exit(d["name"])
0
Example 37
def run(namespace=None, action_prefix='action_', args=None):
"""Run the script. Participating actions are looked up in the caller's
namespace if no namespace is given, otherwise in the dict provided.
Only items that start with action_prefix are processed as actions. If
you want to use all items in the namespace provided as actions set
action_prefix to an empty string.
:param namespace: An optional dict where the functions are looked up in.
By default the local namespace of the caller is used.
:param action_prefix: The prefix for the functions. Everything else
is ignored.
:param args: the arguments for the function. If not specified
:data:`sys.argv` without the first argument is used.
"""
_deprecated()
if namespace is None:
namespace = sys._getframe(1).f_locals
actions = find_actions(namespace, action_prefix)
if args is None:
args = sys.argv[1:]
if not args or args[0] in ('-h', '--help'):
return print_usage(actions)
elif args[0] not in actions:
fail('Unknown action \'%s\'' % args[0])
arguments = {}
types = {}
key_to_arg = {}
long_options = []
formatstring = ''
func, doc, arg_def = actions[args.pop(0)]
for idx, (arg, shortcut, default, option_type) in enumerate(arg_def):
real_arg = arg.replace('-', '_')
if shortcut:
formatstring += shortcut
if not isinstance(default, bool):
formatstring += ':'
key_to_arg['-' + shortcut] = real_arg
long_options.append(isinstance(default, bool) and arg or arg + '=')
key_to_arg['--' + arg] = real_arg
key_to_arg[idx] = real_arg
types[real_arg] = option_type
arguments[real_arg] = default
try:
optlist, posargs = getopt.gnu_getopt(args, formatstring, long_options)
except getopt.GetoptError as e:
fail(str(e))
specified_arguments = set()
for key, value in enumerate(posargs):
try:
arg = key_to_arg[key]
except IndexError:
fail('Too many parameters')
specified_arguments.add(arg)
try:
arguments[arg] = converters[types[arg]](value)
except ValueError:
fail('Invalid value for argument %s (%s): %s' % (key, arg, value))
for key, value in optlist:
arg = key_to_arg[key]
if arg in specified_arguments:
fail('Argument \'%s\' is specified twice' % arg)
if types[arg] == 'boolean':
if arg.startswith('no_'):
value = 'no'
else:
value = 'yes'
try:
arguments[arg] = converters[types[arg]](value)
except ValueError:
fail('Invalid value for \'%s\': %s' % (key, value))
newargs = {}
for k, v in iteritems(arguments):
newargs[k.startswith('no_') and k[3:] or k] = v
arguments = newargs
return func(**arguments)