I wrote little wrapper for urllib (python3). Is it proper and safe to import module in if?
if self.response_encoding == 'gzip':
import gzip
I didn't find any PEP about this code. However, it bothers me.
I wrote little wrapper for urllib (python3). Is it proper and safe to import module in if?
if self.response_encoding == 'gzip':
import gzip
I didn't find any PEP about this code. However, it bothers me.
Is it safe? Yes. As Martijin's answer pointed out that Official Python use this.
Is it proper? Depends. Python performance docs points out that even though python can avoid import the same module, there is still overhead.
So i believe you should ask yourself, how often the if statement is true. If very often, then there will be large overhead, and you should import it at the beginning of the file. If not often, then import in if statement is a wise choice.
Sure, that's fine. It can even be necessary in cases where the module has initialization code that you don't always want to run.
This is a reasonably common idiom actually. You'll sometimes see it to pick between different modules:
Then, assuming both
linuxdeps
andwin32deps
have the same functions, you can just use it:This is even used to get
os.path
in the standard library (some of the source code foros
follows):The Python standard library uses it, so it is most definitely proper and safe. See the
os
module source for an excellent example:It's quite common to conditionally import modules in python. Instead of
if
, you'll often see atry:
/except ImportError:
combination too:Here, we basically use the moral equivalent of an
if
test: If you can importcheck_output
, do so, otherwise define the full function here.An import statement is just a re-binding of an external piece of code to a local name. Using an
if
control flow to control the import is no different from assigning a variable in anif
statement in that regard. You need to make sure you don't end up using the name without it being defined either way.