"Don't rebind built-in names*" - it confuses readers
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Wed Jun 12 21:01:12 EDT 2013
On Wed, 12 Jun 2013 17:04:48 -0700, Mark Janssen wrote:
>> Apart from Erlang, got any other examples? Because it seems to me that
>> in languages with nested scopes or namespaces, shadowing higher levels
>> is exactly the right thing to do.
>
> Really?
>
>>>> int="five"
>>>> [int(i) for i in ["1","2","3"]]
> TypeError: str is not callable
Yes, really. Not for the example shown above, of course, that's pretty
useless. But one might define a custom int() function, or more common,
you want to define a local variable x without caring whether or not there
is a global variable x.
If you, the programmer, have a good reason for re-defining int as the
string "five", then presumably you *wanted* to get that TypeError. If
not, then it's simply a bug, like any other bug: that you get when you
use the wrong name:
x = 23 # I want x to equal 23, always and forever.
x = 42 # I don't actually want to rebind x, but I can't help myself.
assert x == 23 # This now fails, because I am an idiot.
Should we conclude that, because somebody might accidentally assign a
value to a name without considering the consequences, that assigning
values to names should be forbidden? No, of course not. The solution is
to think before you code, or fix the bug afterwards.
Shadowing builtins is confusing to newbies, I get that. But anyone with
even a modicum of experience will be able to deal with such errors
trivially. If you (generic you) cannot work out what is going on, then
you're not a Python programmer. You're a Python dabbler.
> Now how are you going to get the original int type back?
Trivial. Here are three ways:
py> int = "five"
py> int
'five'
py> del int
py> int("42")
42
Or:
py> int = "five"
py> int
'five'
py> type(5)("42")
42
Or:
py> int = "five"
py> import builtins # Use __builtin__ in Python 2.
py> builtins.int("42")
42
--
Steven
More information about the Python-list
mailing list