Question about using from/import from with a class

J

John Taylor

I have a class that has this code in it:

def __init__(self,Site):
self.Site = Site
import_cmd = "from regexpr_%d import *" % ( int(self.Site.id) )
exec( import_cmd )
print AGENT # fails, NameError: global name 'AGENT' is not defined


The regexpr_1.py file, for example, has the line:
AGENT="Mozilla"

After the exec() command is ran, how to I access varaibles defined in
the regexpr_%d file?

Thanks,
John
 
J

John Lenton

I have a class that has this code in it:

def __init__(self,Site):
self.Site = Site
import_cmd = "from regexpr_%d import *" % ( int(self.Site.id) )
exec( import_cmd )
print AGENT # fails, NameError: global name 'AGENT' is not defined

The regexpr_1.py file, for example, has the line:
AGENT="Mozilla"

After the exec() command is ran, how to I access varaibles defined in
the regexpr_%d file?

don't do it this way. Try this instead:

regexpr = __import__('regexpr_%d' % int(self.Site.id))
print regexpr.AGENT
 
J

John Lenton

I have a class that has this code in it:

def __init__(self,Site):
self.Site = Site
import_cmd = "from regexpr_%d import *" % ( int(self.Site.id) )
exec( import_cmd )
print AGENT # fails, NameError: global name 'AGENT' is not defined

The regexpr_1.py file, for example, has the line:
AGENT="Mozilla"

After the exec() command is ran, how to I access varaibles defined in
the regexpr_%d file?

don't do it this way. Try this instead:

regexpr = __import__('regexpr_%d' % int(self.Site.id))
print regexpr.AGENT
 
J

John Lenton

I have a class that has this code in it:

def __init__(self,Site):
self.Site = Site
import_cmd = "from regexpr_%d import *" % ( int(self.Site.id) )
exec( import_cmd )
print AGENT # fails, NameError: global name 'AGENT' is not defined

The regexpr_1.py file, for example, has the line:
AGENT="Mozilla"

After the exec() command is ran, how to I access varaibles defined in
the regexpr_%d file?

don't do it this way. Try this instead:

regexpr = __import__('regexpr_%d' % int(self.Site.id))
print regexpr.AGENT
 
P

Peter Otten

John said:
I have a class that has this code in it:

def __init__(self,Site):
self.Site = Site
import_cmd = "from regexpr_%d import *" % ( int(self.Site.id) )
exec( import_cmd )
print AGENT # fails, NameError: global name 'AGENT' is not defined


The regexpr_1.py file, for example, has the line:
AGENT="Mozilla"

It may be bad style but it _does_ work here. I would verify that

[faked:]
'Mozilla'

in the interpreter doesn't also raise the NameError. If so, check
int(self.Site.id).

Peter
 

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

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top