Python Basics:

Python Import:

When we create a bunch of functionalities. It is possible that the similar functionalities need to be used in another place. In this case, we can create a file and import this file wherever we need it. 

Another case, let us say we have a large python file. There is a possibility of writing a util.py file or a bunch files for specific functionality and call them into our main file. We do this to simplify our scripts/code files. In this case, we need to split the giant file and organise in multiple files.

We can import following modules:

  • built-in module such os, sys
  • externally created module such as fastapi, pydantic,
  • local custom files and/or .so file we created
In order to import a module of any kind we can take following approach

import everything from a module in our current file (also known as global namespace). This pose a conflict problem. For example if an entity is defined in the imported module and we redefined the same entity. This will create issues of precedence of recently defined entity. 

from os import *

import specific entities from a module in our current file. This pose the problem of conflict as well but things are more controlled now. 

from sys import path,

import all entities from a module as a separate namespace. The only issue remains here is that we don't redefine the module itself. 

import site 

# site="offshore" # blunder

We can also create alias to keep module shorter or use a different name

import pandas as pd

from sys import path as pth

We can import multiple modules in the same line as well

import pandas, numpy, os, sys

To check all the entities provided by a module we can use dir built-in function

import fastapi

dir(fastapi)

-> platform module for machine information

__name__ variable

The value of __name__ variable becomes  main in the file when that file itself is run. 
If the same file is called from a different file which is getting executed, the value of __name__ variable becomes the name of the file. 

We can use the fact that the variable name is getting changed, we can do testing of the functionality we have developed in the same file. But when we call the module script, the __name__ == "__main__" condition will fail in another script. 
Example:
# module.py file

#!/usr/bin/env python3

''' module.py - an example of a python module '''
__counter = 0

def get_sum(numbers):
    global __counter
    total = 0
    for element in numbers:
        __counter += 1
        total += element
    return total

if __name__ == "__main__":
    print("I prefer to be a module but I can do some tests for you")
    nums = [i + 1 for i in range(5)]
    print(get_sum(nums))


# main.py
from module import get_sum, __name__

print("the name of module is ", __name__)

zeros = [ 0 for _ in range(5)]
ones = [1 for _ in range(5)]

print(zeros)
print(ones)

print(get_sum(zeros))
print(get_sum(ones))

Module Search path:

#!/usr/bin/env python3

from sys import path as paths

for path in paths:
    print(path)

/Users/macbookpro/sitendra/2025/python_/path_identification/sample
/Library/Frameworks/Python.framework/Versions/3.13/lib/python313.zip
/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13
/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/lib-dynload
/Users/macbookpro/sitendra/2025/fastapi/venv/lib/python3.13/site-packages

python supports importing from .zip file as well. 

When we import a module (any module), python looks for it in a list of predefined directories in sys.path. 
Three main directories
- current working directory or the directory where the python script is available. 
- site-packages
- python-specific paths 

Import module from a custom package/directory

# custom module
# ownmodule/module1.py
print("I am in module 1")

# main.py 
from sys import path
# to ask python to look for this directory, we can add the path in sys.path
path.append("ownmodule")
from ownmodule import module1


Python namespace:

Local namespace: example variable inside a function

Enclosing namespace: A function inside a function. Where inside function can access outside entity. 

Global namespace: Anything defined in the main file. If it is a module file, then for its own file we have the global scope

Built-in namespace: Some of the functions are always available such as print, dir, len when an interpreter gets the call. 

local, enclosing, global namespaces are lived until the execution. 

We need namespace to resolve the conflict of defined entities such as variables and functions. 

list = []

new_list = list(1,2,3)

We are not reaching to built-in namespace

LEGB 

What is the difference between myprogram.txt and myprogram.py?

They both are text files. 

A TXT file can be written with any texts in it while a python file is written with texts in certain manner. 

python interpreter is a software. It is designed such that if a file written in specific style is fed to it then it does manipulation and spits out an outcome. 

If we control manipulation, we can achieve certain outcome that we desiring for. 

Example if we write the text file with rules of multiplication, division, addition, we can calculate simple interest. We don't need to manually do it with hands. 


python3 myprogram.py


Python path discovery

sys.path

Python provides sys library which considers available PYTHONPATH.  

sys.path lists all the PYTHONPATH

We can append a path to it just like any other list. 

sys.path.append("<path-to-be-added->")

PYTHONPATH as an environment variable

export PYTHONPATH=<path-to-be-added>

echo "PYTHONPATH=<path-to-be-added>" > ~/.zshrc # It can be any other shell. 

.pth file

add paths in the site-package of .pth file. It is a good practice as it will keep the python library path accessible. 

1. locate the site-package and create a file <any-name>.pth inside and below code. Or just path.

2. Add below import os, sys; sys.path.append(os.getenv('MY_EXT_LIB'))





Comments

Popular posts from this blog

Git Basics

Linux Basics

Internet basics