You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: blog_files/pysheet.md
+40Lines changed: 40 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -3868,6 +3868,46 @@ Exit
3868
3868
3869
3869
```
3870
3870
3871
+
## __main__ Top-level script environment
3872
+
3873
+
```__main__```is the name of the scopein which top-level code executes.
3874
+
A module’s__name__isset equal to```__main__``` when readfrom standardinput, a script,orfrom an interactive prompt.
3875
+
3876
+
A module can discover whetherornot itis runningin the main scope by checking its own```__name__```, which allows a common idiomfor conditionally executing codein a module when itis runas a scriptorwith```python-m``` butnot when itis imported:
3877
+
3878
+
```python
3879
+
>>>if__name__=="__main__":
3880
+
...# execute only if run as a script
3881
+
... main()
3882
+
```
3883
+
For a package, the same effect can be achieved by including a __main__.py module, the contents of which will be executed when the moduleis runwith-m
3884
+
3885
+
For example we are developing script whichis designed to be usedas module, we should do:
3886
+
3887
+
```python
3888
+
>>># Python program to execute function directly
3889
+
>>>def add(a, b):
3890
+
...return a+b
3891
+
...
3892
+
>>> add(10,20)# we can test it by calling the function save it as calculate.py
3893
+
30
3894
+
>>># Now if we want to use that module by importing we have to comment out our call,
3895
+
>>># Instead we can write like this in calculate.py
3896
+
>>>if__name__=="__main__":
3897
+
... add(3,5)
3898
+
...
3899
+
>>>import calculate
3900
+
>>> calculate.add(3,5)
3901
+
8
3902
+
```
3903
+
3904
+
### Advantages:
3905
+
1. Every Python module has it’s```__name__``` definedandif thisis```__main__```, it implies that the moduleis being run standalone by the userand we can do corresponding appropriate actions.
3906
+
2. If youimport this scriptas a modulein another script, the__name__isset to the name of the script/module.
3907
+
3. Python files can actas either reusable modules,oras standalone programs.
3908
+
4.if```__name__== “main”:```is used to execute some code onlyif thefile was run directly,andnot imported.
3909
+
3910
+
3871
3911
## Virtual Environment
3872
3912
3873
3913
The use of a Virtual Environmentis to test python codein encapsulated environmentsand to also avoid filling the base Python installationwith libraries we might usefor only one project.