Ask coding questions

← Back to all posts
Creating an object contained within a string in python
Dunce (50)

Okay, so if I had a string set to "<class 'Some_class'>" and I wanted to create the object contained within the string (in this case Some_class), what would I do? here's an example of what I'm talking about:

input:

string = "<class 'Some_class'>"
some_class_instance = string()

output:
Traceback (most recent call last):
File "main.py", line 6, in <module>
some_class_instance = string()
TypeError: 'str' object is not callable

to be clear, string = "<class 'Some_class'>" is the same as string = str(Some_class)

Answered by SixBeeps (5067) [earned 5 cycles]
View Answer
Comments
hotnewtop
SixBeeps (5067)

This is simply impossible. If you want to store instances of a class within a string, you'll have to use JSON.

Dunce (50)

@SixBeeps Thank you! The reason I wanted to do this in the first place was so I could store it in JSON, I just couldn't figure out how to do it correctly.

Coder100 (17122)

Yeah sure, like this:

class_dict = {
  "<class 'Some_class'>": Some_class
}

class Some_class: pass

what = "<class 'Some_class'>"
string = class_dict[what]()

so easy

Dunce (50)

@Coder100 Thanks allot, but I literally just saw SixBeep's response.