vendredi 12 juillet 2019

How to implement back referencing in python?

I am trying to implement a logic where you can back reference objects. I think an example would make it clear.

class State:
    def __init__(self, name, allowed_transitions=None):
        self.name = name
        self.allowed_transitions = allowed_transitions or []

run = State('Run')
walk = State('Walk', allowed_transitions=[run, 'sprint'])
sprint = State('Sprint', allowed_transitions=[walk])

In above code, run can be referenced in walk state as an object but sprint can not be since it is defined after walk state.

I want to allow support of two types State and str. I could convert or transform a name given as a string to a State object inside the State constructor but does not seem elegant solution.

Similar things is supported in Django framework where you could back reference the model class name using string. I want to achieve similar functionality.

author = ForeignKey('Person')

What is the best way to handle this use-case ?

Aucun commentaire:

Enregistrer un commentaire