pathlib--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[2], line 1 ----> 1 pathlib NameError: name 'pathlib' is not defined
Every Python installation includes a number of modules by default. They are called collectively the “Python Standard Library” or “built-in” modules.
Even though these modules are available in our computer, we cannot directly use them, we need to import them into our current namespace to actually use them.
For example, if we try to use the module pathlib, we get this NameError
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[2], line 1 ----> 1 pathlib NameError: name 'pathlib' is not defined
That means that the word pathlib is unknown in this context (namespace).
Let’s bring it in:
Now we can use it:
We can also import only specific parts of the module (submodules):
It is also possible to alias these imported names using the keyword as:
We can also import our own code. For example, if we have a python file called mymodule.py we can use it in another file:
Sometimes we have a Python module (any .py file) that contain code that we only want to run as a script alongside code that we only want to use somewhere else (importing parts of it).
We can isolate part of the code that we want to run as a script with a special syntax, let’s do some exercises to show it.
Create 2 files like these in our working project /pycourse/src/pycourse/data.py, /pycourse/src/pycourse/preprocessing.py:
RAWDATA from the previous lab exercises into a file data.pypreprocessing.py in the same directory.RAWDATA string inside preprocessing.pydata.py as a script with uv run src/pycourse/data.py. Pay attention to the printed outputuv run src/pycourse/preprocessing.py. Pay attention to the printed output. What difference do you see compared to the previous point?Congratulations! You just ran your first python scripts 🚀