Search code examples
pythonpython-3.xpy2neo

flexible class name using python (py2neo Metaclasses used)


Until now i have not found the answer to this question (more a general Python question than explicite for py2neo) I want to be able to call py2neo classes flexible:

class foo1(GraphObject):
    __primarykey__ = "bar"
    bar = Property()
    foobar = RelatedTo("foo1")
    foobar2 = RelatedTo("foo1")

class foo2(GraphObject):
    __primarykey__ = "bar"
    bar = ""
    foobar = RelatedTo("foo2")
    foobar2 = RelatedTo("foo2")

def flexiblefoocreate(classname,newbar):
    #classname is "foo1" or "foo2"
    tempvar=classname()
    tempvar.bar=newbar

def flexiblefoobaradding(classname,startbar,foobarname,endbar)
    #classname is "foo1" or "foo2"
    #foobarname is "foobar" or "foobar2"
    startfoo=classname()
    startfoo.bar=startbar
    endfoo=classname()
    endfoo.bar=endbar
    startfoo.foobarname.add(endfoo)

How can I get this working?

background: Later on easy adding/using of properties


Solution

  • You can use metaclasses:

    class Foo1(object):
        def d1(self):
            print(self, ".d1")
    
    
    class Foo2(object):
        def d2(self):
            print(self, ".d2")
    
    
    def make_class(base):
        return type(str(base), (base,), {})
    
    
    MyExtraordinarilyNamedFoo1Class = make_class(Foo1)
    MySimpleFoo2Class = make_class(Foo2)
    
    foo1 = MyExtraordinarilyNamedFoo1Class()
    foo2 = MySimpleFoo2Class()
    
    foo1.d1()
    foo1.new_attr = 1
    print(foo1.new_attr)
    
    foo2.d2()
    foo2.new_attr = 2
    print(foo2.new_attr)