In Python 3.6+, there are two new ways of annotating fields for complex objects: using class attributes, like so:
class Foo: field1: int field2: List[str] def __init__(self, arg: Bar) -> None: # Complex setup logic here
...or by annotating instance variables inside
__init__, like so:
class Foo: def __init__(self, arg: Bar) -> None: self.field1: int self.field2: List[str] # Complex setup logic here
Is there any sort of official ruling on which version is considered more Pythonic? I know I prefer the second version because it seems conceptually cleaner, but the first version does look more aesthetically pleasing.
x = None # type: int)
__init__and other methods. I also think that with PEP 526 this will be the future (also with things like class-based NamedTuple declarations and possibly https://github.com/ericvsmith/dataclasses).
class Point(NamedTuple('Point', [('x', float), ('y', float)])): def __add__(self, other: Point) -> Point: # E: error: Argument 1 of "__add__" incompatible with supertype "tuple" return Point(self.x + other.x, self.y + other.y)
NamedTupleis a subclass of
(1, 2) + (3, 4)is a pre-defined operation in python. I think it's unfortunate because deriving things like
namedtupleis a perfect idiom in non-typed python code; so it's sad to lose that idiom in typed python.
NamedTupleright? Maybe it's worth including in the tutorial at some point? It's kinda a nice pattern.
Point(1, 1) + SomethingElseInheritedFromTuple(1, 2), not caught at compile time. Now that it actually happened, I strengthened my opinion on that, and I no longer think using
def __add__(self, other: object)is an acceptable solution. The only solution I personally find acceptable is to not derive from
tuple, and just manually implement
__repr__, etc in my own generic class
MyTuplethat does not define
+and derive my
Point/etc. from that class. (Well, I could wrap a
MyTupleand forward the useful methods but not the ones I don't want. So I do get some code reuse.)
+meaning concatenation is reasonable. It's just an unfortunate reality for cases where
+needs to be pointwise.