The name special variable

The name special variable is used to check whether a file has been imported as a module or not, and to identify a function, class, module object by their name attribute.

name == ‘main

The special variable name is not set by the user. It is mostly used to check whether or not the module is being run by itself or run because an import was performed. To avoid your module to run certain parts of its code when it gets imported, check if name == ‘main‘.

Let module_1.py be just one line long:

import module2.py

And let’s see what happens, depending on module2.py

Situation 1

module2.py
print('hello')

Running module1.py will print hello

Running module2.py will print hello

Situation 2

module2.py

if name == 'main':
print('hello')

Running module1.py will print nothing

Running module2.py will print hello

Use in logging

When configuring the built-in logging functionality, a common pattern is to create a logger with the name of the current module:

logger = logging.getLogger(name)

This means that the fully-qualified name of the module will appear in the logs, making it easier to see where messages have come from.

function_class_or_module.name

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

import os

GoalKicker.com – Python® Notes for Professionals 387

class C:
pass
def f(x):
x += 2
return x
print(f)
print(f.name)
f
print(C)
print(C.name)
C
print(os)
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

LEAVE A REPLY

Please enter your comment!
Please enter your name here