Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #197486

Re: Dynamic classes

From Left Right <olegsivokon@gmail.com>
Newsgroups comp.lang.python
Subject Re: Dynamic classes
Date 2025-05-20 08:03 +0200
Message-ID <mailman.67.1747767982.3008.python-list@python.org> (permalink)
References <CAApdmf3UwA6zf2-eSfd=1U=Unx3-6PUj6+XS0Sp62rkn73C8iQ@mail.gmail.com> <CAJQBtgmOKat7eVWcVzatLwvU+Xy_Ntj9BeRf1tBb-QEHxTBFSw@mail.gmail.com>

Show all headers | View raw


> I have created a dynamic class using the type() function:
> x = type('MyFlags', (), {'Flag1': 1, 'Flag2': 2, 'Flag3: 4, ' '__init__' :
> __init__})

I find that it's generally more convenient to do this using similar code:

def constructor(flag1, flag2):
    class _Hidden:
        def __init__(self):
            self.flag1 = flag1
            self.flag2 = flag2
    return _Hidden()

h = constructor('Flag1', 'Flag2')

This accomplishes the same goal (with some overhead, perhaps), but is
easier to format, the editor will recognize that you are writing a
class rather than a bunch of data bits, you will have the ability to
define the methods together with the class, benefit from the class
initialization environment (eg. by using @static or @property
decorators etc.). Also, this allows class parametrization in ways that
are difficult to accomplish using metaclasses and other complicated
mechanisms Python language provides to that end. Eg. you can
conditionally inherit from different superclasses (so, you can use
this approach as a factory that creates different classes), or you can
conditionally add methods, conditionally provide different method
bodies, conditionally provide different arguments to parametrized
decorators.

Back to comp.lang.python | Previous | NextNext in thread | Find similar


Thread

Re: Dynamic classes Left Right <olegsivokon@gmail.com> - 2025-05-20 08:03 +0200
  Re: Dynamic classes ram@zedat.fu-berlin.de (Stefan Ram) - 2025-05-21 11:20 +0000
    Re: Dynamic classes (Posting On Python-List Prohibited) Lawrence D'Oliveiro <ldo@nz.invalid> - 2025-05-22 00:19 +0000

csiph-web