How can a function access its own attributes?

前端 未结 16 1831
再見小時候
再見小時候 2020-11-28 07:49

is it possible to access the python function object attributes from within the function scope?

e.g. let\'s have

def f():
    return          


        
16条回答
  •  悲&欢浪女
    2020-11-28 07:55

    Here's a decorator that injects current_fun into the functions globals before executing the function. It's quite the hack, but also quite effective.

    from functools import wraps
    
    
    def introspective(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            exists = 'current_fun' in f.func_globals
            old = f.func_globals.get('current_fun',None)
            f.func_globals['current_fun'] = wrapper
            try:
                return f(*args, **kwargs)
            finally:
                if exists:
                    f.func_globals['current_fun'] = old
                else:
                    del f.func_globals['current_fun']
        return wrapper
    
    @introspective
    def f():
        print 'func_dict is ',current_fun.func_dict
        print '__dict__ is ',current_fun.__dict__
        print 'x is ',current_fun.x
    

    Here's a usage example

    In [41]: f.x = 'x'
    
    In [42]: f()
    func_dict is  {'x': 'x'}
    __dict__ is  {'x': 'x'}
    x is  x
    
    In [43]: g = f
    
    In [44]: del f
    
    In [45]: g()
    func_dict is  {'x': 'x'}
    __dict__ is  {'x': 'x'}
    x is  x
    

提交回复
热议问题