by pansa2 · 5y ago · 0 comments
- The `AstNode` abstract base class becomes completely unnecessary and can be deleted.
- We can't use `@dataclass` and are forced to write an `__init__` method for each class. But this is good, right? "Explicit is better than implicit"?
- It's then clear that our three classes each have two methods, one of which is __init__. Following the advice from "Stop Writing Classes" [0], each class should just be a function (in this case, a generator).
These changes reduce the code above "AST representation of the Ruby statement" from 70 lines to 40, and simplify some of those lines as well - for example, `arg_reprs = (arg.representations() for arg in self.args or [])` becomes simply `arg_reprs = args`.
The knock-on effects of type annotations seem to be doubling the complexity of the code. This is why I'm far from convinced that static type checking in Python is worth the cost.
I don't think that applies. @dataclass is an explicit wrapper with specific result and can be inspected and interacted with.
Implicit would be something like "when a class has more than one attribute and doesn't define init or repr, add those methods assuming they're wanted/needed".
> The `AstNode` abstract base class becomes completely unnecessary and can be deleted.
You're mixing type annotations with class usage. You can have either one without the other.
For example without AstNode you could still have an `Expr|MethodCall|Lambda` type hint on relevant variables. Or even alias that expression to AstNode without having the class and inheritance.
Finally, classes help describe/construct the structure present in "stmt". Sure, you could replace those with functions, but that means your data is either reduced to untyped / string-tagged lists/dicts, or you're running the exact function immediately inline. It doesn't matter for this toy example, but it would in any practical use of this code.
To me, it's a great application of "explicit is better than implicit." Because @dataclass explicitly indicates that this class has a certain set of behavior, and is meant to be used a certain way. If you manually implement exactly the same behavior, you've made the individual statements more explicit, but you've made the class's actual function implicit. A reader needs to figure it out by reading the code and working backward from there. An editor of the code needs to recognize the intended behavior and not break it, otherwise the understanding that other people built up by reading the code may break in subtle ways.
Expr = Callable[[str]], Callable[..., Iterable[str]]]
AstNode = Expr | Callable[... ], Callable[..., Iterable[str]]]
You then don't event need to call representation() , as each node is callable. No classes needed.But my instinct tells me a node will eventually have more attributes and methods. Stuff to get parents, children, siblings, filtering and so on.
So it's probably a good call to use a class for later. Also you want to keep AstNode as a node could be an expression, a statement or a comment.
I couldn't agree more with Jack Diederich's thoughts on that sentiment, at 5:40 in the video linked above:
https://youtu.be/o9pEzgHorH0?t=340
> Lots of times people think they might need something later. You don't. Or, you can just do it later.
Experience helps with this.
It's a middle path as usual: naive approaches waste as much time as overenginering.
Maybe this is an indictment of Python as a language, but I think it's a case of not taking anything too literally. YAGNI fetishism is like DRY fetishism all over again.
My sense is that many of us are taught to think in terms of classes and methods instead of data structures and functions, so it's very easy to slip into thinking you need objects in order to manage state, even when that's not the simplest way to do it.
Strictly speaking, though, I think that the only time in Python that you really have no workable alternative to classes is when you also need dynamic dispatch.
* I could have said refactoring, but some people have very specific definitions attached to that word so I use something more general here
It's also worth it in plumbing code, as it tends to be more difficult to test properly and having types will catch a whole class of errors.
The fact that the program at the bottom of the article can be simplified is not an issue of typing, in fact static typing could also be used in your approach without any issue.
If adding types to your existing code cannot be done without creating new types, that’s a sign that your type-system lacks expressiveness.
For instance C# 1 lacked a good and general way to describe types for functions (that is, decoupled from a class).
In later C# revisions this have been greatly improved, making this pain go away, and accepting type-safe function-value parameters as easy as any other parameter.
I’m guessing Python is lagging quite a bit in that regard. That doesn’t mean that type-safety (when done right) isn’t massively useful and worth the effort 200 times over.
Now this is also a very yagni view, and maybe TFAA uses the structure they build for inspection before the final consumption, but their point that the posted script could be half the size and work the same without loss of readability… is compelling.
Said another way, patterns which were once Pythonic are now discouraged by the type system (or, mypy I suppose, since the door is still open for other type checkers to emerge). Examples:
- Duck typing. I was taught that's Pythonic, yet mypy really only accepts nominal subtyping i.e. it infers type compatibility from the type hierarchy. There is typing.Protocol, but I've never encountered that in code. Ruby's new type annotation language RBS introduces interfaces, so maybe it'll stay true to its duck typing roots.
- Lists with mixed types. I might as well bookmark this page, because this behavior of mypy always surprises me: https://mypy.readthedocs.io/en/stable/common_issues.html#inv...
In both cases, mypy reminds me way more of Java's type system than of Python's, which is maybe why heavily typed Python code often ends up looking like Java.
There are several typecheckers, and while they are at slightly different points, they evolving together and together with the core typing library.
> Duck typing. I was taught that's Pythonic, yet mypy really only accepts nominal subtyping i.e. it infers type compatibility from the type hierarchy. There is typing.Protocol
Which entirely undercuts “mypy only accepts...”
> but I've never encountered that in code.
That's a library author issue, not a mypy (or typing, the standard library) issue.
> In both cases, mypy reminds me way more of Java's type system than of Python's
Python’s type system has always supported both nominal and structural subtyping.
> heavily typed Python code often ends up looking like Java.
That's probably because Java (and languages with closely related type systems) are the typed languages most people writing typed Python have prior experience with, so it's where their typing instincts go.
This is very different from the useless "you don't need classes" classes.
Think of classes nowadays serving as being both traditional OO classes and Scala case classes: they can be types of stateful objects, or just dumb record types, which you now can easily extend with logic if you do happen to need it (and you often do, in nontrivial applications).
Now this is also a very yagni view, and maybe TFAA uses the structure they build for inspection before the final consumption, but their point that the posted script could be half the size and work the same without loss of readability… is compelling.
I find this "it would be half as long and work the same" argument totally bizarre. Do you look at a basic Rust program and say "it would be half as messy and look the same if we did away with all the move/borrow stuff"?
Of course not. Yes, YAGNI is fine and all, but at least recognize that there is an upside to this tradeoff. I am not going to need internal state on the object, but I sure as hell am going to want the type checking.
And yes, you could (perhaps should) use Typescript or Kotlin for new web server projects instead. But some people want Python with types, including me.
I wouldn't accuse Python of being "concise" in the first place, so I am happy to add some up-front verbosity in exchange for a much smoother developer experience later in my project, with significantly less mental overhead as my IDE can do a lot of work for me.
1: https://www.attrs.org/en/stable/
2: https://docs.python.org/3/library/typing.html#typing.TypedDi...
3: https://docs.python.org/3/library/collections.html#collectio... and https://docs.python.org/3/library/typing.html#typing.NamedTu...
That is not even remotely what is being done here. And just because you can do it doesn't mean you should or must do it. Not every argument needs to be bundled in its own object.
> I find this "it would be half as long and work the same" argument totally bizarre. Do you look at a basic Rust program and say "it would be half as messy and look the same if we did away with all the move/borrow stuff"?
Again, missing the point. The point was not about the typechecking but the design perspective it engenders and encourages.
> Of course not. Yes, YAGNI is fine and all, but at least recognize that there is an upside to this tradeoff.
Why would I? There is none in the article's snippet.
> I am not going to need internal state on the object, but I sure as hell am going to want the type checking.
Type checking doesn't require classes. You can typecheck a funtion.
> I wouldn't accuse Python of being "concise" in the first place, so I am happy to add some up-front verbosity in exchange for a much smoother developer experience later in my project, with significantly less mental overhead as my IDE can do a lot of work for me.
You're still missing the point entirely, but I hope you're happy about all those strawmen you beat down.
But...TypedDicts and NamedTuples are classes (that is, the thing returned from those callable is a class and can be subclassed or have methods added just like any other class), so it's kind of odd to say you are using classes instead of...classes.
The point is to stop passing around dicts/hashmaps/tables and tuples, and to start passing around containers with a known and fixed set of keys/names, and known types for the values/elements.
I don't know of any language where the compiler automatically infers field names and types, and I don't know if I would ever want such a thing.
I haven't actually tried interfacing them, it's next on my docket. Have you found any good learning resources for that?
A good test as an example: https://github.com/yglukhov/nimpy/blob/master/tests/tpyfromn...
I've tried it and it works fine. The only problem I ever had was trying to call a specific Python function at the same time from multiple Nim threads. I'm not sure where the fault lay exactly, I just made that part of the code single-threaded and moved on.