有人可以向我解释一下为什么 type(foo)(bar) 如此不受欢迎吗?

发布于 2024-09-16 23:36:20 字数 425 浏览 8 评论 0原文

我有一个配置变量的字典,看起来像这样:

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

我希望能够从用户输入更新这些变量(在这种情况下,将始终采用字符串的形式)。我面临的问题是显而易见的,我的第一个解决方案对我来说似乎已经足够好了:

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

然而,Freenode 中的 #python 几乎让我建议这样的解决方案冒犯了。有人能告诉我为什么这是不好的做法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小兔几 2024-09-23 23:36:20

并非所有类型都支持习惯用法“使用字符串调用类型以创建该类型的新实例”。但是,如果您确保配置字典中有此类类型(可能在初始化时进行健全性检查),放置合适的try /除了围绕您的转换尝试的保护(以比死于堆栈跟踪更好的方式处理用户错误,例如拼写错误;-),没有什么“对于支持该功能的类型使用该功能本质上是错误的。

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.

小嗷兮 2024-09-23 23:36:20

更不用说,Python 中有配置模块,下面是我处理配置的方式,以整数值“bar”为例。 +1 for alex as '' 表示 False 的方式,请参阅值“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"]))

该值也可以在配置中保存为 int,但我们不需要 type 因为我们知道我们正在输入整数。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文