Skip to content

Commit 72a8b53

Browse files
committed
name shadowing
1 parent 8b84bb9 commit 72a8b53

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

using-functions.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,49 @@ Unlike with `+`, the arguments don't need to be strings.
163163
>>>
164164
```
165165

166+
## Variables names and built-in things
167+
168+
In [the previous chapter](variables.md) we learned that `if` is not a
169+
valid variable name because it's a keyword.
170+
171+
```py
172+
>>> if = 123
173+
File "<stdin>", line 1
174+
if = 123
175+
^
176+
SyntaxError: invalid syntax
177+
>>>
178+
```
179+
180+
But `print` and `input` are not keywords, so can we use them as
181+
variable names?
182+
183+
```py
184+
>>> print = "hello"
185+
>>> print
186+
'hello'
187+
>>>
188+
```
189+
190+
We can, but there's a problem. Now we can't even do our hello world!
191+
192+
```py
193+
>>> print("Hello World!")
194+
Traceback (most recent call last):
195+
File "<stdin>", line 1, in <module>
196+
TypeError: 'str' object is not callable
197+
>>>
198+
```
199+
200+
The error message complains that strings aren't callable because we
201+
just set `print` to the string `'hello'` and now we're trying to call
202+
it like a function. As you can see, this is not a good idea at all.
203+
Most editors (including IDLE) display built-in functions with a special
204+
color so you don't need to worry about doing this accidentally.
205+
206+
Exit out of Python and start it again, and `print("Hello World!")`
207+
should work normally.
208+
166209
## Summary
167210

168211
- `function()` calls a function without any arguments, and
@@ -173,6 +216,7 @@ Unlike with `+`, the arguments don't need to be strings.
173216
and then does `stuff = the_return_value` and the return value ends
174217
up in x.
175218
- Python comes with `print` and `input`. They are built-in functions.
219+
- Avoid variable names that conflict with built-in functions.
176220

177221
***
178222

0 commit comments

Comments
 (0)