Introduction to Imports in Python
In Python, you can import not only standard modules, such as re (for working with regular expressions), but also create your own new modules from user files.
Let's say we have a file lib.py, which is located in the same directory as our working file test.py:
- lib.py
- test.py
Let's create a function in it that will print an exclamation mark to the console:
def func():
print('!')
Now let's go to the test.py file and import this function into it. In the top line of the file, write the command import, after which we specify the name of the desired file (module). Since both files are in the same directory, after import it is enough to specify only the name of the module without its extension:
import lib
Then we call the imported function. To do this, after the module name, we specify the function name func through a dot:
lib.func()
Result of code execution:
'!'
When you import a module, not only the functions in the working file become available, but also all of its other contents, such as variables.
After importing the module, a service folder __pycache__ automatically appeared in the working directory. Note that the names of all service files and folders in Python have double underscores:
- /__pycache__/
- lib.py
- test.py
There are cases when you need to import a module located in another folder, for example, at /dir/lib.py:
- /__pycache__/
- /dir/
- lib.py
- test.py
Then the name of the folder and file during import is written through a dot and the imported function is also written:
import dir.lib
dir.lib.func()
Create a file file.py. In it, create a function that will output a number to the console. Import this function into your file with working code.
In the file test1.file1.py create a function that prints some message. Import it into your working file.