代码之家  ›  专栏  ›  技术社区  ›  Bijoy

在正常情况下使用内置的import()

  •  1
  • Bijoy  · 技术社区  · 7 年前

    我在这里检查了 __import__()

    In [9]: %%timeit
       ...: math = __import__('math')
       ...: sqrt = math.sqrt
       ...: sqrt(7894561230)
       ...: 
    The slowest run took 11.16 times longer than the fastest. This could mean that an intermediate result is being cached.
    1000000 loops, best of 3: 534 ns per loop
    
    In [10]: %%timeit
        ...: from math import sqrt
        ...: sqrt(7894561230)
        ...: 
        ...: 
    The slowest run took 10.23 times longer than the fastest. This could mean that an intermediate result is being cached.
    1000000 loops, best of 3: 979 ns per loop
    

    内置 __import__

    那么它可以像我用过的那样用在代码中吗?或者这样做有什么重大危害吗, 医生没有说这样做有什么害处。

    导入名称仅在运行时已知的模块。

    1 回复  |  直到 7 年前
        1
  •  3
  •   Right leg A.s. Bhullar    7 年前

    这是一个小的“基准”。让我们定义两个函数:

    def f1():
        import sys
    
    def f2():
        sys = __import__('sys')
    

    >>> dis.dis(f1)
      5           0 LOAD_CONST               1 (0)
                  2 LOAD_CONST               0 (None)
                  4 IMPORT_NAME              0 (sys)
                  6 STORE_FAST               0 (sys)
                  8 LOAD_CONST               0 (None)
                 10 RETURN_VALUE
    
    >>> dis.dis(f2)
      8           0 LOAD_GLOBAL              0 (__import__)
                  2 LOAD_CONST               1 ('sys')
                  4 CALL_FUNCTION            1
                  6 STORE_FAST               0 (sys)
                  8 LOAD_CONST               0 (None)
                 10 RETURN_VALUE
    

    生成的字节码具有相同数量的指令,但它们不同。 那么时机呢?

    >>> timeit.timeit(f1)
    0.4096750088112782
    
    >>> timeit.timeit(f2)
    0.474958091968411
    

    事实证明 __import__ 此外,它的可读性远不如经典 import 陈述

    进口 .


    现在我们来解释一下。。。

    我想是打电话 __导入__ 进口

    __导入__ 就像任何其他函数调用一样 CALL_FUNCTION 指示 另一方面 报表结果为 IMPORT_NAME 指令,它看起来就像是专门用于导入的东西,并且可能由解释器以优化的方式执行。

    所以这两个函数的区别在于 导入名称 CALL_函数