Easy questions from a python beginner

Thomas Jollans thomas at jollans.com
Fri Jul 23 14:07:34 EDT 2010


On 07/23/2010 07:13 PM, Thomas Jollans wrote:
> On 07/23/2010 12:34 AM, wheres pythonmonks wrote:
>> 2.  Is there a better way to loopup by id?  I'm not very familiar with
>> sys.exc_info, but creating the id->name hash each time seems like
>> overkill.
> 
> I just had the most horrendous idea. Really, looking up objects by ID,
> or even swapping two objects, isn't that difficult if you do some C
> black magic. Don't try this in front of the kids.
> 
> I wrote a little module, called "hell":
> 
> Python 3.1.2 (release31-maint, Jul  8 2010, 09:18:08)
> [GCC 4.4.4] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>>
>>>> from hell import swap, getptr
>>>> dir
> <built-in function dir>
>>>> len
> <built-in function len>
>>>> swap(dir, len)
>>>> dir
> <built-in function len>
>>>> len
> <built-in function dir>
>>>> a = "this was a"
>>>> b = "this was b, hell yeah"
>>>> (a, b, id(a), id(b))
> ('this was a', 'this was b, hell yeah', 32417752, 32418144)
>>>> tpl = (a, b, id(a), id(b))
>>>> tpl
> ('this was a', 'this was b, hell yeah', 32417752, 32418144)
>>>> swap(a, b)
>>>> tpl
> ('this was b, hell yeah', 'this was a', 32417752, 32418144)
>>>> getptr(32417752)
> 'this was b, hell yeah'
>>>>


The great thing about this is that it can illustrate, in a very perverse
manner, some lovely facets of Python. For example: combined hash and
equality checks when accessing sets and dicts:

Python 3.1.2 (release31-maint, Jul  8 2010, 09:18:08)
[GCC 4.4.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from hell import swap
>>> s1 = 'string1'
>>> s2 = 'string2'
>>> s = {s1, s2}
>>> swap(s1, s2)
>>> s
{'string1', 'string2'}
>>> s1 in s
False
>>> s2 in s
False
>>> s1 in list(s)
True
>>> s2 in list(s)
True
>>>




More information about the Python-list mailing list