# Importeren
# ./python/syntax/imports/my_module__1.py
def my_function():
print('Called my_function() from my_module__1.')
def main():
my_function()
main()
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
$ python3 ./python/syntax/imports/my_module__1.py
Called my_function() from my_module__1.
$ _
# ./python/syntax/imports/importing_module__1.py
import my_module__1
print('Module 1 imported.')
1
2
3
2
3
$ python3 ./python/syntax/imports/importing_module__2.py
Called my_function() from my_module__1.
Module 1 imported.
$ _
Een functie enkel aangeroepen worden als het bestand rechtstreeks uitgevoerd wordt en niet als het bestand als module geïmporteerd wordt doe je door te controleren of de naam van de module overeenkomt met __main__
.
# ./python/syntax/imports/my_module__2.py
def my_function():
print('Called my_function() from my_module__2.')
def main():
my_function()
if __name__ == '__main__':
main()
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
$ python3 ./python/syntax/imports/my_module__2.py
Called my_function() from my_module__2.
$ _
# ./python/syntax/imports/my_module__2.py
import my_module__2
print('Module 2 imported.')
1
2
3
2
3
$ python3 ./python/syntax/imports/importing_module__2.py
Module 2 imported.
$ _