Dynamically creating a class from a file in Python

I saw these "dynamically creating a class" questions that are answered: "use the type () function". I'm sure I will have to at some point, but I know that I do not know. But from what I saw, you should already know something about the class, for example, the name.

What I'm trying to do is parse the idl type of the file and create a class that will have methods and attributes. So I don’t have ANY knowledge before the name of the class, function, arguments or anything else will be there until I parse the string.

Any ideas?

+5
source share
3 answers

http://docs.python.org/library/functions.html#type

This is a bit tricky for Google, but you can find python type(name, bases, dict) function examplesto get:

http://www.voidspace.org.uk/python/articles/metaclasses.shtml

, :


:

def __init__(self, x):
    self.x = x

def printX(self):
    print self.x

Test = type('Test', (object,), {'__init__': __init__, 'printX': printX})

class Test(object):
    def __init__(self, x):
        self.x = x

    def printX(self):
        print self.x

" ", . - ( , ). , IDL. : http://effbot.org/pyfaq/how-do-you-make-a-higher-order-function-in-python.htm

, , IDL ( IDL), - , :

def makeMethod(idlCode):
    syntax = MyIDL.parse(idlCode)

    def newMethod(*args, **kw):
        if syntax.statementType == MyIDL.IF_STATEMENT:
            if secureLookup(mySyntaxTree.IF):
               return secureLookup(args[0]) 
            else:
               return secureLookup(args[1])
        ...

    return (syntax.methodName, newMethod)

, IDL * args ** kw, .

:

class DynamicIdlClass(object):
    ...

for idlObject in idlCode:
    methods = dict(makeMethod(clause) for clause in idlObject.clauses})
    methods['__init__'] = makeInitMethod(idlObject.initClause)
    idlObject = type('Test', (DynamicIdlClass,), methods)

    yield idlObject  # or idlObjectsList.push(idlObject), etc.
+14

, , , . yaml .

def add_method(name, callable):
    setattr(self,name,callable)

, . - __schema, , docstrings kwarg.

def skel(self, *args, **kwargs):
    if '_schema' in kwargs:
        parse_yml, add control statements
    handle args and kwargs based on schema

some_instance.add_method('blah',skel)

, , . .

:

IonObject

+1

Instead of thinking of it as “how I dynamically create a class”, think of it as an opportunity to use the Python metaprogramming capabilities.

The first thing I was looking for ideas was the standard library source for xmlrpclib- see how it uses __getattr__to handle otherwise non-existent method calls on the fly.

I know that I really don’t understand why they call Python a dynamic language, until I completely agree with these possibilities.

+1
source

All Articles