def open(path):
f = builtins.open(path, 'r')
return UpperCaser(f)
class UpperCaser:
'''Wrapper around a file that converts output to upper-case.'''
def __init__(self, f):
self._f = f
def read(self, count=-1):
return self._f.read(count).upper()
# ...
As an implementation detail, most modules have the name__builtins__ made available as part of their globals. The value of__builtins__ is normally either this module or the value of this module’s__dict__ attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.
__main__ — Top-level script environment
'__main__'
is the name of the scope in which top-level code executes. A module’s __name__ is set equal to'__main__'
when read from standard input, a script, or from an interactive prompt.
A module can discover whether or not it is running in the main scope by checking its own__name__
, which allows a common idiom for conditionally executing code in a module when it is run as a script or withpython -m
but not when it is imported:
if __name__ == "__main__":
# execute only if run as a script
main()
For a package, the same effect can be achieved by including a __main__.py
module, the contents of which will be executed when the module is run with-m
.