如何为 Python 的函数参数设置调用者上下文的表达式默认值? - V2EX
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
AndyAO

如何为 Python 的函数参数设置调用者上下文的表达式默认值?

  •  2
     
  •   AndyAO Mar 23, 2021 1345 views
    This topic created in 1861 days ago, the information mentioned may be changed or developed.

    想在 Python 3 上封装个将文件作为代码动态执行的函数,exec的参数globals,locals 的默认值分别是当前上下文globals()locals(),自己封装的函数如何实现这种效果?

    1. 已经尝试过 def file(filepath,globals=globals(),locals=locals()) 没有效果。
    2. 查看exec的实现,发现被定义在def exec(__object: Union[str, bytes, CodeType], __globals: Optional[Dict[str, Any]] = ..., __locals: Optional[Mapping[str, Any]] = ...) -> Any: ...,直接使用这个参数列表会导致语法错误。

    目前的函数是这样定义的

    def file(filepath,globals,locals): with open(filepath, 'r', encoding='utf8') as textFileObj: return exec(compile(textFileObj.read(), filepath, 'exec'),globals,locals) 

    调用的时候只能这样手动传入,虽然可以通过片段等方法简化这个过程,实现类似的效果,但总归是默认值更方便。

    Exe.file(Path.here(__file__,'HelloWorld.py'),globals(),locals()) 
    Supplement 1    Mar 23, 2021
    我的问题已经得到了解决,目前看来,Python 没有这样的机制,另外如果要使用表达式来定义默认参数,那么很可能会出现令人意想不到的现象,从这里可以察觉出 Python 函数的某种本质,下面这个高票答案很好的讲述了这个问题,很值得去看。

    [“Least Astonishment” and the Mutable Default Argument]( https://stackoverflow.com/a/1145781)
    2 replies    2021-03-23 14:26:33 +08:00
    ebingtel
        1
    ebingtel  
       Mar 23, 2021
    这样?

    a.py:

    import inspect


    def f():
    print(inspect.currentframe().f_back.f_globals)


    调用:

    >>> b = 1
    >>> m = __import__('a')
    >>> m.f()
    {'b': 1, '__builtins__': <module '__builtin__' (built-in)>, 'm': <module 'a' from 'a.py'>, '__package__': None, '__name__': '__main__', '__doc__': None}
    wangaroo
        2
    wangaroo  
       Mar 23, 2021
    global 关键字?
    About     Help     Advertise     Blog     API     FAQ     Solana     4175 Online   Highest 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 43ms UTC 05:26 PVG 13:26 LAX 22:26 JFK 01:26
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86