|
|
Subscribe / Log in / New account

Super Python (part 1)

Super Python (part 1)

Posted Apr 19, 2022 17:01 UTC (Tue) by stop50 (subscriber, #154894)
In reply to: Super Python (part 1) by NYKevin
Parent article: Super Python (part 1)

Dynamic classes exist. Django uses them for their user classes.


to post comments

Super Python (part 1)

Posted Apr 19, 2022 19:52 UTC (Tue) by NYKevin (subscriber, #129325) [Link] (2 responses)

Honestly, I'm starting to think that this person can get 80% of what they want by turning their mixins into functions like this:

T = typing.TypeVar('T', bound=SomeBaseClass)

def Mixin(Parent: type[T]) -> type[T]:
    class MixinClass(Parent):
        # Put mixin code here.
    return MixinClass

# Elsewhere in the codebase:

class SomeClass(SomeBaseClass):
    # Put the parent's code here.

class Derived(Mixin(SomeClass)):
    # Put the child's code here.

You don't need to futz with metaclasses to do that, you get the nice class Derived(Mixin(SomeClass)): syntax that this person seems to want, as well as an explicit, purely linear inheritance hierarchy, and (I think) you can even run this through a type-linter. The only downside is that pickling tends to dislike such dynamic classes, but frankly pickling is evil anyway.

If even that is too much typing, you can make a decorator that automagicks your mixin classes into Mixin()-like functions.

Super Python (part 1)

Posted Apr 19, 2022 21:48 UTC (Tue) by mathstuf (subscriber, #69389) [Link] (1 responses)

One issue here is that the `MixinClass` will be different from all other usages. If you use something like `isinstance` to detect if a mixin interface is available, you're kind of out of luck. But hey, this is Python, just call those methods and hope a duck quacks instead of a goose honking when you do that ;) .

Super Python (part 1)

Posted Apr 19, 2022 23:23 UTC (Tue) by NYKevin (subscriber, #129325) [Link]

Oh, I don't think this is actually a Good Idea. I just think the author can accomplish what they want without modifying the core language. Python is flexible, but that doesn't mean you should go around flexing it into whatever shape you like.


Copyright © 2025, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds