Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make import conditionally in Python? [duplicate]

I want to do something like this in C:

#ifdef SOMETHING
do_this();
#endif

But in Python this doesn't jive:

if something:
    import module

What am I doing wrong? Is this possible in the first place?

like image 468
foo Avatar asked Mar 17 '26 12:03

foo


2 Answers

It should work fine:

>>> if False:
...     import sys
... 
>>> sys
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sys' is not defined
>>> if True:
...     import sys
... 
>>> sys
<module 'sys' (built-in)>
like image 66
Pär Wieslander Avatar answered Mar 19 '26 01:03

Pär Wieslander


If you're getting this:

NameError: name 'something' is not defined

then the problem here is not with the import statement but with the use of something, a variable you apparently haven't initialized. Just make sure it's initialized to either True or False, and it'll work.

like image 42
Jason Orendorff Avatar answered Mar 19 '26 00:03

Jason Orendorff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!