'from X import a' versus 'import X; X.a'

I've seen some Python programmers use the following style fairly consistently (we'll call it style 1):

import some_module
# Use some_module.some_identifier in various places.

For support of this style, you can cite the "explicit is better than implicit" maxim. I've seen other programmers use this style (style 2):

from some_module import some_identifier
# Use some_identifier in various places.

The primary benefit that I see in style 2 is maintainability -- especially with duck typing ideals I may want to swap some_module for some_other_module. I also feel style 2 wins points with the "readability counts" maxim. Although I tend to disagree, one can always argue that search-and-replace is just as good an option when using the first style.

Addendum: It was noted that you could use as to solve the switch from some_module to some_other_module in style 1. I forgot to mention that it is also common to decide to implement some_identifier in your current module, which makes creation of an equivalent some_module container slightly awkward.


Asked by: Audrey189 | Posted: 05-10-2021






Answer 1

There are uses for both cases, so I don't think this is an either-or issue. I'd consider using from module import x,y,z when:

  • There are a fairly small number of things to import

  • The purpose of the functions imported is obvious when divorced from the module name. If the names are fairly generic, they may clash with others and tell you little. eg. seeing remove tells you little, but os.remove will probably hint that you're dealing with files.

  • The names don't clash. Similar to the above, but more important. Never do something like:

     from os import open
    

import module [as renamed_module] has the advantage that it gives a bit more context about what is being called when you use it. It has the disadvantage that this is a bit more cluttered when the module isn't really giving more information, and is slightly less performant (2 lookups instead of 1).

It also has advantages when testing however (eg. replacing os.open with a mock object, without having to change every module), and should be used when using mutable modules, e.g.

import config
config.dburl = 'sqlite:///test.db'

If in doubt, I'd always go with the import module style.

Answered by: Carlos812 | Posted: 06-11-2021



Answer 2

With the existence of the following syntax:

import some_other_module as some_module

the maintainability argument of style 2 is no longer relevant.

I tend to use style 1. Normally, I find that I explicitly reference the imported package name only a few times in a typical Python program. Everything else is methods on the object, which of course don't need to reference the imported package.

Answered by: Fenton588 | Posted: 06-11-2021



Answer 3

I usually use a threshold to decide this. If I want to use a lot of things within some_module, I'll use:

import some_module as sm
x = sm.whatever

If there's only one or two things I need:

from some_module import whatever
x = whatever

That's assuming I don't need a whatever from some_other_module, of course.

I tend to use the as clause on the imports so that I can reduce my typing and substitue another module quite easily in the future.

Answered by: Lana671 | Posted: 06-11-2021



Answer 4

I prefer to import X and then use X.a as much as possible.

My exception centers on the deeply nested modules in a big framework like Django. Their module names tend to get lengthy, and their examples all say from django.conf import settings to save you typing django.conf.settings.DEBUG everywhere.

If the module name is deeply nested, then the exception is to use from X.Y.Z import a.

Answered by: Lydia466 | Posted: 06-11-2021



Answer 5

I find that the notation

from some_module import some_symbol

works best in most cases. Also, in case of name clash for the symbol, you can use:

from some_module import some_symbol as other_symbol

As the question states, it avoids rewriting the module name all the time, each time with a risk of mistyping it. I use the syntax:

import  module [as other_module]

Only in two cases:

  1. I use too many of the module functions/objects to import them all
  2. The module defines some symbol that may change during execution

Answered by: Stuart229 | Posted: 06-11-2021



Answer 6

I personally try not to mess too much with my namespace, so in most situations I just do

import module  

or import module as mod

Only real diffrence is when I have a module with a single class that's used a lot. If I had sublclassed a list type to add some funcionality there, I'd use

from SuperImprovedListOverloadedWithFeatures import NewLIst
nl = NewList()

etc.

Answered by: Catherine115 | Posted: 06-11-2021



Answer 7

I tend to use only a few members of each module, so there's a lot of

from john import cleese
from terry import jones, gilliam

in my code. I'll import whole modules (such as os or wx) if I expect to be using most of the module and the module name is short. I'll also import whole modules if there is a name conflict or I want to remind the reader what that function is associated with.

import michael
import sarah

import wave

gov_speech = wave.open(sarah.palin.speechfile)
parrot_sketch = wave.open(michael.palin.justresting)

(I could use from wave import open as wave_open, but I figure that wave.open will be more familiar to the reader.

Answered by: Andrew929 | Posted: 06-11-2021



Answer 8

You may be interested in Stack Overflow question Why does 'import x;x.y' behave different from 'from x import y', and the first one fails when package x.init is not completed?.

Answered by: John680 | Posted: 06-11-2021



Answer 9

I believe in newer versions of Python (2.5+? must check my facts...) you can even do:

import some_other_module as some_module

So you could still go with style 1 and swap in a different module later on.

I think it generally maps to how much you want to clutter up your namespace. Will you just be using one or two names in the module? Or all of them (from x import * is not allways bad, just generally)?

Answered by: Hailey99 | Posted: 06-11-2021



Similar questions

Python import error when I just 'import numpy'

I use Ubuntu 16.04 and installed Python3, numpy, pandas. When I just entered 'import numpy', the following error came out. Traceback (most recent call last): File "regression1.py", line 3, in <module> import numpy File "/home/user/.local/lib/python3.5/site-packages/numpy/__init__.py", line 142, in <module> from . import core File "/home/user/.local/lib/python3.5/site-packages/n...


python - 'from X import a' works but 'import X; X.a' doesn't

This question already has answers here:


macos - Mac OS X python 'import vigra' error

I want to use vigra under Mac OS X 10.6.4. So I installed all dependencies with Macpotrs. Everything compiled and I could install vigra too. But when I try to import vigra, then I get a 'Segmentation fault'. Do someone know how to solve this problem? Here the Mac OS X error report: Process: Python [784] Path: /opt/loc...


python - How to run 'import data'?

I am trying to figure out how to run the script below. #------------Necessary Variables--------------# import datetime as dt symbols = ['INTC','VZ','AAPL', 'AMZN', 'MSFT', 'CAT', 'AXP', 'BA', 'GE', 'CVX', 'HD', 'NKE', 'PFE', 'MMM', 'TRV', 'UTX', 'MRK', 'DIS', 'DWDP', 'JNJ'] allocations = [25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25] start_date = dt.date(2017, 1, 3) #Bench...


Python import error when I just 'import numpy'

I use Ubuntu 16.04 and installed Python3, numpy, pandas. When I just entered 'import numpy', the following error came out. Traceback (most recent call last): File "regression1.py", line 3, in <module> import numpy File "/home/user/.local/lib/python3.5/site-packages/numpy/__init__.py", line 142, in <module> from . import core File "/home/user/.local/lib/python3.5/site-packages/n...


python - 'from X import a' works but 'import X; X.a' doesn't

This question already has answers here:


macos - Mac OS X python 'import vigra' error

I want to use vigra under Mac OS X 10.6.4. So I installed all dependencies with Macpotrs. Everything compiled and I could install vigra too. But when I try to import vigra, then I get a 'Segmentation fault'. Do someone know how to solve this problem? Here the Mac OS X error report: Process: Python [784] Path: /opt/loc...


syntax - Python : 'import module' vs 'import module as'

Is there any differences among the following two statements? import os import os as os If so, which one is more preferred?


python - 'import x' vs " 'from x import y' and 'import x.y' "

I tried from urllib import request mine = request.Request() and import urllib.request mine = urllib.request.Request() They both work fine. But import urllib mine = urllib.request.Request() gives me AttributeError: 'module' object has no attribute 'request' Shouldn't it work too consid...


python - Can I add 'import pandas' to the %pylab magic?

Every jupyter notebook I write has the same first two lines: %pylab inline import pandas How can I add pandas to pylab's imports, so that I no longer need to import it separately. Thanks!


python - 'import this' and view it with command 'less'

I'd like to check a word in 'The Zen of Python'. Firsty, import this from ipython In [1]: import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. ... Secondly, Ctr...


python - How to run 'import data'?

I am trying to figure out how to run the script below. #------------Necessary Variables--------------# import datetime as dt symbols = ['INTC','VZ','AAPL', 'AMZN', 'MSFT', 'CAT', 'AXP', 'BA', 'GE', 'CVX', 'HD', 'NKE', 'PFE', 'MMM', 'TRV', 'UTX', 'MRK', 'DIS', 'DWDP', 'JNJ'] allocations = [25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25] start_date = dt.date(2017, 1, 3) #Bench...


Python import error when I just 'import numpy'

I use Ubuntu 16.04 and installed Python3, numpy, pandas. When I just entered 'import numpy', the following error came out. Traceback (most recent call last): File "regression1.py", line 3, in <module> import numpy File "/home/user/.local/lib/python3.5/site-packages/numpy/__init__.py", line 142, in <module> from . import core File "/home/user/.local/lib/python3.5/site-packages/n...


python - 'from X import a' works but 'import X; X.a' doesn't

This question already has answers here:


Need a help 'import random' in python

Closed. This question needs details or clarity. It ...


python - Use 'import module' or 'from module import'?

I've tried to find a comprehensive guide on whether it is best to use import module or from module import. I've just started with Python and I'm trying to start off with best practices in mind. Basically, I was hoping if anyone could share their experiences, what preferences other developers have and what's the best way to avoid any gotchas down the road?






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top