Importing with Dot Notation

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.

4

2 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__.py

for 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.

5

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 sqrt

Both statements import the function sqrt into the current namespace, however, the second import statement overrides the first one.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest