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

Source: Internet
Author: User
This article mainly introduces the mechanism of using statements to import modules or packages in Python, compares the statements of several imported packages or modules, and briefly describes the advantages and disadvantages of these methods, you can refer to this article to discuss the Python from Import * and from Import *, how to execute them and why to use this syntax (maybe) is a bad idea.
Import all from one module

From Import * means "I want to access ". 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 see the following content:

>>> 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 * imports all names except the names starting with _ from something. according to the rules, the names starting with _ are private and are not imported.
Well, it's not that bad! What else?

We didn't mention what _ all _ is. _ All _ is a string list, specifying When import * is used, which symbols in the module (or the package mentioned later) will be exported. If we do not define _ all _ (we didn't define something. py above), the default import method for import * is to import all names starting with underscores. Again, in programming conventions, underlines indicate that a symbol is private and not imported properly. 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_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

Now, we expect that from something import * will only import _ private_variable and PublicClass:

>>> 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?

When importing all data from a package, the _ all _ method is basically the same as that of the module, but it processes the modules in the package (instead of importing all the names in the module ). So when we use from Import *. _ all _ indicates all the modules to be imported into the current namespace.

The difference is that if you do not declare _ all __, from The import * statement does not import anything (This statement is not completely correct. the correct statement is here)
But what's worse?

Before continuing to read, execute import this in your Python interpreter and read the Python Zen again (read it to your child every night before going to bed ).

Being clear is better than being vague.

From Import * is not clear. It does not tell us what we are importing or what we are bringing to the current namespace. It is better to explicitly import all the names we need. In this way, the reader (probably yourself in the future) will not be confused about where a variable, method, class, or other things are used in your code, this also tells us the next point:

Readability is important

Even if you need to import many things, it is clearer to import them one by one explicitly. Use PEP 328:

from Tkinter import (Tk, Frame, Button, Entry, Canvas, Text,  LEFT, DISABLED, NORMAL, RIDGE, END)

Now you can clearly understand what is in your namespace, and use ctrl + f to quickly tell you where they come from.

At the same time, you are always at risk of changing the list content (add/subtract) by the module/package author. That is, one of the following two:

The author deletes a string from _ all. If your code uses that name, your code will report a NameError and it is difficult to find out why.
The author adds many things in _ all. You may not need the added content, so you just fill your namespace with the things you don't care about. They even replace other content with the same name when you don't pay attention to it.

Of course, it is useful to import all the content from a module or package. However, think twice before doing so. In my experience, this is usually just a result of laziness.

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.