The most efficient way to import

In terms of performance (time or memory) it is better to do:

import pandas as pd

or

from pandas import DataFrame, TimeSeries

Is it best to depend on how many classes I import from the package?

In the same way, I saw people doing things like:

def foo(bar):
    from numpy import array

Why would I want to import within a function or method definition? Doesn't that mean that the import is done every time the function is called? Or is it just to avoid namespace conflicts?

+4
source share
3 answers

This is micro-optimization, and you should not worry about it.

Modules are loaded once in the Python process. All code that then imports should only associate the name with the module or objects defined in the module. This binding is extremely cheap.

, , . , , , , .

: ( ), , , .

, , , . .

+6

, , - . , , . , .

, pypy , , pypy. , .

"import pandas pd" vs "from pandas import DataFrame, TimeSeries", ( ), . , , . , , 0,0001% . 90%. 10%, .

, , import X as Y, form X import Y - , , . 2000, , "calculate_mean" - , . numpy, / , / pip install np. , , , , "np" - python "numpy", 3- , . numpy. numpy.

+1

, : . , @J.J answer , .

? , , , :

, , , , .

MSDN:

script . , Qt, Pandas, Numpy Matplotlib. , . , - .

But if, for example, Matplotlib is imported only from those functions that are called whenever the user issues the plot command, the startup time is noticeably reduced. The user does not perceive your application so sluggish that it may lead to a better user experience.

+1
source

Source: https://habr.com/ru/post/1659939/


All Articles