DEV Community

Discussion on: How Specific Are you With Your Imports and Why?

Collapse
 
rhymes profile image
rhymes

I'm not sure about "security reasons" (?) but there is a difference, albeit an insignificant one unless you are in a loop.

This is what happens at the moment of the import statement:

python import statement

The only case where performance might actually matter is if you loop a lot of times and call a function inside another method. Taking from this answer - stackoverflow.com/a/33642848/4186181 - I ran the two example functions on Python 3.6.6 and I get these timings:

In [2]: %timeit tight_loop_slow(10000000)
2.14 s ± 33.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [3]: %timeit tight_loop_fast(10000000)
1.63 s ± 43.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

So yeah, if you're looping a lot consider aliasing the function

Collapse
 
kaelscion profile image
kaelscion

So there is a performance benefit after all? That is very cool. The difference seems a bit on the academic side in this example, but since most of what I do deals in datasets that seem to get larger by the day, an academic difference over few iterations can be an enormous difference over thousands or more!

As far as security goes, I've never really been sure what was meant by that either. I was at a coding meetup in Portland, ME where I live and some other developers were talking about it. They used different languages than I did, mostly C, C++, and Java, and seemed to reference the fact that importing things you didn't need would leave those modules unintentionally usable from within the code that imported but didn't use them. I've never been all that low level and, though I have worked in a C-derivative language (C#) it was very early on in my career and only for about a year so I never got that deep with it. Either way, thanks for pointing out those docs! It really makes me think about what I am actually doing with imports that I take for granted so much at this point.

Collapse
 
rhymes profile image
rhymes

mostly C, C++, and Java, and seemed to reference the fact that importing things you didn't need would leave those modules unintentionally usable from within the code that imported but didn't use them

Ok got it. I'm not sure that's applicable to Python because you bring the runtime with you when you deploy the app and because you can import modules at runtime which means you can execute anything in the standard library and libraries packaged with the app. It also depends on what kind of security we're talking about but I'm not a real expert on the subject...