Modules and Packages

  • Importing Parts of Packages

    It’s easy to import only parts of a package in Python. You can import a particular module (file) from a package, or particular classes, functions or constants (variables) from a module. The syntax looks the same or similar in all of these cases. Consider this module: mystuff/mymodule.py If we want to import only the greet…

    Read more

  • Package Initialisation

    A package in Python is just a directory, which can contain modules (Python files with a .py extension). If you place a file called __init__.py in the directory, it will run when you import the package. mystuff/__init__.py myprog.py output: Importing Packages Directly Instead of importing particular module files from packages, if you place an __init__.py…

    Read more

  • Packages

    Individual Python module files can be placed in directories, or even entire hierarchies of directories. This means you can put multiple module files in a directory, forming a package. While directories are separated by a / character (or \ on Windows) when referring to them in a terminal, when you import modules in Python, the…

    Read more

  • Python ‘Main’ Function

    When you load a Python module, by default all the code in that module will be interpreted by the Python interpreter. This means that if your module has a ‘main’ function — some function that you use as an entry point to your program — by default it will run, and this is often not…

    Read more

  • Simple Python Module Example

    Here is a very simple example of a Python module. First, we create a file called mymodule.py containing a simple function called greet. mymodule.py: Now we can use this file in another Python program by ‘importing’ it. Then we can access the greet function via the name of the module (which is just the name…

    Read more

  • Installing Python Modules

    Modules in Python are files containing Python code which you can use in your program, by “importing” them. Packages are collections of modules. Many pre-made modules and packages are available to use in Python. You can install them using pip, the package installer for Python. It’s best to ensure you are working in an activated…

    Read more

Blog at WordPress.com.