Why does an imported function “as” another name keep its original __name__?

后端 未结 3 1292
别那么骄傲
别那么骄傲 2021-02-12 19:09

Here:

from os.path import exists as foo
print foo.__name__

we get: \'exists\'. Why not \'foo\'? Which attribute would

3条回答
  •  被撕碎了的回忆
    2021-02-12 19:37

    You can view import foo as bar as just an assignment. You would not expect a function to change its __name__ attribute when you assign another name to the function.

    >>> def foo(): pass
    >>> 
    >>> foo.__name__
    'foo'
    >>> bar = foo
    >>> bar.__name__
    'foo'
    

    Thanks. What attribute of the variable bar would return the string 'bar' then?

    There is no such attribute. Names (bar) refer to values (the function object) unidirectionally.

    The __name__ attribute of a function is set as the name the function was defined with using the
    def ... syntax. That's why you don't get a meaningful __name__ attribute if you define an anonymous function and assign the name foo after it has been created.

    >>> foo = lambda: None
    >>> foo.__name__
    ''
    

提交回复
热议问题