[Python] ‘int’ object is not callable

[問題/Problem]

‘int’ object is not callableというエラーが出る

“‘int’ object is not callable” error shows up

[原因/Cause]

関数名と変数名が重複している。たいていの場合は組み込み関数

Variable name conflicts with a function name, which in most cases is a build-in function

[解説/Details]

例えば下記の例では4行目と5行目でmaxという関数とmaxという変数が重複しており、max=aとした時点で関数maxが(このスコープでは)使用不能となった。

The sample code below has naming conflicts at lines 4 and 5, where “max=a” redefines a build-in function max() to an integer. The function max() is no longer callable within this scope, causing an error at line 5.

a=1
b=2
c=3
max=a
max=max(b,c)

上記の例だと変数定義と関数呼び出し箇所が近いのでそんなバカなと思うが、例えば以下のような、引数で定義してしまった場合や場所的に離れている場合などなどついうっかりということがあり得る。とくに予約語はmax,min,len,range等、単純でよく使う英単語の事があるため注意が必要。

Although the example above seems trivial, and might seem unlikely to occur, cares must be taken as those errors are sometimes encountered in more complicated cases including re-definition of built-in function as an argument, or re-definitions at distant locations, in which case forgetful programmers like me struggle finding this bug. Many short English words being reserved for built-in functions, naive naming like max, min, len, range, … should be avoided.

def do_something(a,b,c,max=100):
   d=max(a,b)
   #...

def do_something2(a,b,c):
   max=a #redefinition of the function max()
   #for loops or something
   # ... 10 lines or so
   return max(x,y) #trying to use max()

I feel that it would be nicer to show some kind of warning for making the redefinition, rather than just saying “type” is not callable…

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です