Reputation: 27
is it possible to use a value of a string directly inside of the code as a class etc? I don't know to exactly describe what I want to do with words, so the pseudo code version is probably the best way to understand what's the issue. Here is the example:
for node in itemdict.iterkeys():
nodeinfo = itemdict.get(node)
if nodeinfo[4] == "node": #create new Links based on original nodeclass
#Example if nodeinfo[1] == "Dot"
#link = nuke.nodes.Dot(hide_input=nodeinfo[3], label='to: ' + nodeinfo[2])
link = nuke.nodes.XXX_value of nodeinfo[1] here_XX(hide_input=nodeinfo[3], label='to: ' + nodeinfo[2])
Upvotes: 0
Views: 100
Reputation: 55630
You want to use the getattr
builtin function to get attributes from objects by name:
for node in itemdict.iterkeys():
nodeinfo = itemdict.get(node)
if nodeinfo[4] == "node": #create new Links based on original nodeclass
# Get the attribute named <the value of nodeinfo[1]> from nuke.nodes
cls = getattr(nuke.nodes, nodeinfo[1])
link = cls(hide_input=nodeinfo[3], label='to: ' + nodeinfo[2])
If the object does not have an attribute wit the name that you passed to getattr
, an AttributeError
will be raised. You can either handle this error in your code or pass a third argument to getattr
, which getattr
will return instead raising AttributeError
.
Upvotes: 1
Reputation: 106543
If you want to get a class by name, you can use the built-in function globals
to obtain it.
For example:
class A(object):
def __init__(self):
self.number = 1
class B(object):
def __init__(self):
self.number = 2
for name in 'A', 'B':
print(globals()[name]().number)
This outputs:
1
2
Upvotes: 1