python writing modules and packages

python writing modules and packages

We basically write computer programs to solve the problems. Problem may be simpler or moderate one or a complex. For simple problems we can solve it with 50 to 80 lines of code. If it is the case then we can easily manage the code. But, if code grows in an amount thousands of lines then obiviously it will be very difficult to maintain that code. So, we devide the code into modules each module contains a group of reusable functionalities. After, we combine these modules into packages by putting them into directories based on their nature.

Python Modules

  • Python module is a file it contains definitions and statements.
  • It can be composed of functions, classes and variables.
  • In python, a piece of code in a moule can be inherited to other module using the "import" keyword.
  • Let's do some code and check how it works.
    # simple_math.py
    
    def add(a, b):
        return a + b
    
    def substract(a, b):
        return a - b
    
    # main.py
    from simple_math import add, substract
    
    print(add(100, 50))
    # output: 
    print(substract(100, 50))
    # output:
    
  • In above code we have created a module called "simple_math.py" and imported it's functions in the other module "main.py" and used them.
  • In python source code we can find many reusable modules like os, math, collections, etc.

Python Packages

  • In python a package is simply a directory which contains modules.
  • Each python package must contain a special file named "init.py". Because it tells python interpreter that the directory is a package.
  • we can import a package just like a python module.
  • First see the directory structure

    ├── main.py
    ├── my_package
    │   ├── __init__.py
    │   └── utils.py
    ├── simple_math.py
    
  • Let's do some code and check how it works.

    # utils.py
    def say_hello(name):
        print("Hello {}".format(name))
    
    # main.py
    from my_package import utils
    
    utils.say_hello("LearnBATTA")
    # output: Hello LearnBATTA
    
    - We can find many python packages at PyPI