[Tutor] str object is not callable

Dave Angel d at davea.name
Tue Jul 10 17:45:19 CEST 2012


On 07/10/2012 10:56 AM, Chris Hare wrote:
> This piece of code works:
>
> Big-Mac:Classes chare$ more tmp.py
> import re
>
> def special_match(string, search=re.compile(r'[^a-zA-Z0-9\.\ \-\#\$\*\@\!\%\^\&]').search):
>         #string = string.rstrip()
>         return not bool(search(string))
You just redefined string from the name of a module to a local variable
(function parameter).  Pick a safer name.


> print special_match("admin")
> print special_match("&!*")
> print special_match("=")
>
> Big-Mac:Classes chare$ python tmp.py
> True
> True
> False
> Big-Mac:Classes chare$ 
>
> 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
Since there are two places in that line that look like function calls,
it's hard to guess which one is nor working.  Just put prints
immediately in front of the error line, and see what kind of objects
bool and search are.

Chances are you masked the name bool in your top-level code.

> The input to the function in the larger program is the same as the first test in the small script that works -- "admin".  
>
> 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.
Importing is irrelevant when you hide the name inside your function. 
But since you don't specify what you mean by "broken," who knows if
that's relevant.  The preferred version of rstrip() is  a method of str
object.


>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 

DaveA



More information about the Tutor mailing list