What I'm Trying to do
Considering a file with rows:
A B C value
A B D value
Is it possible to create a structure that would be able to acccess the values like this:
A.B.C.val()
A.B.D.val()
Considering that A, B, C, D
are containers (like forms, windows, etc), I would like to be able to get each element path by using this structure.
What I'm asking
In the end, what I would want to know is if, having a class (let's say generic
), can I create an inheriting class named A
(name read from a file, can be anything) during runtime which would then cease to exist (the last part is not really important)?
Is that what you're looking for?
# Generic class definition
class Generic (object):
value = None
@classmethod
def val(cls):
return int(cls.value)
# Top level class
TopLevelClass = type('TopLevelClass',
(Generic, ), {})
lines = ["A B C 42",
"A B D 43"]
for line in lines:
# Parse the line
path = line.split()[:-1]
value = line.split()[-1]
# Create the classes
current = TopLevelClass
for x in path:
if hasattr(current,x):
current = getattr(current,x)
else:
cls = type(x, (Generic, ), {})
setattr(current,x,cls)
current = cls
# Apply value
setattr(cls,'value',value)
# Test
print(TopLevelClass.A.B.C.val())
print(TopLevelClass.A.B.D.val())
Output :
>>> 42
>>> 43