【发布时间】:2020-02-09 21:34:38
【问题描述】:
在函数中将对象类型作为参数传递的最 Pythonic 方式是什么?
让我举个例子。假设我试图从环境变量中获取配置。因为所有环境变量都是字符串,所以我需要将值转换为正确的类型。
为此,我需要告诉函数所需的类型。这就是coerce 参数的目的。我的第一直觉是将所需的类型作为coerce 的值传递。但是,我不确定这样做是否有任何影响或问题。
import os
# The Function
def get_config(config: str, coerce: type, default: any, delimiter: str = ","):
value = os.getenv(config, None) # Get config from environment
if value is None:
return default # Return default if config is None
if coerce is bool:
value = str2bool(value) # Cast config to bool
elif coerce is int:
value = str2int(value) # Cast config to int
elif coerce is list:
value = value.split(delimiter) # Split string into list on delimiter
return value # Return the config value
# Usage
os.environ["TEST_VAR"] = "True"
test_var = get_config("TEST_VAR", bool, False)
print(test_var) # output is True
print(type(test_var)) # output is <class 'bool'>
在我看来,这似乎比使用 "str" 或 "bool" 等字符串来指定类型更清晰和更符合 Python 风格。但是,我想知道将内置类型作为函数参数传递是否会导致任何问题。
【问题讨论】:
-
这很好。你有什么具体的顾虑吗?这可能更适合 CodeReview 而不是 StackOverflow
-
@juanpa.arrivillaga 没有特别关注。只是不确定这是否会在以后回来咬我。感谢您指出 CodeReview 我不知道它存在!