How to Set PYTHONPATH? Explain Concepts of Namespace, Scope and Packages in python.
SOLUTION....
Set PYTHONPATH
PYTHONPATH
is an environment variable that Python uses to add extra directories to sys.path
so modules/packages in those directories can be import
ed.
Quick check (see what Python currently searches):

Temporarily (current shell session)
Linux / macOS (bash / zsh):

Permanently
Linux / macOS: add the
export
line to~/.bashrc
/~/.zshrc
(or the shell profile you use).Windows: use System Properties → Environment Variables or run:

Note setx
modifies future sessions, not the current.
Alternatives (recommended for development)
Use a virtual environment and
pip install -e /path/to/your/package
(editable install) so your package is available without relying onPYTHONPATH
.Temporarily at runtime in Python:

Add a
.pth
file to site-packages containing absolute paths (automatic on interpreter start).
Security & practical notes:
Avoid adding untrusted paths.
PYTHONPATH
affects imports globally for the session.Prefer packaging + virtualenv for reproducibility.
How Python finds modules (brief)
When you import x
, Python searches sys.path
in order. sys.path
is initialized roughly as:
The directory containing the running script (or
''
for interactive shell) — current working directory first.Paths listed in
PYTHONPATH
(if set).Standard library directories and installed site-packages.
So PYTHONPATH
entries are searched before site-packages.
Namespace
A namespace is a mapping from names (identifiers) to objects. Think of it as a dictionary where Python stores associations name -> object
.
Common namespaces:
Local namespace: names defined inside a function.
Global (module) namespace: names defined at the top-level of a module.
Built-ins namespace: names provided by Python (e.g.,
len
,int
,print
).Class namespace: attributes defined inside a class body.
Namespaces keep names isolated so the same identifier can be reused in different places without conflict.
Scope (LEGB rule)
Scope describes where a name is visible. Python resolves names using the LEGB rule:
Local — inside the current function.
Enclosing — any enclosing function scopes (for nested functions).
Global — module-level names.
Built-in — names in the
builtins
module.
Example (shows LEGB + nonlocal
and global
)
