FAQ
Hi,

I'm a Python beginner and I'm would like to write a function that
returns a class (perhaps a tad ambitious...). I've looked through
the FAQ and perused "Python In A Nutshell" (not a good book to
start with?). The only example I found in PiaN used a simple
if statement to return one of a selection of pre-existing classes.
I'd like to generate a class on-the-fly from a parameter (a dictionary).
Can Python do this sort of stuff? Does the mean I have to mess with
the dreaded meta-classes?

thanks for any help anyone can give.


--
Nick Keighley

It's always September. But sometimes it is _more_ September.

Search Discussions

  • Andrew Dalke at Aug 20, 2003 at 8:28 am

    Nick Keighley:
    I'm a Python beginner and I'm would like to write a function that
    returns a class (perhaps a tad ambitious...).
    There's

    class MyClass:
    pass

    def fctn():
    return MyClass

    or you can make the class inside of the function

    def fctn():
    class MyClass:
    pass
    return MyClass
    I'd like to generate a class on-the-fly from a parameter (a dictionary).
    Can Python do this sort of stuff? Does the mean I have to mess with
    the dreaded meta-classes?
    Well, *what* do you want to do?
    def fctn(d):
    ... class MyClass:
    ... def get(self, x):
    ... return d[x]
    ... return MyClass
    ...
    klass = fctn({"A": 1, 2: "B"})
    klass
    <class __main__.MyClass at 0x01351810>
    instance = klass()
    instance.get("A")
    1
    >>>
    import types
    def fctn(name, d):
    ... return types.ClassType(name, (), d)
    ...
    fctn("YoYo", {"around": "world", "walk": "dog"})
    <class __main__.YoYo at 0x01351900>
    klass = _
    inst = klass()
    inst.walk
    'dog'
    >>>

    Andrew
    dalke at dalkescientific.com
  • Helmut Jarausch at Aug 20, 2003 at 8:46 am
    I'm quite new to Python, as well.

    Nick Keighley wrote:
    Hi,

    I'm a Python beginner and I'm would like to write a function that
    returns a class (perhaps a tad ambitious...). I've looked through
    the FAQ and perused "Python In A Nutshell" (not a good book to
    ===============================================^^^^^^^^^^^^^^^^^^
    start with?). The only example I found in PiaN used a simple
    ^^^^^^^^^^^
    Python in a Nutshell is an excellent book except if Python is your
    very first programming language.
    if statement to return one of a selection of pre-existing classes.
    I'd like to generate a class on-the-fly from a parameter (a dictionary).
    Can Python do this sort of stuff? Does the mean I have to mess with
    the dreaded meta-classes?
    Have a look at ch 13 (top of page 262).
    Build a string 'ClassDefinition',
    call compile like
    GenClassCode= compile(ClassDefinition,'my_class_def','exec')
    and than in some context
    exec(GenClassCode)
    If 'ClassDefinition' generates a class 'X' just use it
    like
    newX= X(....)



    --
    Helmut Jarausch

    Lehrstuhl fuer Numerische Mathematik
    RWTH - Aachen University
    D 52056 Aachen, Germany
  • David M. Cook at Aug 20, 2003 at 8:47 am
    In article <8ad2cfb3.0308200015.4f5bd504 at posting.google.com>, Nick Keighley
    wrote:
    I'm a Python beginner and I'm would like to write a function that
    returns a class (perhaps a tad ambitious...). I've looked through
    the FAQ and perused "Python In A Nutshell" (not a good book to
    start with?). The only example I found in PiaN used a simple
    if statement to return one of a selection of pre-existing classes.
    I'd like to generate a class on-the-fly from a parameter (a dictionary).
    Can Python do this sort of stuff? Does the mean I have to mess with
    the dreaded meta-classes?
    You can create classes on the fly using "type"
    type('Foo', (object,), {})
    <class '__main__.Foo'>

    The arguments are the class name, a tuple of base classes, and a dictionary
    of methods.

    See http://python.org/2.2/descrintro.html#factories

    Dave Cook
  • Daniel Klein at Aug 20, 2003 at 1:07 pm

    On 20 Aug 2003 01:15:44 -0700, nick.keighley at marconi.com (Nick Keighley) wrote:

    I'd like to generate a class on-the-fly from a parameter (a dictionary).
    class MyClass(object):
    def __init__(self, deadparrot):
    self.deadparrot = deadparrot
    mydict = { 'MyClass' : 'foobar'} # { className : constructorArgument }

    className = mydict.keys()[0]
    arg = mydict.values()[0]

    myInstance = eval(className + '(arg)')
    myInstance
    <__main__.MyClass object at 0x00A7DE30>
    myInstance.deadparrot
    'foobar'

    HTH,

    Daniel Klein
    Member of the Dead Parrot Society
  • Alex Martelli at Aug 20, 2003 at 9:37 pm

    Nick Keighley wrote:

    Hi,

    I'm a Python beginner and I'm would like to write a function that
    returns a class (perhaps a tad ambitious...). I've looked through
    the FAQ and perused "Python In A Nutshell" (not a good book to
    start with?). The only example I found in PiaN used a simple
    If you're an experienced programmer with other languages then
    the Nutshell should be helpful -- if you're a newbie to programming,
    you should start with easier books (but with the kind of tasks
    you're setting yourself I guess you aren't). I didn't particularly
    emphasize metaprogramming in the Nutshell -- it's more of a "gee
    whiz" kind of thing and the Nutshell aims to cover solid, everyday,
    bread-and-butter usage.
    if statement to return one of a selection of pre-existing classes.
    I'd like to generate a class on-the-fly from a parameter (a dictionary).
    How do you want to use that dict -- as the class's dict? Then either:

    def makeaclass(fromdict):
    class X: pass
    X.__dict__ = fromdict
    return X

    or

    def makeaclass(fromdict):
    class X: pass
    X.__dict__.update(fromdict)
    return X

    might be helpful.

    Can Python do this sort of stuff? Does the mean I have to mess with
    the dreaded meta-classes?
    Metaclasses may be easier to use than sufficiently-general class-building
    functions, actually -- no reason to dread them. But anyway, yes, Python
    IS pretty good at metaprogramming, too, both with and without metaclasses.


    Alex
  • Nick Keighley at Aug 22, 2003 at 12:07 pm
    Alex Martelli <aleax at aleax.it> wrote in message news:<5SR0b.21604$zN5.668541 at news1.tin.it>...
    Nick Keighley wrote:
    thamks all for help and suggestions.
    I'm a Python beginner and I'm would like to write a function that
    returns a class (perhaps a tad ambitious...). I've looked through
    the FAQ and perused "Python In A Nutshell" (not a good book to
    start with?). The only example I found in PiaN used a simple
    If you're an experienced programmer with other languages then
    the Nutshell should be helpful -- if you're a newbie to programming,
    you should start with easier books (but with the kind of tasks
    you're setting yourself I guess you aren't).
    no, not a programming beginner. A Python beginner. I was specifically
    trying to do something that was hard (impossible) to do in "normal"
    language (eg. C). The idea was try and generate types (ie. classes)
    that had a
    limited set of values. I'd found the C enum emulators in

    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/67107

    but they didn't quite do what I wanted.
    [...] I didn't particularly
    emphasize metaprogramming in the Nutshell -- it's more of a "gee
    whiz" kind of thing and the Nutshell aims to cover solid, everyday,
    bread-and-butter usage.
    if statement to return one of a selection of pre-existing classes.
    I'd like to generate a class on-the-fly from a parameter (a dictionary).
    How do you want to use that dict -- as the class's dict? Then either:

    def makeaclass(fromdict):
    class X: pass
    X.__dict__ = fromdict
    return X

    or

    def makeaclass(fromdict):
    class X: pass
    X.__dict__.update(fromdict)
    return X

    might be helpful.

    Can Python do this sort of stuff? Does the mean I have to mess with
    the dreaded meta-classes?
    Metaclasses may be easier to use than sufficiently-general class-building
    functions, actually -- no reason to dread them. But anyway, yes, Python
    IS pretty good at metaprogramming, too, both with and without metaclasses.

    --
    Nick Keighley

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
grouppython-list @
categoriespython
postedAug 20, '03 at 8:15a
activeAug 22, '03 at 12:07p
posts7
users6
websitepython.org

People

Translate

site design / logo © 2022 Grokbase