Featured post
Python code to get current function into a variable? -
how can variable contains executing function in python? don't want function's name. know can use inspect.stack
current function name. want actual callable object. can done without using inspect.stack
retrieve function's name , eval
ing name callable object?
edit: have reason this, it's not remotely one. i'm using plac parse command-line arguments. use doing plac.call(main)
, generates argumentparser object function signature of "main". inside "main", if there problem arguments, want exit error message includes text argumentparser object, means need directly access object calling plac.parser_from(main).print_help()
. nice able instead: plac.parser_from(get_current_function()).print_help()
, not relying on function being named "main". right now, implementation of "get_current_function" be:
import inspect def get_current_function(): return eval(inspect.stack()[1][3])
but implementation relies on function having name, suppose not onerous. i'm never going plac.call(lambda ...)
.
in long run, might more useful ask author of plac implement print_help method print text of function most-recently called using plac, or similar.
the stack frame tells code object we're in. if can find function object refers code object in func_code
attribute, have found function.
fortunately, can ask garbage collector objects hold reference our code object, , sift through those, rather having traverse every active object in python world. there typically handful of references code object.
now, functions can share code objects, , in case return function from function, i.e. closure. when there's more 1 function using given code object, can't tell function is, return none
.
import inspect, gc def giveupthefunc(): frame = inspect.currentframe(1) code = frame.f_code globs = frame.f_globals functype = type(lambda: 0) funcs = [] func in gc.get_referrers(code): if type(func) functype: if getattr(func, "func_code", none) code: if getattr(func, "func_globals", none) globs: funcs.append(func) if len(funcs) > 1: return none return funcs[0] if funcs else none
some test cases:
def foo(): return giveupthefunc() zed = lambda: giveupthefunc() bar, foo = foo, none print bar() print zed()
i'm not sure performance characteristics of this, think should fine use case.
- Get link
- X
- Other Apps
Comments
Post a Comment