When I started
python as a beginner, the first thing which was confusing me is If__name__ = “__main__”. It is mainly used to check whether the module
is imported or not.
Usually the
code inside ‘If’ block will be executed only, if it ran directly.
Let’s take
a closer look at this.
If python
interpreter is running the module (m1 )as a main program it sets the __name__
variable to the value __main__. So thus printing the __name__ variable will
produce output “__main__”.
Let’s consider
we import the module m1 to another module m2.
#m2.pyImport m1
Print m1.__name__
Now if we
are printing the __name__ variable which will provide module name ‘m1’ as
output.
By giving
if __name __ == “__main__” statement, you can check whether your program is being
run directly or imported by someone else.
No comments:
Post a Comment