osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

OT: This Swift thing


On Fri, Jun 6, 2014 at 1:16 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Fri, 06 Jun 2014 09:21:26 +1000, Chris Angelico wrote:
>
>> On Fri, Jun 6, 2014 at 9:02 AM, Sturla Molden <sturla.molden at gmail.com>
>> wrote:
>>> You cannot spoof the type of an object in Python.
>>
>> Not without fiddling around. Python 3.4 on win32:
> [...]
>>>>> x = Foo()
>>>>> x.spam()
>> <__main__.Foo object at 0x0169AB10> spams
>>>>> x.__class__ = Bar
>>>>> x.spam()
>> <__main__.Bar object at 0x0169AB10> eats spam
>>
>> The thing has the same id (as shown in its repr), but has changed class.
>
> That's not spoofing types. That is a language feature: within limits,
> instances can change their type. It has been around for a long, long
> time, back to Python 1.5 or older, and it has real-world use-cases:
>
> http://code.activestate.com/recipes/68429-ring-buffer/

True, it's not *spoofing*, in the same way that this C code is:

float x = 3.14159;
int y = *(int *)&x;

And I'm aware that it's a language feature (why else would it be
specifically limited with a clear exception when you try to assign
something you can't?). So's the C-level fiddling, albeit for different
reasons and in different ways. Anyway, I was broadly agreeing -
Python's type system is "objects have types", rather than "stuff is in
memory and data types are just how you look at it". It just happens to
be possible to fiddle if you want to :)

ChrisA