Import Statements

📦 Python comes with many built-in modules and also allows you to use external packages. To use code from other modules or libraries, you use import statements.

import a Module

Import the whole module and access functions or classes with dot notation.

from ... import ...

Import specific parts (functions, classes, variables) from a module directly.

Aliasing with as

Use as to give a module or function an alias—useful for shortening long names.

Wildcard Import (*)

Import everything from a module (not recommended in most cases).

Avoid using * in production code—it can pollute your namespace and create conflicts.

Importing Custom Modules

You can also import your own .py files as modules.

Suppose you have a file myutils.py with the following code:

|_ myutils.py <- here
def greet():
    print("Hello from myutils!")

You can import and use it on a different Python file:

|- myutils.py
|_ python-advanced.py <- here
from myutils import greet
greet()  # Hello from myutils!
Hello from myutils!

Conditional Imports

You can import modules inside functions or conditionally.

Common Errors

Some frequent errors encountered when dealing with Import Statements in Python.