我需要知道Python中的变量是字符串还是字典.以下代码有什么问题吗?
if type(x) == type(str()):
do_something_with_a_string(x)
elif type(x) == type(dict()):
do_somethting_with_a_dict(x)
else:
raise ValueError
Run Code Online (Sandbox Code Playgroud)
更新:我接受了avisser的回答(但如果有人解释为什么isinstance更喜欢,我会改变主意type(x) is).
但由于nakedfanatic提醒我,这是经常清洁剂使用的字典(作为case语句)比如果/ elif的/其他系列.
让我详细说明我的用例.如果变量是一个字符串,我需要将它放在一个列表中.如果它是一个字典,我需要一个唯一值的列表.这是我想出的:
def value_list(x):
cases = {str: lambda t: [t],
dict: lambda t: list(set(t.values()))}
try:
return cases[type(x)](x)
except KeyError:
return None
Run Code Online (Sandbox Code Playgroud)
如果isinstance是首选,你会怎么写这个value_list()功能?
我有一个函数可以接受两个可选np.array的参数.如果两者都通过,该功能应该执行一些任务.
def f(some_stuff, this=None, that=None):
...do something...
if this and that:
perform_the_task()
Run Code Online (Sandbox Code Playgroud)
如果没有传递任何可选参数,这将按预期工作.如果我通过了np.array然后我获得了错误
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Run Code Online (Sandbox Code Playgroud)
是否有更紧凑的方法来检查额外的args是否通过?我想我可以安全地假设,如果他们通过,那么他们将是np.array.
我有一个GUI,允许用户从特定的*.py文件运行任何功能.我希望某些功能以不同的方式运行.为了做到这一点,我试图将属性附加到函数(简单的事情,如它需要的输入).但是,我发现获取这些属性的唯一方法是首先运行代码.
有没有办法在不运行代码的情况下获得这些属性,或者通常可以采用更加pythonic的方式来处理此任务?
我的代码的非常基本的例子:
FileA.py
def Beta(x):
Beta.input_stype = "Float"
y = x + 0.5
return y
def Gamma(x):
Gamma.input_stype = "String"
y = x + "_blah_blah_blah"
return y
def Delta(x):
Delta.input_stype = "String"
y = x.index('WhereIsIt')
return y
Run Code Online (Sandbox Code Playgroud)
FileB.py
import FileA
import inspect
z = inspect.getmembers(Fiddle2, inspect.isfunction)
#### User selects the code value here ####
x = user_selection
executable = z[x][1] # Pulls the executable code
if executable.input_stype == "Float" :
y = executable(45)
elif executable.input_stype == "String" :
y …Run Code Online (Sandbox Code Playgroud) 我仍然是Python的新手,我正在尝试习惯它的动态类型.有时我有一个函数或类需要某个类型的参数,但是可以得到另一个类型的值,它可以强制它.例如,它可能期望a float而是接收int或decimal.或者它可能需要一个字符串,而是接收一个定义__str__特殊方法的对象.
将论证强制转换为正确的类型(及其原因)的最佳做法是什么?我是在函数/类中还是在调用者中执行此操作?如果在调用者中,我是否也在函数中检查它?例如.
备选方案1:
def myfunc(takes_float):
myval = float(takes_float)
myfunc(5)
Run Code Online (Sandbox Code Playgroud)
备选方案2:
def myfunc(takes_float):
myval = takes_float
myfunc(float(5))
Run Code Online (Sandbox Code Playgroud)
备选方案3:
def myfunc(takes_float):
assert isinstance(takes_float, float)
myval = takes_float
myfunc(float(5))
Run Code Online (Sandbox Code Playgroud)
我已经读这个答案和这一次,他们说,在Python检查类型是"坏"的,但我不想把时间浪费在追踪非常简单的错误,这些错误会在静态类型被立即拾起编译器语言.