faif / python-patterns

A collection of design patterns/idioms in Python

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

zhengtong0898 opened this issue · comments

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

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

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

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

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

@crypdick If there are no behaviour differences yes

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.

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