Import or from import, that is the question

There are three stages of knowledge: you use the tool, you understand how it works, you can teach others to work with this tool. Little by little, he began to flow into the third and began to ask himself questions that he had not asked before.







For example, which is better: import module



or from module import function



?







I decided to dig into this a little deeper, the answers on StackOverflow did not satisfy me.







For those who are too lazy to read: all options are good.







Tips from the creators of the language



Let's turn to the primary sources, namely - to PEP8







When importing a class from a module, it's okay to do it like this:







from myclass import MyClass
from foo.bar.yourclass import YourClass
      
      





, :







import myclass
import foo.bar.yourclass
      
      





myclass.MyClass



foo.bar.yourclass.YourClass





PEP-8 .







?



, . . , .









, — . , , .







"" "" .







from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!
      
      





from bottle import route, run, template

@route('/hello/<name>')
def index(name):
    return template('<b>Hello {{name}}</b>!', name=name)

run(host='localhost', port=8080)
      
      





.







import pytest

def test_zero_division():
    with pytest.raises(ZeroDivisionError):
        1 / 0
      
      





, .

.

, .









. , .







import json

json.load(...)
json.loads(...)
json.dump(...)
json.dumps(...)
      
      





.







from pickle import load
from marshal import dumps
from xmlrpc.client import loads
from xml.etree.ElementTree import dump
      
      





load



json.load



, pickle.load



.

. – . , – . , . , .









, . , .







— , .

, IDE , . , . , isort.







.









. . .







, .









IDE , . : , / . , , ,

– .







100% – . , .







MonkeyPatch



- . . , , , , , , , .

, , - .







– .









, / . , .









, . import module



, from module import item as module_item



. , as



, , . .







import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
      
      







In my opinion, using both approaches does not greatly violate the uniformity, and you can safely mix them. It is desirable, however, not for the same module. Some tools swear at this: https://lgtm.com/rules/1818040193/







Conclusion



For myself, I take the following approach when importing and writing my modules.

Use import from



, except when:







  • there is (or is likely later) a name conflict;
  • functions / classes of the module have short and common names ( json



    );
  • there are well-established traditions or specific recommendations of the authors of the module, for example pytest



    .



All Articles