Instantiating an object when the type is only known at runtime

S

Samuel

Hi,

I am trying to replace the eval() in the following code:

def myfunc(type, table):
module = __import__(type)
type = 'module' + '.' + type
obj = eval(type)
return obj(row[table.c.name], row[table.c.handle])

I am out of ideas. Any hints?

Thanks,
-Samuel
 
R

Rob Williscroft

Samuel wrote in
in comp.lang.python:
Hi,

I am trying to replace the eval() in the following code:

def myfunc(type, table):
module = __import__(type)
type = 'module' + '.' + type
obj = eval(type)
return obj(row[table.c.name], row[table.c.handle])

Rob.
 
T

Terry Reedy

Samuel said:
Hi,

I am trying to replace the eval() in the following code:

def myfunc(type, table):
module = __import__(type)
type = 'module' + '.' + type
obj = eval(type)
return obj(row[table.c.name], row[table.c.handle])

I am out of ideas. Any hints?

Perhaps what you need is a dict 'types' mapping strings to types/classes.
Then the last two lines might become

return types[type](row[table.c.name], row[table.c.handle])

The trick of mapping names to callables for runtime choice of what to call
has several uses.

Terry Jan Reedy
 
S

Samuel

Thanks, that's what I was looking for.

For the records: If the module is already loaded, this also works:

if my_type_is_not_yet_loaded:
module = __import__(type)
obj = getattr(module, type)
else:
obj = globals().get(type)
resource = obj(my_arg1, my_arg2)

Thanks again,
-Samuel
 
C

Carsten Haese

Thanks, that's what I was looking for.


For the records: If the module is already loaded, this also works:

if my_type_is_not_yet_loaded:
module = __import__(type)
obj = getattr(module, type)
else:
obj = globals().get(type)
resource = obj(my_arg1, my_arg2)

You seem to be under the impression that importing an already imported
module is a hideously expensive operation that must be avoided at all
costs. It's not. If you import an already imported module, python simply
returns the module object from sys.modules without executing any of the
module's code.

Your code will be much easier to read if you eliminate the
"my_type_is_not_yet_loaded" check, whatever that may be under the hood,
and always perform the __import__. It's also likely to be at least as
fast, but I couldn't run a timing comparison even if I wanted to because
you didn't post working code.

-Carsten
 

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,054
Latest member
TrimKetoBoost

Latest Threads

Top