Import if condition is correct

G

Georg Brandl

MindClass said:
Is possible import a library according to a condition?

if Foo = True:
import bar

Why don't you try it?

(in the above code, not the import is the problem, but using the
assignment operator in an expression)

Georg
 
M

MindClass

Georg said:
Why don't you try it?
I thinked that could be another way for import statement.

In that case I'll have to set a global variable before of the import
statements although I'd prefer not use them.
 
S

Steve Holden

MindClass said:
I thinked that could be another way for import statement.

In that case I'll have to set a global variable before of the import
statements although I'd prefer not use them.

I'm guessing that you think this might be necessary to avoid importing
the same module multiple times: it's not. Python only runs the module's
code the first time the module is imported into a program. A further
import statement effectively does noting, because the interpreter sees
(from an entry in the sys.modules dictionary) that the module is already
present.

regards
Steve
 
M

MindClass

Steve said:
I'm guessing that you think this might be necessary to avoid importing
the same module multiple times: it's not. Python only runs the module's
code the first time the module is imported into a program. A further
import statement effectively does noting, because the interpreter sees
(from an entry in the sys.modules dictionary) that the module is already
present.
The problem is that I've to import different libraries according to the
ORM (SQLObject, SQLAlchemy, etc)
 
S

Steve Holden

MindClass said:
The problem is that I've to import different libraries according to the
ORM (SQLObject, SQLAlchemy, etc)
So why the need for global variables?

if MySQL_wanted:
import MySQLdb as db
elif sqlite_wanted:
import pysqlite as db
else:
import psycopg2 as db

conn = db.connect(...)
....

regards
Steve
 
B

Bruno Desthuilliers

MindClass said:
Is possible import a library according to a condition?

if Foo = True:
import bar
Did you even try ? Would have been faster than posting here...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top