When importing modules in python, is there a memory difference when you import a single module from a package eg: from math import ceil vs the whole package eg: import math? I guess what I am really asking is whether or not it slows processing down when the script is run?
1 Answer
There is no difference between those. Raymond Hettinger, one of the core Python developers, recently tweeted this:
#python tip: from-imports don't save memory. They execute and cache the entire module just like a regular import.
-
7
-
15@ajsp so that you do not have to access things as -
module.name
? Jul 29, 2015 at 5:08
__init__.py
is configured ... but, python imports are generally fast and the memory footprint is generally small (unless you have some module level intense processing going on). It's probably not really worth worrying about unless you have some really stringent hardware constraints...import math
oros
in multiple files it will lead to code duplication and if will expose so many functions that you don't even know or you don't even want to import. Thus it is a good habit to usefrom os import path
instead ofimport os
.from x import y
just promotes y to the current lexical scope; that is, whether you have to call it smath.sin()
or justsin()
. It otherwise has no effect at all on code duplication or even imported code. Thus,from math import sin
still importsmath.cos()
,math.log()
and all the rest.sin()
function to be called many a times we should opt forfrom math import sin
. Just thinking should we treat this as a feature or a bug?math.sin
takes two dictionary lookups instead of one, however if the top-level namespace becomes very full you'll probably lose that tiny gain in looking through a much larger namespace. But this is Python, so nano-performance ought not be a priority. If I am writing a trigonometry heavy program thenfrom math import *
may well make my code easier to read. In general though,module.object
or evenmodule.submodule.object
is easier on the reader and that's what counts.