I want to get the Python schema definition for the table passed to the get_schema method in runtime.
class Test:
def __init__(self):
self.schema_table1 = {
"name": "str",
"add": "str"
}
self.schema_table2 = {
"n1": "str",
"n2": "str"
}
def get_schema(self, table_name):
schema = table_name
return schema
class Test2:
def __init__(self):
self.test_obj = Test()
def process(self):
table_name = "schema_"+'table1'
print(self.test_obj.get_schema(table_name))
test2_obj = Test2()
test2_obj.process()
Actual output:
schema_table1
Expected output:
{
"name": "str",
"add": "str"
}
bamitabh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
If you want to return variables with arbitrary names in a class, you can use getattr()
to either return the variable, or return None
.
Docs:
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 to x.foobar
class Test:
def __init__(self):
self.schema_table1 = {
"name": "str",
"add": "str"
}
self.schema_table2 = {
"n1": "str",
"n2": "str"
}
def get_schema(self, table_name):
schema = getattr(self, table_name, None)
return schema
class Test2:
def __init__(self):
self.test_obj = Test()
def process(self):
table_name = "schema_" + 'table1'
print(self.test_obj.get_schema(table_name))
test2_obj = Test2()
test2_obj.process()
This will safely fetch the variable if it exists, else it will return nothing back.