开发者

Replace if elif block in python

开发者 https://www.devze.com 2023-02-15 23:50 出处:网络
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.

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 someth开发者_如何转开发ing 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.

datatypes = {'string': 'z', 'double': 'd', 'number': 'i', 'blob': 'z'}
t = datatypes[self.datatype]

You may catch the KeyError and raise a domain exception.


Building on @jleedev's answer, it you really are doing this a lot, and if you want a custom exception:

class EntParEx(KeyError): pass
class DataMapping(dict):
    def __missing__(self, key):
        raise EntParEx("unknown datatype {}".format(key))


>>> datatypes = DataMapping(string='z', double='d', number='i', blob='z')
>>> datatypes['string']
'z'
>>> datatypes['other']
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    datatypes['other']
  File "<pyshell#8>", line 3, in __missing__
    raise EntParEx("unknown datatype {}".format(key))
EntParEx: 'unknown datatype other'

Edit to add code for the extended example:

>>> datatypes = DataMapping(string='static const int {lenvar} = {length};\nchar {cpp_membername}[{lenvar}+2];',
        double='double {cpp_membername};',
        number='int {cpp_membername};',
        blob='char* {cpp_membername};')
>>> inst = C()
>>> inst.lenvar = 'a'
>>> inst.length = 5
>>> inst.cpp_membername='member'
>>> datatypes['number'].format(**vars(inst))
'int member;'
>>> datatypes['string'].format(**vars(inst))
'static const int a = 5;\nchar member[a+2];'


You could also do something more dynamic.

type(self.datatype).__name__

Returns "str", "float", "int", etc. You could take the first character of that.

0

精彩评论

暂无评论...
验证码 换一张
取 消