• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 355
  • Last Modified:

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 ?
0
mannsi
Asked:
mannsi
1 Solution
 
nordtorpCommented:
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.
0
 
mannsiAuthor Commented:
I get the following error:
AttributeError: 'module' object has no attribute 'document_type'
0
 
Hamed ZaghaghiCommented:
Hi
There is no need for IFs.
# classes is defined here
class Book:
    pass
class Magazine:
    pass
class Essay:
    pass
# 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

0
 
Kusala WijayasenaSoftware EngineerCommented:
Using "globals()" inbuilt function you can easily do this

documents  = globals()[document_type]()


-Kusala
0
 
mannsiAuthor Commented:
I am very happy with your answers.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now