407 points · by ingve · 8y ago · 158 comments
One of the prime uses of a dataclass is to be a mutable namedtuple. And the syntax can be almost identical:
Part = make_dataclass('Part', ['part_num', 'description', 'quantity'])
(from Raymond Hettinger's twitter)This has the added benefit of not requiring type hinting, if you don't want to bother with such things.
(attrs) % ipython
Python 2.7.14 (default, Oct 19 2017, 23:28:49)
Type "copyright", "credits" or "license" for more information.
IPython 5.6.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: import attr
In [2]: Part = attr.make_class("Part", ["part_num", "description", "quantity"])
In [3]: Part?
Init signature: Part(self, part_num, description, quantity)
Docstring: <no docstring>
Type: type
Outside of the name of the thing that creates the item, the syntax is identical to what you have here.edit: removed triple backticks, indented with 2sp according to https://news.ycombinator.com/formatdoc rules
It cuts down on the per-instance memory overhead, for cases where you're creating a ton of these objects. It can be useful even when not memory-constrained, because it will throw AttributeError, rather than succeeding silently, if you make a typo when assigning to an object attribute.
0: https://www.python.org/dev/peps/pep-0557/#support-for-automa...
[0] https://www.reddit.com/r/Python/comments/7tnbny/raymond_hett...
This is what I'd prefer
from dataclasses import dataclass, field
@dataclass
class MyClass:
x = field()
but it produces an error because fields need to be declared with a type annotation. This is the GvR recommended way to get around it: @dataclass
class MyClass:
x: object
You could use the typing.Any type instead of object, but then you need to import a whole typing library to use untyped dataclasses. I highly prefer the former code block.There's a big thread discussing the issue on python-dev somewhere. Also some discussion in https://github.com/ericvsmith/dataclasses/issues/2#issuecomm...
Anyway, it's not a huge issue—attrs is great and there's no reason not to use it instead for untyped Python.
[1] https://stackoverflow.com/questions/47350570/is-it-possible-...
from typing import NamedTuple
class Foo(NamedTuple):
bar: str
baz: int
and this for DataClasses: @dataclass
class Foo:
bar: str
baz: int class Person(typing.NamedTuple):
name: str
age: int
But I don't think it supports the __post_init__; however, constructors have no business doing parsing like this anyway, so unless I'm missing something, deriving from `typing.NamedTuple` seems strictly better than `@dataclass` insofar as it seems less likely to be abused.There are uses cases for mutability, but it should be opt-in, not opt-out. So I'm not loving the fact that "frozen" (the mutability param for data classes) defaults to False.
>>> class Foo:
... def bar(self):
... print('foo')
...
>>> class Baz:
... def bar(self):
... print('baz')
...
>>> f = Foo()
>>> f
<__main__.Foo object at 0x7fa311e7a278>
>>> f.bar()
foo
>>> f.__class__ = Baz
>>> f
<__main__.Baz object at 0x7fa311e7a278>
>>> f.bar()
bazIs this like an unsafe pointer cast where “you are responsible, and it will likely blow up spectacularly if you don’t know what you are doing” or is it something safer that will magically work e.g with types of different size?
- Does that work even if the types had fields? Yup!
- What about it the fields had a different total size? Totally fine!
- What if Baz had no parameterless constructor (I.e only had a contractor that guaranteed arg > 0 for example)? Then you throw an exception when you call the constructor.
- Is this like an unsafe pointer cast where “you are responsible, and it will likely blow up spectacularly if you don’t know what you are doing” or is it something safer that will magically work e.g with types of different size?
Mostly the former, but if you're coming from a strongly typed compiled language, it may feel like a bit of the latter too, since if you don't run into any obvious runtime incompatibilities, it'll all "just seem to work" even if the underlying classes are 200% different.
(Disclaimer, I've been using python for ~decade now but am still always nervous to speak authoritatively about it, since I work with peers who are FAR deeper in the actual implementation than I am, and I run the risk of being subtlety incorrect.)
As with most things, there are trade-offs.
I wouldn't qualify this as an advantage; it encourages bad code and it precludes a lot of good tooling (including tooling which would automate the sort of refactoring you'd like to avoid).
That's a matter of opinion, not a fact. It can be thought of as a shortcut for an applied mixin, without the needless pollution and boilerplate.
Yeah, I've just moved from a Python thing to doing some modern JS (async/await etc.), and they feel like cousins. To my surprise, I find that I like the comparative minimalism of JS: it has most of the key features of Python, but doesn't feel like it has the same cognitive load.
C++11 though is quite a bit different. Probably the biggest change being that raw pointers * for the most part should not be used anymore.
Static languages such as Go and C already essentially let you do this through initialization through braces.
created: datetime
But if type(self.created) is str:
self.created = dateutil.parser.parse(self.created)
So basically, the type annotation cannot be trusted.I don't know that it should scare you, but, like with many Python features, it's something that should be approached in a sensible manner. The Python philosophy is to leave you with the freedom to monkey around, and leave it to you to decide whether you want to abuse that ability.
(Look at me, all talking like someone who didn't spend 2 hours diagnosing a type error that a static language would have found and forced me to fix within half a second. :P )
I have to imagine that the type checkers would factor in anything that occurs in __post_init__ when evaluating whether the class conforms to the type hints, but it still feels like this python static typing stuff is drifting in the wrong direction.
Arguments accepted in __init__() are not necessarily tied to the so-called "shape of the type" at runtime. Fields with init=False, and the presence of ClassVar and InitVar is just two examples.
In terms of types of arguments passed to __init__(), they totally can be incompatible with the runtime type of the given field. There's nothing wrong with that. On the contrary, that is a useful feature. The obvious example is factories for field defaults. E.g. you can't store a list instance as a default value, it would be reused across your type's instances. Instead, you use default_factory=list. But when you do, what type does the respective argument to __init__ accept? Well, it's Union[YourType, MISSING] because you can omit it and it will initialize your type for you.
Type conversion is another common example. Your __init__ might accept timestamps as strings but always convert them to datetimes. Maybe you accept Unicode strings but internally store as bytes or vice versa? Maybe you support an external API so you have to accept a bunch of arguments that you later convert to a saner internal state? There are numerous use cases.
Summing up, don't confuse the signature of __init__ with the type shape.
@dataclass
class DataObj:
some_date: datetime
def __init__(self, **kw):
kw['some_date'] = dateutil.parser.parse(kw['some_date'])
super().__init__(**kw) dataclass.__init__(self, **kw)
Like in the olden days before super(). @dataclass
class BaseDataObj:
some_date: datetime
class DataObj(BaseDataObj):
def __init__(self, **kw):
kw['some_date'] = dateutil.parser.parse(kw['some_date'])
super().__init__(**kw)Example from the PEP 557:
@dataclass
class C:
a: float
b: float
c: float = field(init=False)
def __post_init__(self):
self.c = self.a + self.b
https://www.python.org/dev/peps/pep-0557/#post-init-processi...I could use this all over the place.
I've tried to elaborate here why annotating variables with type doesn't make a dynamic language static:
https://medium.com/@Jernfrost/dynamically-typed-languages-ar...
You can't look at the presence of type information to determine if a language is static or dynamic. What matters is when and how that type information is used. In static languages expression have type. In dynamic languages values have type.
The implication is that you can't know the type of something in a dynamic language until the expression has been evaluated at run time. With a static language we can determine the type of every expression at compile time, which requires full knowledge of the whole program. It is why dependencies becomes much more problematic in static languages and why they are so poor as glue languages.
I don't think this is true. In a dynamic language all values, including expressions, share a single type - a union of all possible types. In a static language you can limit which possible types a value may hold. A dynamic language is like if you cast every single type to Any in a static language.
In Python this is entirely possible with mypy - a static type system for the Python language, which works through annotations.
> in static languages they are used to prevent the compilation of programs containing expressions where types don’t match up.
This is already the case with mypy in Python. It seems very much static. It's like everything is statically determined to be Any, then you specify in certain areas a more limited type.
In your case with Julia, the type annotations are static. Even if by default Julia is dynamic, it allows for static annotations.
I disagree that there is no in-between. I think Julia is actually a great example of an in-between. And, in fact, it has a name - gradual typing.
No, you're thinking of a weakly- versus strongly-typed language. Python is dynamically and strongly typed - values have a definite type, but a variable can be assigned a value of any type.
https://stackoverflow.com/a/28096079/659248
The notion that dynamic languages are "unityped" comes from looking at them through the lens of static typing, leading to a disconnect about what "type" means and a correspondingly meaningless answer. Since the static notion of type applies to expressions and the dynamic notion of type applies to values, when you ask what the type of an expression in a dynamic language is, you get an useless answer since dynamic languages don't—by their very nature—assign types to expressions. Yes, you can sometimes figure out what the type of an expression must be, but the ability to do so is incidental and not guaranteed by the language, nor an inherent part of its semantics.
The dynamic notion of type belonging to a value distinct from an expressions is present to a limited extent in object-oriented static languages with subtyping: when the static type of an expression and its actual runtime type can be different. The static type corresponds to the static notion of what a type is while the runtime type corresponds to the dynamic notion of what a type is.
And given how mypy works, you can enforce types over only parts of a program.
That, to me, sounds like the python ecosystem is becoming more statically typed.
But you have to have this information anyway, or at least most of it. Even in a dynamically typed language, you have to know what sort of arguments a function expects; otherwise, how can you write any code at all to operate on those values if you don't even know what they are? Static typing just forces you to be more explicit about encoding those constraints. Whether that's worth the tradeoff depends on a lot of factors, but its use as a "glue" language is certainly not one of them.
Edit: Moreover, the line between statically typed and dynamically typed languages isn't as well-defined as you claim. For instance, TypeScript is a statically typed language, but it successfully compiles regular JavaScript code because, by default, every expression is given the type `any`. This means you can start out with dynamic typing and add static types progressively. And at that point, how is that any different than Python with mypy[0]?
Not necessarily...
If the value passed to function implements whatever functionality called then its type doesn't really matter. Really the whole theory behind duck typing.
>>> i = 1 + "1"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
while javascript (apparently) will assign "11" to i.True, but the Smalltalk idea was that you send a message to an object, and that object decides how (or whether) to handle it. So in Ruby, if you send the + method to some kind of number object along with the objects you want added, and the receiving object decides how to perform that addition, assuming the objects you sent can be summed.
> With a static language we can determine the type of every expression at compile time, which requires full knowledge of the whole program.
> Dynamic and static languages are fundamentally different. There is no more or less.
For many Python programs, every expression can be determined statically. While this may not be true for all expressions in all programs, surely this means the OP's claim that "Python is becoming more statically typed" is true and your claim that "There is no more or less" is false, no?
Besides, there are languages like Go which have dynamic types (interface{}) and which are considered statically typed languages. You might say that the static type is interface{}, but then you could say that every type in an un-annotated Python program is also interface{} (or whatever the equivalent Python type would be).
It seems like your arguments hinge on semantic games.
And C# has a var type (dynamic) and Dart has gradual typing.
Because (1) you need to declare the fields, and (2) it's good to do that in a way that will work with typecheckers even though they are external, and (3) there are actually two particular type declarations that are used by the implementation, even aside from external typecheckers.
For example you could set the type to object, typing.Any, ... (Ellipsis), or None, etc.
RHEL/CentOS 6 is still reasonably widely used, and the system Python there is 2.6.
I will never understand why that matters. "ed" is the default system editor, but I'm only "{apt-get,yum} install {vim,emacs}" away from having something I actually want to use. That's the whole point of a distro. You don't have to use Python 2.ancient just because /usr/bin/paleolithic is written with it.
d = {Foo : do_something_with_foo,
Bar : do_something_with_bar}
d.get(type(x), default_function)(x)
Probably some more efficient way but honestly I've used this before instead of writing a whole if elif chain.--edit--
Makes python's lack of a switch operator sometimes less painful...
I guess my uses for dictionaries are pretty vanilla. But that’s a kind of thing I do all the time. I set up dictionaries where the key is a possible value from some operation or query, and the value is the function I want to perform on that value.
This extends that concept. Thanks!
- If the objects are value types (as dataclasses are, since they respect equality): it makes sense to use them as dict keys, just as it makes sense to use tuples as dict keys. Changing a tuple to a namedtuple is natural.
- If the objects have reference semantics rather than value semantics, you can still use them as dict keys in Python. The default __hash__ is the id/address of the object (the default __eq__ uses id() too). I don't particularly like this style but I have seen it used. It feels error-prone to me and not "algebraic".
I've used tuples has dict keys several times, so I don't see why I conceivably wouldn't use a Data Class containing the same data as a dict key.