Python Packages and Modules

How does import packages/modules work in python

Syntax

import <module_name>
from <module_name> import <name(s)>
from <module_name> import <name> as <alt_name>
import <module_name> as <alt_name>

Import By Modules Example

.
├── demo.py
└── mod.py

demo.py

import mod

print(mod.s)
print(mod.a)
mod.foo(['aaa', 'bbb', 'ccc'])

mod.py

s = "hello world"
a = [100, 200, 300]

def foo(arg):
    print(f'arg = {arg}')

class Foo:
    def hello():
        print("hi")

output

# python3 demo.py
# >> output

# hello world
# [100, 200, 300]
# arg = ['aaa', 'bbb', 'ccc']

Import functions / classes of a module

.
├── demo.py
├── demo2.py
└── mod.py

demo2.py

from mod import Foo

Foo.hello()

Import by Package Example

use the same python files above. restructure as following and update demo.py

.
├── demo.py
└── pkgs
    ├── module1
    │   ├── __init__.py
    │   └── mod.py
    └── module2
        └── mod2.py

demo.py

from pkgs.module1 import mod
from pkgs.module2 import mod2

print(mod.s)
print(mod2.s)

mod2.py

s = "hello there"
a = [100, 200, 300]

def bar(arg):
    return f'arg = {arg}'

class Foo:
    def hey():
        print("how r u")
output:
hello world
hello there

create packages as folders, put a __init__.py in those folders to help make folders a package friendly structure, python3 does not require __init__.py, please refer to implicit namespace packages from https://peps.python.org/pep-0420/#rationale, but some IDEs detects __init__.py to form a python packages, hence put __init__.py anyway

Do you like the article “Python Packages and Modules” ? If you want latest update and find more tips and tricks to build your own business platform, please checkout more articles on https://www.productdeploy.com and https://blog.productdeploy.com

Share This

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*
*