0

I need to create a new instance of a specific class named from the content of a variable.

For example create an instance of the Foo class named whatever the content of the "s" variable is. This is what I tried

class Foo:
    pass
s = 'bar'
eval(s) = Foo

The above code returns a "can't assign to function call" error.

I need it to create an instance called 'bar' in the Foo class in this case but I also need to be able to change the 's' variable to any string and for it to still work.

If there is another way for me to create class instances and then access them later with the "s" variable that would work too.

A lot of similar questions have been answered by creating pre defined dictionaries but in my case these dictionaries would have to be several hundred items long and hand written, and so are impractical and not very pythonian. I need to create and access the instance completely dynamically, hopefully by name but if there is another way I'm open to that too.

  • May I ask what is it you're trying to solve with this? – Reut Sharabani Jul 18 '16 at 22:16
  • You can assign to `globals` if it is in the global namespace (`globals()['bar'] = Foo`). However, you generally _shouldn't_ do this. When programming, it's almost always best to know what names you're working with ahead of time. Have a look at this [excellent article](http://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html) by Ned Batchelder. – mgilson Jul 18 '16 at 22:16
  • Using a dictionary is the pythonic approach to what you are trying to accomplish. What do you mean "hand written?"All that is necessary is `my_dict['s'] = Foo()` – juanpa.arrivillaga Jul 18 '16 at 22:17
  • StefanW seems to have answered this here: http://stackoverflow.com/questions/19122345/to-convert-string-to-variable-name-in-python – VortixDev Jul 18 '16 at 22:18
  • 1
    Possible duplicate of [How can you dynamically create variables in Python via a while loop?](http://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables-in-python-via-a-while-loop) – Dimitris Fasarakis Hilliard Jul 18 '16 at 23:12

1 Answers1

0

This should do it.

def make_class(name):
    class_text = """
global {} # Makes the class object global.
class {}: # You put the class here.
    pass
""".format(name, name) # Formats the text. There are a couple different ways to do this.
    exec(class_text)

Example:

>>> make_class("Foo")
>>> make_class("Bar")
>>> Foo()
<__main__.Foo object at 0x7fedebcda748>
>>> Bar()
<__main__.Bar object at 0x7fedebcda8d0>
Pugduddly
  • 1
  • 2