anomaly

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun May 10 23:19:30 EDT 2015


On Mon, 11 May 2015 03:28 am, Gary Herron wrote:

> On 05/10/2015 09:48 AM, Rustom Mody wrote:
>> On Sunday, May 10, 2015 at 10:14:36 PM UTC+5:30, Ian wrote:
>>> On Sun, May 10, 2015 at 10:34 AM, Mark Rosenblitt-Janssen wrote:
>>>> Here's something that might be wrong in Python (tried on v2.7):
>>>>
>>>>>>> class int(str): pass
>>> This defines a new class named "int" that is a subclass of str. It has
>>> no relation to the builtin class int.
>>>
>>>>>>> int(3)
>>>> '3'
>>> This creates an instance of the above "int" class, which is basically
>>> equivalent to calling "str(3)".
>>>
>>> Were you expecting a different result?
>> In C (family) languages int is a keyword
>>  From that pov this is completely bizarre
> 
> Not really.  Expecting Python to act like C family languages *is* bizarre.

It's not really *bizarre* to expect that standard functions and types are
reserved words. That applies to many languages other than C, and is not
unique to the C family. E.g. it also applies to Fortran, and the Algol
family of languages.

There are advantages and disadvantages to allowing standard names be
redefined, and it should not surprise us that someone coming from another
language may be taken aback by the fact that

str = 23

doesn't give an error.

What is funny is that one might think it is a *bug* rather than a deliberate
feature, or perhaps misfeature. Python is well over 20 years old. If int
was intended to be a keyword, someone would have noticed by now :-)


> Common Python thought::  "We're all adults here."    If you want to
> override a builtin within your own namespace, who are we to stop you?
> Besides, it's still available as __builtins__.int  (unless you've also
> overridden that).

Don't use __builtins__ that is a private implementation detail. The correct
way to access the built-in namespace explicitly is:


import __builtin__ # Python 2
import builtins # Python 3




-- 
Steven




More information about the Python-list mailing list