[英]Check if string is type
I wish to parse keyword arguments to determine if they also refer to types, such as in the case below:我希望解析关键字 arguments 以确定它们是否还指代类型,例如以下情况:
from inspect import isclass
def convert(converting, **kwargs):
for key, value in kwargs.items():
if value and isclass(eval(key[1:])):
return(eval(key[1:])(converting))
string = "Hello!"
print(convert(string, _list = True))
I am well aware that eval
has security concerns for unknown strings, which is why I am looking for a safer method of determining the type from the keyword name.我很清楚
eval
对未知字符串有安全问题,这就是为什么我正在寻找一种更安全的方法来确定关键字名称的类型。
Built-in types can be checked via import builtins; isclass(getattr(builtins, 'str'))
内置类型可以通过
import builtins; isclass(getattr(builtins, 'str'))
import builtins; isclass(getattr(builtins, 'str'))
, as per a_guest's comment here , but I am still stumped on how to check other classes. import builtins; isclass(getattr(builtins, 'str'))
,根据a_guest在此处的评论,但我仍然对如何检查其他类感到困惑。 Perhaps isclass(getattr(globals(), key[1:]))
?也许
isclass(getattr(globals(), key[1:]))
?
Python normally looks up names using LEGB. Python 通常使用 LEGB 查找名称。 Since you have no non-locals, you can ignore
E
.由于您没有非本地人,您可以忽略
E
。 You know that you don't have a local name, do indeed So the equivalent lookup would indeed be a call to globals
.您知道您没有本地名称,确实如此 所以等效的查找确实是对
globals
的调用。
You don't need a dictionary if all you care about are the keys.如果您只关心键,则不需要字典。 That way, you explicitly pass in simple strings and don't need to play games with extra characters:
这样,您可以显式传递简单的字符串,而无需玩带有额外字符的游戏:
def convert(converting, *names):
for name in names:
obj = globals.get(name, getattr(__builtin__, name, None))
if isclass(obj):
return obj(converting)
return converting
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.