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

  • A+
Category:Languages

Here:

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

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

 


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

>>> 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__ >>> '<lambda>' 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: