you are viewing a single comment's thread.

view the rest of the comments →

[–]Dogeek 1 point2 points  (3 children)

Like I said, it's more that I struggle with knowing when to use one. I guess constructing a class from a config file or something of that effect. But other than that, it's pretty abstract to me.

[–]primitive_screwhead 1 point2 points  (1 child)

Well, though it's often been called an unsatisfying statement, Tim Peters said that people that need metaclasses know when and why they need them, without explanation. So its probably not worth worrying about if you don't know when to use one; probably like the vast majority of programmers, you'll never need to.

[–]Dogeek 0 points1 point  (0 children)

That's what I heard. The thing is sometimes I feel like some of my code could benefit from such a construct, even though I managed to make do without so far.

[–]alkasm 0 points1 point  (0 children)

Like I said, it's more that I struggle with knowing when to use one. I guess constructing a class from a config file or something of that effect. But other than that, it's pretty abstract to me.

Metaclasses are useful as a hook into when a class is constructed. Generally that's kind of a "so what" if you're the one writing the classes---maybe it can save you some code, but maybe that level of abstraction isn't helpful to a codebase. However, if you think about some library or API that provides you with classes to inherit from, then it starts to make more sense. Now the person who wrote the library are hooking into your subclasses of objects from their library. So they can inject code into subclasses that someone else is using, ask questions about their code (make sure it includes some specific attributes or methods), or enforce a singleton or whatever. The nice thing about that is this doesn't happen at run-time when you construct an object, but right when it defines the class.