It turned out that this conditional block keeps on repeating itself in my code. Any other way to make my life easier? Of course, the body to be executed for a condition differs.
if self.datatype == "string":
t = "z"
elif self.datatype == "double":
t = "d"
elif self.datatype == "number":
t = "i"
elif self.datatype == "blob":
t = "z"
else:
raise EntParEx("Unknown datatype" + self.datatype)
……more code using the same conditional
def emit_cpp_def(self):
s = ""
e = ""
if self.datatype == "string":
s += "static const int " + self.lenvar + " = " + self.length + ";"
s += "\nchar"
e += "[" + self.lenvar + " + 2" + "]"
elif self.datatype == "double":
s += "double"
elif self.datatype == "number":
s += "int"
elif self.datatype == "blob":
s += "char*"
else:
raise EntParEx("Unknown datatype" + self.datatype)
s += " " + self.cpp_membername;
s += e
s += ";"
return s;
def emit_cursor_def_code(self):
if self.datatype == "blob":
return ""
ret = "nvl(" + self.db_fieldname + ", "
#TODO: Add default value loading!
if self.datatype == "string":
ret += "\' \'"
elif self.datatype == "double":
ret += "-1.0"
elif self.datatype == "number":
ret += "-1"
else:
raise EntParEx("Unknown datatype" + self.datatype)
ret += "), "
return ret
EDIT:
I think what I need is something like running a specific function for each type. Unfortunately I’m not that versed in python. Can that be done? i.e.
switch_datatype(function_string(), function_integer(), ...etc)
Is this worse?
If it’s the exact same conditional, stick it in a method and call it where you need it. Otherwise, define the dictionaries somewhere and use whichever you need.
You may catch the KeyError and raise a domain exception.