Issue
i have the following json template
template.py
from string import Template
test1 = Template(u'''\
{
"data": {
"name": "$name"
}
}
''')
and to generate the JSONs I use JSONGen.py
import template
class JSONGen:
result1 = template.test1.safe_substitute(
name = 'SomeName'
)
print(result1)
now that works, it produces the JSON but i'm trying to create a function that accepts the template name and calls it something like
JSONGenV2.py
import template
class JSONGenV2:
def template_func(self, templateName):
generatedTemplate = template.templateName.safe_substitute(
name = 'SomeName'
)
print (generatedTemplate)
template_func(test1)
now what i want to achieve is to use 'templateName' contents to be the template to call, as it is right now
template.templateName.safe_substitute
gives me an error saying 'templateName' doesn't exist, how can 'templateName' be a changed to the value passed in tihs case 'test1' so it would call
template.test1.safe_substitute
Thank you
Solution
Use getattr()
, usage like this:
getattr
(object, name[, default])Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example,
getattr(x, 'foobar')
is equivalent tox.foobar
. If the named attribute does not exist, default is returned if provided, otherwiseAttributeError
is raised.
Applied to your code:
class JSONGenV2:
def template_func(self, templateName):
generatedTemplate = getattr(template, templateName).safe_substitute(
name = 'SomeName'
)
print (generatedTemplate)
template_func(test1)
Answered By - r.ook
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.