faif / python-patterns

A collection of design patterns/idioms in Python
40.21k stars 6.93k forks source link

[question] does prototype pattern have necessary to be exist in python patterns? #324

Closed zhengtong0898 closed 3 years ago

zhengtong0898 commented 4 years ago

i can use copy.deepcopy() to copy a object in python,

does prototype pattern have necessary to be exist in python patterns?

gyermolenko commented 4 years ago

I agree. copy.deepcopy works for arbitrary objects and custom classes. And if we would want to customise that - we can define __deepcopy__ method (or .clone() just to make it as GoF describes)

Also couple of interesting thoughts here: https://python-patterns.guide/gang-of-four/prototype/#the-prototype-pattern

faif commented 4 years ago

I also agree. Feel free to add a pull request that replaces the current code with a deepcopy example

crypdick commented 4 years ago

@faif in any case, shouldn't the existing example be using copy.deepcopy() in the clone method?

faif commented 4 years ago

@crypdick If there are no behaviour differences yes

yhay81 commented 3 years ago

I think prototype.py is wrong. This should work but Got nothing from last line instead of a-category.

def main():
    """
    >>> prototype = Prototype()
    >>> a = prototype.clone(value='a-value', category='a-category')
    >>> b_from_a = a.clone(value='b-value')
    >>> getattr(a, 'category', None)
    a-category
    >>> getattr(b_from_a, 'category', None)
    a-category
    """

This example does not copy any attributes. Even value is not copied because it is always from hard-cording default. I think the core of prototype pattern is that user can dynamically create various prototype.

And, just copy.deepcopy() is not okay with prototype pattern because it just copy and we are not always able to update attributes when we copy it.

yhay81 commented 3 years ago

I think the pythonic way to do what prototype pattern really wanted to do is use types and create class dinamically. https://docs.python.org/ja/3/library/types.html