Research on the mechanism of using statements to import modules or packages in Python

Source: Internet
Author: User
This article discusses Python's from Import * and from Import *, how they execute and why using this syntax (perhaps) is a bad idea.
import all from one module

from import * means means "I want to have access to all the names I have access to." For example, the following code something.py:

# something.py public_variable = 42_private_variable = 141 def public_function ():  print ("I ' m a public function! yay! ") Def _private_function ():  print ("Ain ' t nobody accessing me from another module...usually") class Publicclass (object) :  Pass Class _weirdclass (object):  Pass

In the Python interpreter, we can execute from something import *, and then see something like this:

>>> from something import *>>> public_variable42>>> _private_variable ... Nameerror:name ' _private_variable ' is not defined>>> public_function () "I ' m a public function! yay! " >>> _private_function () ... Nameerror:name ' _private_function ' is not defined>>> C = Publicclass () >>> c
 
    
     
  >> > c = _weirdclass () ... Nameerror:name ' _weirdclass ' is not defined
 
    

From something import * imported from something all names except the name beginning with _, by specification, _ The name started is private so it was not imported.
Well, not particularly bad! What else?

There is no mention of what __all__ is. __ALL__ is a list of strings that specify which symbols in the module (or packages mentioned later) are exported when the from import * is used. If we do not define __ALL__ (we do not define it in the above something.py), import * The default is to import all names except the underscore (_). Again, the programming conventions underscore that a symbol is private, and that it is reasonable not to import it. Let's see what happens when we define our own __all__ in something.py.

# something.py __all__ = [' _private_variable ', ' Publicclass '] # The rest is the same as before public_variable = 42_privat e_variable = 141 def public_function ():  print ("I ' m a public function! yay! ") Def _private_function ():  print ("Ain ' t nobody accessing me from another module...usually") class Publicclass (object) :  Pass Class _weirdclass (object):  Pass

Now, we expect that from something import * only _private_variable and Publicclass will be imported:

>>> from something import *>>> public_variable42>>> _private_variable ... Nameerror:name ' _private_variable ' is not defined>>> public_function () "I ' m a public function! yay! " >>> _private_function () ... Nameerror:name ' _private_function ' is not defined>>> C = Publicclass () >>> c
 
    
     
  >> > c = _weirdclass () ... Nameerror:name ' _weirdclass ' is not defined
 
    

What is the package like?

When importing all from a package, the __all__ approach is essentially the same as the module, but it handles the modules in the package (rather than importing the names in the module). So when we use from import *. __all__ describes all modules that need to be imported into the current namespace.

The difference is that if you do not declare the __ALL__,FROM import * statement in a package __init__.py it will not import anything (this is not entirely true, the correct statement here)
But what's wrong with that?

Before you continue reading, in your Python interpreter, execute import this, and then read the Python Zen (read to them before your child sleeps every night).

Clarity is better than ambiguity.

The From import * is ambiguous. It didn't tell us what we were importing or what we brought into the current namespace. A better approach is to explicitly import all the names we need. In this way, the reader (very likely the future of yourself) will not be confused by the use of a variable/method/class/Other thing in your code, which also tells us the next point:

Readability is important

Even if you need to import a lot of things, an explicit import is also clearer. Using PEP 328:

From Tkinter import (Tk, Frame, Button, Entry, Canvas, Text, left  , DISABLED, NORMAL, RIDGE, END)

You can now know exactly what's in your namespace, and using Ctrl+f can quickly tell you where they came from.

At the same time, you always have to bear the risk of the module/package author changing the list content (plus/minus things). One of the following:

The author removed a string from __all__. If your code uses that name, your code will report nameerror errors and it's hard to see why.
The author added a lot of things to the __all__. You may not need the added content, so you're just letting those things you don't care about fill up your namespace. They will replace other names even when you are not aware of them.

Of course, it is sometimes useful to import all the content from a module or package. However, think twice before doing so. From my experience, it's usually just lazy.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.