Every module has a name and statements in a module can find out the name of its module. This is especially handy in one particular situation - As mentioned previously, when a module is imported for the
first time, the main block in that module is run. What if we want to run the block only if the program
was used by itself and not when it was imported from another module? This can be achieved using the
__name__ attribute of the module.
Using a module's __name__
Example 8.2. Using a module's __name__
#!/usr/bin/python
# Filename: using_name.py
if __name__ == '__main__':
print 'This program is being run by itself'
else:
print 'I am being imported from another module'
Output
$ python using_name.py
This program is being run by itself
$ python
>>> import using_name
I am being imported from another module
>>>
How It Works
Every Python module has it's __name__ defined and if this is '__main__', it implies that the module
is being run standalone by the user and we can do corresponding appropriate actions.
first time, the main block in that module is run. What if we want to run the block only if the program
was used by itself and not when it was imported from another module? This can be achieved using the
__name__ attribute of the module.
Using a module's __name__
Example 8.2. Using a module's __name__
#!/usr/bin/python
# Filename: using_name.py
if __name__ == '__main__':
print 'This program is being run by itself'
else:
print 'I am being imported from another module'
Output
$ python using_name.py
This program is being run by itself
$ python
>>> import using_name
I am being imported from another module
>>>
How It Works
Every Python module has it's __name__ defined and if this is '__main__', it implies that the module
is being run standalone by the user and we can do corresponding appropriate actions.
No comments:
Post a Comment