开发者

Would someone explain to me why type(foo)(bar) is so heavily discouraged?

I have a dict of configuration variables that looks something like this:

self.config = {
    "foo": "abcdef",
    "bar": 42,
    "xyz": True
}

I want to be able to update these variables from user input (which, 开发者_开发问答in this case, will always be in the form of a string). The problem I'm facing is obvious, and my first solution seemed good enough to me:

def updateconfig(self, key, value):
    if key in self.config:
        self.config[key] = type(self.config[key])(value)

However, #python in Freenode almost seemed offended that I would suggest such a solution. Could someone tell me why this is bad practice?


Not all types support the idiom "call the type with a string to make a new instance of that type". However, if you ensure you only have such types in your config dict (with a sanity check at init time maybe), and put suitable try/except protection around your conversion attempt (to deal with user errors such as typos in a far better way than dying with a stack trace would be;-), there's nothing "inherently wrong" in using that functionality for the types that do support it.


Not to mention, that there is config module in Python, here is how I would deal with config, with example of integer value "bar". +1 for alex as '' for the way to say False, see value "xyz"!

config = {
    "foo": "abcdef",
    "bar": "42",
    "xyz": "True" ## or 'Yes' or anything not False, "" for False
}

bar = ''
while not bar:
    barinput = raw_input('Enter property  bar, integer (1..99): ')
    try:
        if 0 < int(barinput) < 100:
            pass
        else:
            raise ValueError("%s is not integer in range 1..99" % barinput)
    except ValueError as e:
        print(str(e)+"\nWrong input, try again")
    else:
        print("Saving correct value")
        bar = config["bar"] = barinput
print('New value of "bar" in config: %i' % int(config["bar"]))

The value could be saved as int in config also, but we have not need for type as we know that we are inputing integer.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜