Importing modules in Python - best practice

后端 未结 6 555
时光取名叫无心
时光取名叫无心 2020-12-02 11:46

I am new to Python as I want to expand skills that I learned using R. In R I tend to load a bunch of libraries, sometimes resulting in function name conflicts.

What

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 12:20

    They are all suitable in different contexts (which is why they are all available). There's no deep guiding principle, other than generic motherhood statements around clarity, maintainability and simplicity. Some examples from my own code:

    1. import sys, os, re, itertools avoids name collisions and provides a very succinct way to import a bunch of standard modules.
    2. from math import * lets me write sin(x) instead of math.sin(x) in math-heavy code. This gets a bit dicey when I also import numpy, which doubles up on some of these, but it doesn't overly concern me, since they are generally the same functions anyway. Also, I tend to follow the numpy documentation — import numpy as np — which sidesteps the issue entirely.
    3. I favour from PIL import Image, ImageDraw just because that's the way the PIL documentation presents its examples.

提交回复
热议问题