15

Why is this giving me an error?

>>> variable = str(21)

Traceback (most recent call last):
  File "<pyshell#101>", line 1, in <module>
    variable = str(21)
TypeError: 'str' object is not callable
smci
  • 32,567
  • 20
  • 113
  • 146
blueplastic
  • 201
  • 1
  • 2
  • 4
  • 4
    did you name a variable "str"? – Wooble Aug 15 '11 at 16:16
  • 2
    Did you define another string variable and assign it to a variable `str` ? because doing so you end up shadowing the builtin function `str()` e.g: `str = 'test'; print(str(124))`. – mouad Aug 15 '11 at 16:16
  • 2
    The downvotes are misplaced. Most of us have shadowed builtins, when learning. Look how many code examples out there with `list = [...]`. I updated the title of this question. – smci Apr 09 '14 at 10:05

2 Answers2

41

That code alone won't give you an error. For example, I just tried this:

~ $ python3.2
>>> variable = str(21)
>>> variable
'21'

Somewhere in your code you're defining that str = something else, masking the builtin definition of str. Remove that and your code will work fine.

Jeremy
  • 1
  • 85
  • 340
  • 366
14

Because you've probably overwritten the str function by calling your own variable str.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • I think you might be right. I closed out of my IDLE session (which had a lot of earlier code samples I found online loaded), and now I can use the built-in str function properly. One of those earlier code samples must have done something quirky to the BIF str(). Thanks! – blueplastic Aug 15 '11 at 16:23