[Tutor] str object is not callable
Steven D'Aprano
steve at pearwood.info
Tue Jul 10 18:23:24 CEST 2012
Chris Hare wrote:
> def special_match(string, search=re.compile(r'[^a-zA-Z0-9\.\ \-\#\$\*\@\!\%\^\&]').search):
> #string = string.rstrip()
> return not bool(search(string))
The call to bool is redundant. Get rid of it. The not operator will
automatically convert its argument into a bool:
py> print('s', bool('s'), not 's')
s True False
py> print(None, bool(None), not None)
None False True
That eliminates one possible source of errors, and will be a tiny bit faster.
Also, a stylistic comment: your function as defined above is painful. Do
yourself, and your readers, a favour by defining a named constant like this:
SPECIAL_CHARS = re.compile(r'[^a-zA-Z0-9\.\ \-\#\$\*\@\!\%\^\&]')
def special_match(string, search=SPECIAL_CHARS.search):
return not search(string)
> However, when I use the EXACT same code in the context of the larger code,
> I get the error
>
> return not bool(search(strg)) TypeError: 'str' object is not callable
As numerous people have already pointed out, you have shadowed either the bool
or the search functions with a variable with the same name containing a
string:
py> len("hello world")
11
py> len = 11 # oops, shadowing the builtin function
py> len("hello world")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
> As a side note -- the rstrip call is also broken, although the string
> module is imported. I just can't figure out why this code works in one
> context and not in another.
For the same reason -- you define a local variable "string", which shadows the
global "string" module.
--
Steven
More information about the Tutor
mailing list