1 year ago

#302239

test-img

Rami Ma

Dynamically create a class inherited from neomodel.StructuredNode

Python's library neomodel provides the ability to define a relationship with a class that hasn't been defined yet, by using its name as string, which works fine as follows:

from neomodel import StructuredNode, RelationshipTo
# if Foo is already defined
class Bar (structuredNode):
    rel = RelationshipTo(Foo, 'REL')
# if Foo isn't defined
class Bar(StructuredNode):
    rel = RelationshipTo('Foo', 'REL')

I want to create a class in the runtime and provide it with the attribute RelationshipTo, which should make a relationship with undefined yet class, so I did:

Bar = type('Bar', (StructuredNode,), {'rel': RelationshipTo('Foo', 'REL')})

In some point in the runtime later, I define Foo:

Foo = type('Foo', (StructuredNode,), {})

Now if I want to use the class I've just made:

bar = Bar()

The next error still pops up as if I haven't defined Foo:

AttributeError: module '_pydevd_bundle.pydevd_exec2' has no attribute 'Foo'

Note: This error doesn't appear if I at least define Bar statically (not in the runtime)

Would someone explain why that happens and how to define them properly in runtime, please? I appreciate any help!

python

relationship

knowledge-graph

neomodel

dynamic-class-creation

0 Answers

Your Answer

Accepted video resources