# Python Modules

> Learn how Python modules work: every file is a module you can pull in with import or from .. import, and how __init__.py turns a folder into a package.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2020-12-25 | Updated: 2026-08-07 | Topics: [Python](https://flaviocopes.com/tags/python/) | Canonical: https://flaviocopes.com/python-modules/

Every [Python](https://flaviocopes.com/python-introduction/) file is a module.

You can import a module from other files, and that's the base of any program of moderate complexity, as it promotes a sensible organization and code reuse.

In the typical Python program, one file acts as the entry point. The other files are modules and expose functions that we can call from other files.

The file `dog.py` contains this code:

```python
def bark():
    print('WOF!')
```

We can import this function from another file using `import`, and once we do, we can reference the function using the dot notation, `dog.bark()`:

```python
import dog

dog.bark()
```

Or, we can use the `from .. import` syntax and call the function directly:

```python
from dog import bark

bark()
```

The first strategy allows us to load everything defined in a file.

The second strategy lets us pick the things we need.

## Renaming what you import

You can give a different name to what you import, using `as`:

```python
from dog import bark as woof

woof()
```

This helps when two modules expose functions with the same name, or when the original name is too long.

## Importing standard library modules

The same syntax works for the modules Python ships with. The standard library is a big collection of modules, and you import them like your own:

```python
import math

print(math.sqrt(16))  # 4.0
```

Nothing to install. If Python runs, the standard library is there.

## Organizing modules in folders

Those modules are specific to your program, and importing depends on the location of the file in the filesystem.

Suppose you put `dog.py` in a `lib` subfolder.

In that folder, you need to create an empty file named `__init__.py`. This tells Python the folder contains modules.

Now you can choose, you can import `dog` from `lib`:

```python
from lib import dog

dog.bark()
```

or you can reference the `dog` module specific function importing from `lib.dog`:

```python
from lib.dog import bark

bark()
```

## A pitfall to avoid

Be careful with file names. If you name one of your files `math.py`, then `import math` in the same folder loads *your* file, not the standard library module.

A call like `math.sqrt(16)` then fails with an `AttributeError`, because your file has no `sqrt` function.

This happens because Python searches the folder of the running script before the standard library. Rename your file, and the import works again.
