Importing modules in Python - best practice

后端 未结 6 557
时光取名叫无心
时光取名叫无心 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条回答
  •  难免孤独
    2020-12-02 12:21

    Disadvantage of each form

    When reading other people's code (and those people use very different importing styles), I noticed the following problems with each of the styles:

    import modulewithaverylongname will clutter the code further down with the long module name (e.g. concurrent.futures or django.contrib.auth.backends) and decrease readability in those places.

    from module import * gives me no chance to see syntactically that, for instance, classA and classB come from the same module and have a lot to do with each other. It makes reading the code hard. (That names from such an import may shadow names from an earlier import is the least part of that problem.)

    from module import classA, classB, functionC, constantD, functionE overloads my short-term memory with too many names that I mentally need to assign to module in order to coherently understand the code.

    import modulewithaverylongname as mwvln is sometimes insufficiently mnemonic to me.

    A suitable compromise

    Based on the above observations, I have developed the following style in my own code:

    import module is the preferred style if the module name is short as for example most of the packages in the standard library. It is also the preferred style if I need to use names from the module in only two or three places in my own module; clarity trumps brevity then ("Readability counts").

    import longername as ln is the preferred style in almost every other case. For instance, I might import django.contrib.auth.backends as djcab. By definition of criterion 1 above, the abbreviation will be used frequently and is therefore sufficiently easy to memorize.

    Only these two styles are fully pythonic as per the "Explicit is better than implicit." rule.

    from module import xx still occurs sometimes in my code. I use it in cases where even the as format appears exaggerated, the most famous example being from datetime import datetime (but if I need more elements, I will import datetime as dt).

提交回复
热议问题