有人可以向我解释一下为什么 type(foo)(bar) 如此不受欢迎吗?
我有一个配置变量的字典,看起来像这样:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
并非所有类型都支持习惯用法“使用字符串调用类型以创建该类型的新实例”。但是,如果您确保配置字典中仅有此类类型(可能在初始化时进行健全性检查),并放置合适的
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.更不用说,Python 中有配置模块,下面是我处理配置的方式,以整数值“bar”为例。 +1 for alex as '' 表示 False 的方式,请参阅值“xyz”!
该值也可以在配置中保存为 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"!
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.