Python转换风格:内部还是外部功能?

fba*_*ber 7 python styles

我有一个期望在数字类型上运行的函数.我正在读取要从文件操作的数字,所以当我读它们时,它们是字符串,而不是数字.是否更好地使我的函数能够容忍其他类型(下面的选项(A)),或者在调用函数之前转换为数字(下面的选项(B))?

# Option (A)
def numeric_operation(arg):
    i = int(arg)
    # do something numeric with i

# Option (B)
def numeric_operation(arg):
    # expect caller to call numeric_operation(int(arg))
    # do something numeric with arg
Run Code Online (Sandbox Code Playgroud)

Mic*_*ski 6

如果你的函数希望对数字数据进行操作,那么你可能最好TypeError 不要让Python抛出一个如果它没有收到错误的东西.我会说,在外面进行转换并处理异常.

def numeric_operation(arg):
   # Do numeric things

try: 
  numeric_operation("abc")
except TypeError:
  print("That was supposed to be numeric.")
Run Code Online (Sandbox Code Playgroud)


pwu*_*rtz 5

我会拆分这些操作.有一个函数可以从文件中读取数字,并让该函数返回实数或数组.执行数字操作的函数不应该在每次调用时处理转换,并且您不必为每个函数实现它.可能有例外,例如接受数字的数字函数,数字列表和数组.

当你把所有东西放在一起时,你将看不到任何字符串.你为什么要?您提到的文件中没有真正的字符串.这些是编码为字符串的数字,因此只需相应地读取它们,并在从文件中导入数据的函数中隐藏转换.