Skip to content

Commit 9b6bb91

Browse files
committed
Add __name__ to modules
1 parent c04dd10 commit 9b6bb91

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

06 Modules/2 Creating custom modules.md

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
# Creating custom modules
22

3-
4-
53
When writing more complex programs, we can create our own modules. This makes it possible to split the program into several files, which is desirable in the case of longer programs. In addition, we can collect frequently used functions into a single module and use them over and over again in various projects.
64

75
The simplest module is a Python source file (with extension `.py`) placed in the same directory as the main program. Then we can import it with a command
@@ -22,6 +20,28 @@ import mymodule
2220

2321
mymodule.hello()
2422
```
23+
24+
Every Python module (including those created by you) have special variables that do not need to be declared by hand, but they are created by Python. These variables are:
25+
26+
* `__name__`: the name of the module,
27+
* `__file__`: the Python file in which the module is located (this variable is not present in some built-in modules)
28+
29+
30+
## File that can be both a module and a main program
31+
32+
Sometimes it is good to be able to create a file, which can be both a module (that may be imported from other Python file) or a main program run directly. In the former case, the module should only define functions etc. to be used from other code. In the latter case, the program should start doing its operation.
33+
34+
You can check if your file is imported as a module or run directly, by checking the `__name__` variable. For the file run directly it will always be `'__main__'`:
35+
36+
```python
37+
def do_stuff():
38+
print("I'm alive!")
39+
40+
if __name__ == '__main__':
41+
do_stuff()
42+
```
43+
44+
2545
## Packages
2646
It is also possible to create a hierarchy of modules. To do this, create a directory with the name of the module (without any extensions) and put the file in this directory with the name `__init__.py` (two underscores at the beginning and at the end of the name). Then the command
2747

@@ -37,5 +57,6 @@ or in any other way as shown before. We can also increase the number of hierarch
3757

3858
Creating packages is useful when writing more complex programs.
3959

60+
4061
<hr />
4162
<p id="copyright">Published under <a class="external" rel="nofollow" href="https://creativecommons.org/licenses/by-nc-sa/3.0/">Creative Commons Attribution-NonCommercial-ShareAlike</a> license.</p>

0 commit comments

Comments
 (0)