Why should we import Messagebox explicitly into Tkinter even if it matters with the asterisk?

Asked

Viewed 179 times

3

Whenever I see programs using tkinter and messagebox see the following two lines at the beginning of the code:

from tkinter import *
from tkinter import messagebox

If we use from tkinter import * we import the entire library tkinter, why the need to call the function messagebox the part?

  • In fact, you nay must import with "*" to start. To avoid typing "Tkinter. ' all the time you can: explicitly import whatever you use, or, do import tkinter as tk (in this second case, messagebox, which is a submodule, still needs to be imported explicitly)

2 answers

4

Just like this reply from Soen, the import of from tkinter import messagebox is needed simply by the way the package is designed to work.

The author of tkinter decided that importing "*" wouldn’t matter messagebox, or some of the other packages (ttk is another example)

PS: In general, you should not import "*" even so.

4


That’s because unlike what some think the asterisk doesn’t matter all necessarily.

When you do:

from X import *

If X for a module, the interpreter will search for X.__all__, if X is a package, will search for X.__init__.__all__. If this object exists, it will define what will be imported when using the asterisk. Only all will be imported when the __all__ undefined.

For example, if we create a module called foo.py:

# foo.py

__all__ = ['foonction']

def foonction():
    pass

def barction():
    pass

And in another file we do:

from foo import *

We will have in our current scope the import of foo.foonction, but not of foo.barction. To import the function barction we need to do this explicitly:

from foo import barction

That’s exactly what happens with tkinter.messagebox. By decision of the developers chose not to expose messagebox in the __all__.

And I need to disagree with what was put in the other answer:

Generally speaking, you should never matter * even so.

This information is not necessarily wrong, but is necessarily incomplete. If you couldn’t import using the asterisk this option wouldn’t even exist in the language. After all, why create something you can’t use? The point is to use it when you know what you’re doing; if you’re aware of what the import does, use it fearlessly.

But this is bigger than importing modules, just do what you know you’re doing and never use something without understanding - whether you’re importing a Python module or doing anything else in any language.

  • I get it. So basically it was the decision of the developer.

  • Exactly. Beautiful answer. + 1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.