Override 'and' and 'or'
Diez B. Roggisch
deets at nospam.web.de
Sun Oct 7 11:57:31 EDT 2007
Kay Schluehr schrieb:
> On Oct 7, 4:48 pm, Dekker <m.aschwan... at gmail.com> wrote:
>> On 7 Okt., 16:19, Steven D'Aprano <st... at REMOVE-THIS-
>>
>> cybersource.com.au> wrote:
>>> On Sun, 07 Oct 2007 13:52:15 +0000, Dekker wrote:
>>>> Is it possible to override 'and' and/or 'or'?
>>> Not without hacking the Python source code, in which case what you've got
>>> is no longer Python.
>>> Why do you want to do so?
>>> --
>>> Steven.
>> Well I think it is not possible what I wanted to achieve. By
>> overriding the "and" and "or" keyword I wanted to return a new object:
>>
>> SqlValueInt(4) and SqlValueInt(5) --> SqlOpAnd(SqlValueInt(4),
>> SqlValueInt(5))
>>
>> This is only possible for: +, -, /, *, >, >=, ...
>>
>> Well... I have to live with the (binary) __and__, __or__ option and
>> the user has to write:
>>
>> SqlValueInt(4) & SqlValueInt(5) --> SqlOpAnd(SqlValueInt(4),
>> SqlValueInt(5))
>>
>> Thanks for your input, but __nonzero__ is not of any help in this
>> case... I want to abuse the "magic" functions for some transformations
>> and not some evaluation.
>>
>> Marco
>
> You can see what "and" and "or" are actually doing:
>
> import dis
> dis.dis(lambda: x or y and z)
>
> 1 0 LOAD_GLOBAL 0 (x)
> 3 JUMP_IF_TRUE 11 (to 17)
> 6 POP_TOP
> 7 LOAD_GLOBAL 1 (y)
> 10 JUMP_IF_FALSE 4 (to 17)
> 13 POP_TOP
> 14 LOAD_GLOBAL 2 (z)
> >> 17 RETURN_VALUE
>
> Here you can see nicely that they are not implemented as specialized
> opcodes but being compiled to jumps. This causes their lazy nature. If
Very cool, didn't know that.
Diez
More information about the Python-list
mailing list