MagicTheGathering / mtg-sdk-python

Magic: The Gathering SDK - Python
MIT License
255 stars 45 forks source link

What are the advantages of using `__new__` instead of `__init__`? #21

Closed 0x326 closed 5 years ago

0x326 commented 5 years ago

I noticed in #15 that we changed from __init__ to __new__ in classes like Card and Set. I was wondering what the advantage of this is? It seems like __init__ offers more utility over __new__, since IDEs can suggest class members and, with Python 3.6 type annotations, could even infer their type (see below)

class Card:
    def __init__(self, response_dict=None):
        if response_dict is None:
            response_dict = {}
        self.name: str = response_dict.get('name')
        self.cmc: int = response_dict.get('cmc')
        # ...
0x326 commented 5 years ago

Or, if you wanted to use a native type, you could do something like this:

from typing import NamedTuple

class Card(NamedTuple):
    name: str
    cmc: int

    # Optional functions here...

# Later...
card = Card(**response_dict)
adback03 commented 5 years ago

Feel free to make a PR with the changes if init is the preferred way. I'm not a huge python guy, so I personally can't speak to the benefits of one over the other :)