You can import a Python module (for us, just another python file) inside a Python script.
In Pyzo, in order for this to work:
When Python is importing, it looks for the module to import in the working directory. Using Run->Run file as script makes Pyzo's working directory be the same as the location of the script being run. So if the module is in the same location, Python will find it.
After importing a module, you can access the functions and global variables in the module. We already saw this with
if __name__ == '__main__': print(math.sqrt(16)) # use thr sqrt function in the module math print(math.pi) # access the global variable pi in the module math
When a module is imported, the
__name__ variable inside that module is not equal to
__name__ would be the name of the file without the .py). That means that the code inside the
__main__ block of the imported module will not run.
There are two implications here:
Any global variables need to be initialized outside the main block. We saw this done as a call to the
initialize() function outside the main block; or we could simply set e.g.
pi = 3.14 outside the main block
We can use the main block to test the code inside the script, without having the testing code run when the script is being imported