TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Problems once solved by a metaclass can be solved by __init_subclass__

211 点作者 imaurer超过 3 年前

26 条评论

pengwing超过 3 年前
I feel jumping right into __init_subclass__ without explaining why metaclasses exist and what problems they typically solve excludes the majority of devs on HN. Thereby limiting any discussion only to the advanced Python developer echo chamber, while discussion across very different devs is usually far more interesting.
评论 #29812599 未加载
评论 #29819055 未加载
评论 #29813495 未加载
评论 #29819938 未加载
评论 #29817939 未加载
zzzeek超过 3 年前
Yeah this is great, __init_subclass__ comes along to make dynamic injection of methods and attributes on class creation easier, just as the entire practice is fast becoming fully obsolete because type checkers like pylance and mypy report these attributes and methods as errors.
评论 #29813534 未加载
评论 #29813584 未加载
评论 #29812639 未加载
评论 #29813615 未加载
评论 #29813122 未加载
评论 #29814016 未加载
echelon超过 3 年前
I&#x27;m at a point in my career where I see &quot;magic&quot; and wince hard.<p>This is so hard to reason about and fix at scale. If you let other engineers run wild with this and build features with it, the time will eventually come to decom your service and move functionality elsewhere. Having to chase down these rabbits, duplicate magic, and search large code bases without the help of an AST assisted search is slow, painful, and error prone.<p>I spent several years undoing magic method dispatch in Ruby codebases. Tracing through nearly a thousand endpoints to detect blast radiuses of making schema changes impacted by CRUD ops on lazily dispatched &quot;clever code&quot;.<p>I&#x27;m sure there are valid use cases for this, but be exceedingly careful. Boring code is often all you need. It doesn&#x27;t leave a mess for your maintainers you&#x27;ll never meet.<p>Python users tend not to behave this way, but seeing posts like this requires me to urge caution.
评论 #29812520 未加载
评论 #29812123 未加载
chadykamar超过 3 年前
“Metaclasses are deeper magic than 99% of users should ever worry about. If you wonder whether you need them, you don’t (the people who actually need them know with certainty that they need them, and don’t need an explanation about why).”<p>— Tim Peters
评论 #29812574 未加载
lvass超过 3 年前
Am I just bad at OOP hackery or does anyone else look at this and think it&#x27;d be extremely hard to debug?
评论 #29812115 未加载
评论 #29812941 未加载
评论 #29812367 未加载
评论 #29812012 未加载
评论 #29812943 未加载
评论 #29812077 未加载
评论 #29818086 未加载
评论 #29812329 未加载
评论 #29814228 未加载
imaurer超过 3 年前
URL is to a &quot;Things I Learned&quot; by Simon W, but the title comes from tweet by David Beazley:<p><a href="https:&#x2F;&#x2F;twitter.com&#x2F;dabeaz&#x2F;status&#x2F;1466731368956809219" rel="nofollow">https:&#x2F;&#x2F;twitter.com&#x2F;dabeaz&#x2F;status&#x2F;1466731368956809219</a><p>Which is a warning that people shouldn&#x27;t buy his new book if they want a deep dive on Metaprogramming:<p><a href="https:&#x2F;&#x2F;www.amazon.com&#x2F;dp&#x2F;0134173279&#x2F;" rel="nofollow">https:&#x2F;&#x2F;www.amazon.com&#x2F;dp&#x2F;0134173279&#x2F;</a><p>Simon does a nice job demonstrating how &quot;the __init_subclass__ class method is called when the class itself is being constructed.&quot;
VWWHFSfQ超过 3 年前
There are bugs in this code and I&#x27;m glad that I&#x27;m not the only one that has done it!<p><pre><code> graph = { key: { p for p in inspect.signature(method).parameters.keys() if p != &quot;self&quot; and not p.startswith(&quot;_&quot;) } for key, method in cls._registry.items() } </code></pre> The first parameter to a bound method does not have to be called `self`. It&#x27;s conventional, but not required. Is there a better way in the inspect module to filter these parameters? This comes up more often with classmethods where the naming convention `cls` is most common but I see `klass` somewhat frequently as well.
评论 #29820154 未加载
评论 #29818656 未加载
matsemann超过 3 年前
How does this play with typing and other tools? I hate the use of all the magic stuff in Python making it needlessly hard to use lots of libraries.
评论 #29812750 未加载
zbyforgotpass超过 3 年前
I wish there was a &#x27;Modern Python&#x27; tutorial that would walk me through all the new python stuff like this or the type declarations or the new libs, etc.
评论 #29820663 未加载
评论 #29813936 未加载
评论 #29820151 未加载
3pt14159超过 3 年前
I&#x27;m working on a project right now that uses __init_subclass__ and it works great, but takes some tricks (like having classvars with types set) in order to get mypy to cooperate. But it&#x27;s way easier to reason about than metaclasses.
Naac超过 3 年前
For those curious, here is a great explanation of what metaclasses are in python: <a href="https:&#x2F;&#x2F;stackoverflow.com&#x2F;a&#x2F;6581949" rel="nofollow">https:&#x2F;&#x2F;stackoverflow.com&#x2F;a&#x2F;6581949</a>
captainmuon超过 3 年前
I&#x27;ve only once used metaclasses but I think it was pretty nifty. The use case was with Python and Gtk+ (both version 2), if you had your UI in a glade file you could define a corresponding class, and it would automatically create members for all your named widgets. It made it a bit like coding in VB:<p><pre><code> class MainWindow(gtk.Window): __metaclass__ = MetaDescribedUI(&quot;MainWindow.ui&quot;) def __init__(self): # now you can use e.g. self.lvFiles or self.btnOK pass </code></pre> Although writing it now I could probably do it differently without metaclasses.
kkirsche超过 3 年前
Even using Python regularly I haven’t run into a need for meta classes. I’m sure there is a valid reason, but what is it?
评论 #29812446 未加载
评论 #29813157 未加载
评论 #29814328 未加载
评论 #29814961 未加载
评论 #29817826 未加载
评论 #29813371 未加载
评论 #29814784 未加载
fdgsdfogijq超过 3 年前
I once heard a quote that described David Beazely as:<p>&quot;The Jimi Hendrix of programming&quot;
joebergeron超过 3 年前
(Shameless self-plug incoming…)<p>For those curious about what metaclasses actually are, I wrote up an article with some motivating examples about this a little while back. Might be worth a read if you’re interested!<p><a href="https:&#x2F;&#x2F;www.joe-bergeron.com&#x2F;posts&#x2F;Interfaces%20and%20Metaclasses%20in%20Python&#x2F;" rel="nofollow">https:&#x2F;&#x2F;www.joe-bergeron.com&#x2F;posts&#x2F;Interfaces%20and%20Metacl...</a>
wheelerof4te超过 3 年前
Isn&#x27;t it ironic that one of the most readable procedural languages today has almost unreadable OOP syntax?<p>People unironically created interfaces and various overloaded operations using dunder methods. Not only do you need to keep a list of them under your pillow, but you must also keep notes on how to construct the interface for each one.<p>And they look ugly as hell. In a language that prides itself on readability and user friendlines.<p>My suggestion is to ditch the OOP syntax completely and make a built-in analogue to a C struct. Take inspiration from dataclasses syntax. OOP in a dynamic glue language is a silly idea anyway. Of course, you would have to bump the version to 4.0.
tsujamin超过 3 年前
I recently encountered __init_subclass__ for the first time in Home Assistant&#x27;s custom integrations. Configuration handlers were registerd by &quot;just declaring the class&quot; like so and I couldn&#x27;t grok how it was registered by the runtime<p><pre><code> class MyCustomOptionsFlow(OptionsFlow, DOMAIN=&quot;MYPLUGIN&quot;):... </code></pre> A bit of digging showed that __init__subclass_ was being used effectively as a registration callback, adding the newly defined class&#x2F;DOMAIN to the global CustomOptions handler at class definition.<p>Very neat, not immediately obvious however :&#x2F;
cutler超过 3 年前
Evidence, if any was needed, that OOP, or at least the Python variant, was never designed for metaprogramming. Give me Clojure macros any day of the week over these ugly contortions.
评论 #29817693 未加载
sam0x17超过 3 年前
I love that Python is unique and strange enough that merely seeing &quot;__init_subclass__&quot; in this headline is enough to know exactly what language it is talking about ;)
jwilk超过 3 年前
Official docs for that feature:<p><a href="https:&#x2F;&#x2F;docs.python.org&#x2F;3&#x2F;reference&#x2F;datamodel.html#object.__init_subclass__" rel="nofollow">https:&#x2F;&#x2F;docs.python.org&#x2F;3&#x2F;reference&#x2F;datamodel.html#object.__...</a>
wheelerof4te超过 3 年前
A recent anegdote with regards to typing in Python.<p>Let&#x27;s say you have this code:<p>class Creature:<p><pre><code> def __init__(self, name: str, hp: int, attack: int): ... def attack(self, other: Creature): ... </code></pre> Guess what? Since Creature is not yet defined, your very smart type-checker can&#x27;t see the &quot;other&quot; parameter. Happened to me in VS Code.<p>That is the problem with features bolted on to a language where they perhaps don&#x27;t belong. Now, I know that typing helps when you have simple, functional code. So, this code will work:<p>from dataclasses import dataclass<p>@dataclass<p>class Creature:<p><pre><code> name: str hp: int attack: int </code></pre> def combat_between(attacker: Creature, defender: Creature): ...<p>I was really surprised with this. We need better review in regards to adding additional features that may be broken on certain setups.
评论 #29814222 未加载
评论 #29814210 未加载
评论 #29817201 未加载
ajkjk超过 3 年前
For all of Python&#x27;s magic hackery that it lets you inject it feels like there are still some obvious &#x27;holes&#x27;.<p>The one that bites me a lot is: I want to easily be able to write a decorator that accesses variables on a particular _instance_ of a class (such as a cached return value), and I want to take a Lock when I do it.<p>But since decorators are defined on the class method, not the instance, it has to do a bunch of work when the function runs: look at the instance, figure out if the lock is defined, if not define it (using a global lock?), take the lock, then do whatever internal processing it wants. It feels like decorators should have a step that runs at `__init__` time to do per-instance setup but instead I have to figure it out myself.
评论 #29814537 未加载
wheelerof4te超过 3 年前
Python is slowly going in the direction of C++. Sad to see, really.
评论 #29812950 未加载
评论 #29813969 未加载
Garlef超过 3 年前
What&#x27;s the advantage of this over class decorators?<p><pre><code> @decorator class SomeClass: ... </code></pre> To me, class decorators seem to be much easier to reason about.
评论 #29820695 未加载
评论 #29820644 未加载
amelius超过 3 年前
__This__ __looks__ __very__ __interesting__!
dreyfan超过 3 年前
Python is quickly taking the crown for low-barrier to entry, slow, buggy code supported primarily by stackoverflow copy pastes from a never-ending supply of “data scientists”
评论 #29812690 未加载
评论 #29812991 未加载
评论 #29812970 未加载
评论 #29813985 未加载
评论 #29812758 未加载
评论 #29812910 未加载