Dynamic Python Syntax

Hello experts,

I am not sure if I it is possible to do what I want to do. Consider the following two lines.

document_type = 'Book'
documents = bookModel.document_type.objects.all()

document_type can be 'Book', 'Magazine', 'Essay' etc.
I don't want to have to write an if sentence for each type like this :
if document_type == 'Book':
    documents = bookModel.Book.objects.all()

Can I somehow make it work like the first two lines of code ?
Who is Participating?
Hamed ZaghaghiConnect With a Mentor ProgrammerCommented:
There is no need for IFs.
# classes is defined here
class Book:
class Magazine:
class Essay:
# this is a factory class that creates instances
class factory:
    def __getitem__(cls, name):
        return globals()[name]

# then you can use factory class to create objects e.g.
document_type = 'Book'
f = factory()
abook = f[document_type]

Open in new window

Why can't you use the lines you typed?

document_type = 'Book'
documents = bookModel.document_type.objects.all()

Just set documents after you have set the document_type. Or are there any errors with it?

I would guess you set the document_type somewhere after you have found out which type it is.
mannsiAuthor Commented:
I get the following error:
AttributeError: 'module' object has no attribute 'document_type'
Kusala WijayasenaSoftware EngineerCommented:
Using "globals()" inbuilt function you can easily do this

documents  = globals()[document_type]()

mannsiAuthor Commented:
I am very happy with your answers.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.