Redefining python built-in function

后端 未结 3 1593
花落未央
花落未央 2021-01-02 20:08

I\'m working on a python program and the author has written a function that looks like this

def blah():
    str = \"asdf asdf asdf\"
    doStuff(str)
         


        
3条回答
  •  醉梦人生
    2021-01-02 20:35

    Internally, the function's local variable table will contain an entry for str, which will be local to that function. You can still access the builtin class within the function by doing builtins.str in Py3 and __builtin__.str in Py2. Any code outside the function will not see any of the function's local variables, so the builtin class will be safe to use elsewhere.

    There is another caveat/corner case here, which is described in this question. The local table entry is created at compile-time, not at runtime, so you could not use the global definition of str in the function even before you assign "asdf asdf asdf" to it:

    def blah():
        x = str(12)
        str = "asdf asdf asdf"
        doStuff(str)
    

    will fail with an UnboundLocalError.

提交回复
热议问题