tags:

views:

88

answers:

4

Let's say I have this :

class whatever(object):
   def __init__(self):
      pass

and this function:

def create_object(type_name):
   # create an object of type_name

I'd like to be able to call the create_object like this:

inst = create_object(whatever)

and get back an instance of whatever. I think this should be doable without using eval, I'd like to know how to do this. Please notice that I'm NOT using a string as a parameter for create_object.

+6  A: 

The most obvious way:

def create_object(type_name):
    return type_name()
ebo
It didn't cross my mind that `type_name` is callable.
Geo
Classes are just normal first-class objects in Python, sharing the same namespace as any other variables.
bobince
+2  A: 

If I understand correctly, what you want is:

def create_object(type_name, *args):
    # create an object of type_name
    return type_name(*args)

inst = create_object(whatever)

I don't really know why you want to do this, but would be interesting to hear from you what are your reasons to need such a construct.

voyager
Just wanted to know if it could be done without eval :)
Geo
Yes :)
voyager
`eval` and its uglier, meanier brother, `exec` are rarely needed, if at all. `eval` is usefull to evaluate user input, as long as you take measures to not use the appliaction `globals` and `locals`.
voyager
+2  A: 
def create_object(type_name):
   return type_name()

you can of course skip the function altogether and create the instance of whatever like this:

inst = whatever()
SilentGhost
+4  A: 
def create_object(typeobject):
  return typeobject()

As you so explicitly say that the arg to create_object is NOT meant to be a string, I assume it's meant to be the type object itself, just like in the create_object(whatever) example you give, in which whatever is indeed the type itself.

Alex Martelli