TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Bringing macros to Python by abusing type annotations

75 pointsby jxubalmost 7 years ago

8 comments

1st1almost 7 years ago
In Python 4.0 (the one after 3.9), and in Python 3.7 now with "from __future__ import annotations", annotations are parsed but their interpolation is delayed. So you can literally have "var: 0 < var < 3" (annotation is not a string!) in your code and make it work as you wish.
评论 #17800476 未加载
评论 #17800533 未加载
marmadukealmost 7 years ago
Most of these use cases are idiomatically handled by data descriptors and/or metaclasses, though the typing could reduce boilerplate.
评论 #17799480 未加载
Animatsalmost 7 years ago
Unchecked type &quot;annotation&quot; was one of the worst features ever added to a reasonably popular programming language. Python did OK without type declarations. Optional type declarations could help with checking, documentation, and optimization. What went in is the worst of both worlds. Type annotations don&#x27;t do much, and they might be wrong.<p>Now this. Ugh. This is abusing an internal feature of one implementation.
ben509almost 7 years ago
I&#x27;ve been experimenting with annotations to chain a set of functions together using a common namespace. In a nutshell,<p><pre><code> ns.register(foo: int, bar: int) @ns def add_one(foo : ns.foo) -&gt; ns.bar: return foo + 1 </code></pre> It gets a good bit more complicated than this, but when you&#x27;ve got a whole mess of functions to chain together, this lets you do it _reasonably_ sanely and figure out the ordering.<p>I think it should be possible to be compatible with a type checker like mypy as it could reannotate the decorated function with the types looked up from the namespace, but I haven&#x27;t tested that.
kryptnalmost 7 years ago
I did something similar to the ending of this post, where the realization sets in that annotations are just expressions. I wanted to force the method&#x27;s annotated parameters and return type before entering and exiting the method.<p><a href="https:&#x2F;&#x2F;gist.github.com&#x2F;kryptn&#x2F;2f91fdd9f4c5b2a272472d5e1a5afc5e" rel="nofollow">https:&#x2F;&#x2F;gist.github.com&#x2F;kryptn&#x2F;2f91fdd9f4c5b2a272472d5e1a5af...</a>
boromialmost 7 years ago
This is one area where Julia truly excels and Python falls short
BerislavLopacalmost 7 years ago
An honest question: what are really the benefits of having macros in an interpreted language like Python?
Animatsalmost 7 years ago
Will this work with non-Guido implementations?