design-patterns-python icon indicating copy to clipboard operation
design-patterns-python copied to clipboard

Restricted _state - Memento Design Pattern in Python

Open JuanPabloArbelaez opened this issue 4 years ago • 1 comments

Hello.

I am learning design patterns through the implementations in Python.

The Memento design pattern is supposed to restore previous states, while keeping the information about them, restricted to other objects.

However when implementing the code, I was able to get access to all the restricted states:

if __name__ == "__main__":
    originator = Originator("Super-duper-super-puper-super.")
    caretaker = Caretaker(originator)

    caretaker.backup()
    originator.do_something()
    
    ### this should not work in theory
    for m in caretaker._mementos:
          print(f"_state = {m.get_state()}")  

as seen in the for loop:

I can print all the values of the previous states.

_state = Super-duper-super-puper-super.
_state = kTjoIhPwiBmqvJfuDENWZXKcdUMHtp

is there a way to actually hide these states in Python?

Thanks for your work teaching design patterns. I hope you can guide me on this subject.

JuanPabloArbelaez avatar Jan 18 '21 13:01 JuanPabloArbelaez

No, Python doesn't have anything "strictly" restricted. The leading underscore is only an indication that the variable is an implementation detail and should not be used or changed. In Python everything is accessible.

JakubDotPy avatar Sep 08 '23 11:09 JakubDotPy