Importing and Exporting Modules in Python

Everything in python is itself modularized and is exported by default. These modules — Classes, Functions, and even variables can be imported across packages. Following demo illustrates the above statement:

module.py
class Cars:
 def on_wheels(self,car_name):
   return f"Inside Cars -> on_Wheels method{car_name}"
 
def sum_of_variables(a,b,c):
 return a+b+c
 
CONSTANT_VARIABLE = [100,"Apple",3.14]
test.py
# Import Class, Constants or functions
from module import Cars, CONSTANT_VARIABLE, sum_of_variables
 
print('Accessing Class Methods', Cars().on_wheels('Ferrari'))
print('Accessing Functions', sum_of_variables(50,100,200))
print('Accessing Constants', CONSTANT_VARIABLE)
Output:
Accessing Class Methods Inside Cars -> on_Wheels methodFerrari
Accessing Functions 350
Accessing Constants [100, 'Apple', 3.14]

Suppose the following is the project’s directory structure:

lib/general.py

Static methods and class variables/properties can be imported as well. Static methods can be defined in the following ways using:

  1. Decorators - @ operator
  2. in-built method - staticmethod()
class BaseClass:
  def __init__(self):
    self.location = "Texas, AU"

  @staticmethod
  def example_method(name):
    print(f"Name is ::: {name}")
  
  def hello_method(*args):
    print(f"$Hello,{args[0]}. Welcome to {args[1]}")

BaseClass.hello_method = staticmethod(BaseClass.hello_method)
Test/test.py

Importing and invoking static methods directly using class reference:

from lib.general import BaseClass

BaseClass.example_method("linus torvalds")

# Calling exported method directly
BaseClass.hello_method("Programmers","Python")

# Accessing class property
print(BaseClass(4000).location)
Output:
Name is ::: linus torvalds
$Hello,Programmers. Welcome to Python
Texas, AU

Fun activity:

write import this in your project file or python console, read a fascinating and entertaining poem about python. 🐍

Kartik Kapgate

Kartik Kapgate

Software Engineer | Backend