Modules
A module is any file that contain Python code.
"""Define a module:
When you import a module, it defines new functions, but doesn't run them.
If the program is running as a script, the test code runs.
If module is imported the test code is skipped.
"""
DIR = "/var/www/"
def myprint(str):
print('Print from my module: %s' % str)
print(DIR)
def mysum(a, b):
return a + b
assert mysum(1,2) == 3
assert mysum(-1,2) == 1
"""Test code"""
if __name__ == '__main__':
print('Load my module ' + __name__)
print(DIR)
# /var/www/
Import
You can import the new module in your programs.
"""Import module:
Any file that contains Python code can be imported as module.
Test code (defined in mymodule) is not displayed.
.pyc files are created automatically by the GraalVM Python runtime ...
when you import custom mdules.
"""
import sys
sys.dont_write_bytecode = True # no .pyc
import mymodule
mymodule.DIR = "/usr/local"
mymodule.myprint('Hello World')
# Print from my module: Hello World: __main__
# /usr/local
from mymodule import mysum
from mymodule import myprint
myprint(mysum(1,2))
# Print from my module: 3
# /usr/local
Last update: 420 days ago