function class or module.__name__

suggest change

The special attribute __name__ of a function, class or module is a string containing its name.

import os

class C:
    pass

def f(x):
    x += 2
    return x

print(f)
# <function f at 0x029976B0>
print(f.__name__)
# f

print(C)
# <class '__main__.C'>
print(C.__name__)
# C

print(os)
# <module 'os' from '/spam/eggs/'>
print(os.__name__)
# os

The __name__ attribute is not, however, the name of the variable which references the class, method or function, rather it is the name given to it when defined.

def f():
    pass

print(f.__name__)
# f - as expected

g = f
print(g.__name__)
# f - even though the variable is named g, the function is still named f

This can be used, among others, for debugging:

def enter_exit_info(func):
    def wrapper(*arg, **kw):
        print '-- entering', func.__name__
        res = func(*arg, **kw)
        print '-- exiting', func.__name__
        return res
    return wrapper

@enter_exit_info
def f(x):
    print 'In:', x
    res = x + 2
    print 'Out:', res
    return res

a = f(2)

# Outputs:
#     -- entering f
#     In: 2
#     Out: 4
#     -- exiting f

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents