Importing with dot notation
Emily Wong
Can someone explain this to me?
When you import Tkinter.Messagebox what actually does this mean (Dot Notation)?
I know that you can import Tkinter but when you import Tkinter.Messagebox what actually is this? Is it a class inside a class?
I am new to Python and dot notation confuses me sometimes.
42 Answers
When you're putting that dot in your imports, you're referring to something inside the package/file you're importing from. what you import can be a class, package or a file, each time you put a dot you ask something that is inside the instance before it.
parent/ __init__.py file.py one/ __init__.py anotherfile.py two/ __init__.py three/ __init__.pyfor example you have this, when you pass import parent.file you're actually importing another python module that may contain classes and variables, so to refer to a specific variable or class inside that file you do from parent.file import class for example.
this may go further, import a packaging inside another package or a class inside a file inside a package etc (like import parent.one.anotherfile)
For more info read Python documentation about this.
import a.b imports b into the namespace a, you can access it by a.b . Be aware that this only works if b is a module. (e.g. import urllib.request in Python 3)
from a import b however imports b into the current namespace, accessible by b. This works for classes, functions etc.
Be careful when using from - import:
from math import sqrt
from cmath import sqrtBoth statements import the function sqrt into the current namespace, however, the second import statement overrides the first one.