Do more imported objects affect performance

Steve Holden steve at
Wed Dec 3 04:53:47 CET 2008

Filip Gruszczyński wrote:
[something I moved to after Nick's reply, where it belongs]
> 2008/12/1 Nick Craig-Wood <nick at>:
>> Rafe <rafesacks at> wrote:
>>>  On Dec 1, 7:26?am, "Filip Gruszczy?ski" <grusz... at> wrote:
>>>> I have following question: if I use
>>>> from module import *
>>>> instead
>>>> from module import Class
>>>> am I affecting performance of my program? I believe, that all those
>>>> names must be stored somewhere, when they are imported and then
>>>> browsed when one of them is called. So am I putting a lot of "garbage"
>>>> to this storage and make those searches longer?
>>>  Why use it if you don't need it? Your post implies a choice and the
>>>  '*' import can really make things muddy if it isn't actually necessary
>>>  (rare). Why not just import the module and use what you need? It is
>>>  way easier to read/debug and maintains the name-space.
>> Importing the module is actualy slower...  If you import the name into
>> your namespace then there is only one lookup to do.  If you import the
>> module there are two.
>> $ python -m timeit -s 'from timeit import Timer' 'Timer'
>> 10000000 loops, best of 3: 0.0784 usec per loop
>> $ python -m timeit -s 'import timeit' 'timeit.Timer'
>> 1000000 loops, best of 3: 0.243 usec per loop
>> I'm not suggestion you should ever use "from module import *" only
>> ever import the things you actually need, eg
>> "from module import MyClass, my_function"
>> And here is the test again, actually calling something with the same
>> difference in execution speed :-
>> $ python -m timeit -s 'from os import nice' 'nice(0)'
>> 1000000 loops, best of 3: 1.21 usec per loop
>> $ python -m timeit -s 'import os' 'os.nice(0)'
>> 1000000 loops, best of 3: 1.48 usec per loop
> I see. Thanks for a really good explanation, I like to know, how to do
> things in the proper way :)
Pardon me for intruding, but timings here are entirely the wrong focus
for a Python newcomer. Given that imports are super-optimized (i.e. the
code in the module is only performed once) such a small difference in
timing is inconsequential, I would suggest.

As long as "from module import *" is only ever used with modules
specifically designed to support it, the other forms can be used as
required. Sure, there is a timing difference between

  import module


  from module import something

but that's hardly the point. Learning to write sound Python is *much*
more important that learning to write fast Python, and often the two
coincide anyway.

It was true when Kernighan and Plauger wrote it forty years ago and it's
true now: "First, make it work. Then, *if it doesn't work fast enough*,
make it work faster".

Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC    

More information about the Python-list mailing list