Use 'import module' or 'from module import'?

前端 未结 19 2134
一向
一向 2020-11-21 07:47

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

19条回答
  •  日久生厌
    2020-11-21 08:07

    There are some builtin modules that contain mostly bare functions (base64, math, os, shutil, sys, time, ...) and it is definitely a good practice to have these bare functions bound to some namespace and thus improve the readability of your code. Consider how more difficult is to understand the meaning of these functions without their namespace:

    copysign(foo, bar)
    monotonic()
    copystat(foo, bar)
    

    than when they are bound to some module:

    math.copysign(foo, bar)
    time.monotonic()
    shutil.copystat(foo, bar)
    

    Sometimes you even need the namespace to avoid conflicts between different modules (json.load vs. pickle.load)


    On the other hand there are some modules that contain mostly classes (configparser, datetime, tempfile, zipfile, ...) and many of them make their class names self-explanatory enough:

    configparser.RawConfigParser()
    datetime.DateTime()
    email.message.EmailMessage()
    tempfile.NamedTemporaryFile()
    zipfile.ZipFile()
    

    so there can be a debate whether using these classes with the additional module namespace in your code adds some new information or just lengthens the code.

提交回复
热议问题