# What are Python namespaces?

**URL:** <https://discuss.python.org/t/what-are-python-namespaces/6441>\
**Category:** Python Help\
**Tags:** pypi-q1-2019-ms-2\
**Created:** [January 2, 2021, 10:07am UTC](https://discuss.python.org/t/what-are-python-namespaces/6441 "2021-01-02T10:07:45Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![jeanas](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/jeanas/32/8115_2.png) [@jeanas](https://discuss.python.org/u/jeanas)\
**Post date:** [January 2, 2021, 11:06am UTC](https://discuss.python.org/t/what-are-python-namespaces/6441/2 "2021-01-02T11:06:27Z")

</div>

A simple way to put it is that when you are writing a 100,000-lines program, it is impossible to choose different names for all variables. So, every function defines a namespace. It is like a box with bindings (variables) inside, and the variables cannot be accessed from the outside.

```auto
>>> def f(x):
... a = x + 2
... print(a)
... 
>>> f(5)
7
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

```

Modules are also namespaces. There is not a single `sqrt` function for example. The one from `math` applies to floats. The one from `cmath` also handles complex number. Thanks to namespaces, there is no conflict between these functions. They are called `math.sqrt` and so on.

Furthermore, you will discover when you learn object-oriented programming that objects are namespaces too. A simple example is file objects:

```auto
>>> file = open("foo")
>>> file.name
'foo'
>>> file.closed
False
>>> file.mode
'r'
>>> file.encoding
'UTF-8'

```

See? This file object has associated data, which it owns. The object is a form of namespace.

You can read a lot on the net about namespaces, like

[https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces](https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces)  
[https://www.programiz.com/python-programming/namespace](https://www.programiz.com/python-programming/namespace)

> **[What Are Python Namespaces (And Why Are They Needed?)](https://code.tutsplus.com/tutorials/what-are-python-namespaces-and-why-are-they-needed--cms-28598)**
>
> Name conflicts happen all the time in real life. For example, every school that I ever went to had at least two students in my class who shared the same first name. If someone came into the class...

---

_[View the full topic](https://discuss.python.org/t/what-are-python-namespaces/6441)._
