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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The Python standard library uses it, so it is most definitely proper and safe. See the
osmodule 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
iftest: 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
ifcontrol flow to control the import is no different from assigning a variable in anifstatement in that regard. You need to make sure you don’t end up using the name without it being defined either way.