RE: What is wrong with this code?

2011-09-19 Thread Shambhu Rajak
I think you cannnot use "\" as normal string ,it’s a metacharacter, u can use 
it like this:
'\\begin{document}'

-Shambhu
-Original Message-
From: Steven D'Aprano [mailto:steve+comp.lang.pyt...@pearwood.info] 
Sent: Monday, September 19, 2011 3:31 AM
To: python-list@python.org
Subject: Re: What is wrong with this code?

On Sun, 18 Sep 2011 21:07:22 +, superhappyfuntime wrote:

> On 09-15-2011, Ulrich Eckhardt  wrote:
> 
>> superhappyfuntime wrote:
>>>  #this is antiWYSIWYG, an easy to learn cap for begginners to LaTeX.
> 
>> It's LaTeX, not Python.
> 
>> Uli
> 
> no, it's a cap for LaTeX written in python

If it's Python, it's no Python syntax I've ever seen before.


>>> here it is: = '\begin{document}'
  File "", line 1
here it is: = '\begin{document}'
  ^
SyntaxError: invalid syntax


How about if you start off by explaining what you think "a cap for LaTeX" 
means, or provide a link to something that will explain it? This is a 
Python list, and we don't necessarily know much about LaTeX.



-- 
Steven




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Killing threads (was Re: Cancel or timeout a long running regular expression)

2011-09-19 Thread Antoon Pardon
On Sun, Sep 18, 2011 at 07:35:01AM +1000, Chris Angelico wrote:
> On Sun, Sep 18, 2011 at 5:00 AM, Nobody  wrote:

> Forking a thread to discuss threads ahem.
> 
> Why is it that threads can't be killed? Do Python threads correspond
> to OS-provided threads (eg POSIX threads on Linux)? Every OS threading
> library I've seen has some way of killing threads, although I've not
> looked in detail into POSIX threads there (there seem to be two
> options, pthread_kill and pthread_cancel, that could be used, but I've
> not used either). If nothing else, it ought to be possible to
> implement a high level kill simply by setting a flag that the
> interpreter will inspect every few commands, the same way that
> KeyboardInterrupt is checked for.
> 
> Is it just that nobody's implemented it, or is there a good reason for
> avoiding offering this sort of thing?

Python has a half baked solution to this. If you go to

  http://docs.python.org/release/3.2.2/c-api/init.html

You will find the following:

int PyThreadState_SetAsyncExc(long id, PyObject *exc)

  Asynchronously raise an exception in a thread. The id argument is
the thread id of the target thread; exc is the exception object to be
raised. This function does not steal any references to exc. To prevent
naive misuse, you must write your own C extension to call this. Must be
called with the GIL held. Returns the number of thread states modified;
this is normally one, but will be zero if the thread id isn’t found. If
exc is NULL, the pending exception (if any) for the thread is cleared.
This raises no exceptions.

Some recipes can be found at:

  
http://www.google.com/search?ie=UTF-8&oe=utf-8&q=python+recipe+PyThreadState_SetAsyncExc

However it this doesn't work 100% correctly. Last time I tried
using this, it didn't work with an exception instance but
only with an execption class as parameter. There was a discussion at

  http://mail.python.org/pipermail/python-dev/2006-August/068158.html

about this. I don't know how it was finaly resolved.

-- 
Antoon Pardon
-- 
http://mail.python.org/mailman/listinfo/python-list


Operator commutativity

2011-09-19 Thread Henrik Faber
Hi there,

when I have a python class X which overloads an operator, I can use that
operator to do any operation for example with an integer

y = X() + 123

however, say I want the "+" operator to be commutative. Then

y = 123 + X()

should have the same result. However, since it does not call __add__ on
an instance of X, but on the int 123, this fails:

TypeError: unsupported operand type(s) for +: 'int' and 'X'

How can I make this commutative?

Best regards,
Henrik
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Operator commutativity

2011-09-19 Thread Arnaud Delobelle
On 19 September 2011 12:11, Henrik Faber  wrote:
> Hi there,
>
> when I have a python class X which overloads an operator, I can use that
> operator to do any operation for example with an integer
>
> y = X() + 123
>
> however, say I want the "+" operator to be commutative. Then
>
> y = 123 + X()
>
> should have the same result. However, since it does not call __add__ on
> an instance of X, but on the int 123, this fails:
>
> TypeError: unsupported operand type(s) for +: 'int' and 'X'
>
> How can I make this commutative?

Overload X.__radd__() as well

HTH

-- 
Arnaud
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Operator commutativity

2011-09-19 Thread Paul Rudin
Henrik Faber  writes:


> How can I make this commutative?

Incidentally - this isn't really about commutativity at all - the
question is how can you define both left and right versions of add,
irrespective of whether they yield the same result.

I think __radd__ is what you're after.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Operator commutativity

2011-09-19 Thread Duncan Booth
Henrik Faber  wrote:

> Hi there,
> 
> when I have a python class X which overloads an operator, I can use that
> operator to do any operation for example with an integer
> 
> y = X() + 123
> 
> however, say I want the "+" operator to be commutative. Then
> 
> y = 123 + X()
> 
> should have the same result. However, since it does not call __add__ on
> an instance of X, but on the int 123, this fails:
> 
> TypeError: unsupported operand type(s) for +: 'int' and 'X'
> 
> How can I make this commutative?
> 
By defining __radd__

>>> class X:
def __add__(self, other):
return "%r + %r" % (self, other)
def __radd__(self, other):
return "%r + %r" % (other, self)


>>> X() + 123
'<__main__.X object at 0x029C45B0> + 123'
>>> 123 + X()
'123 + <__main__.X object at 0x02101910>'


-- 
Duncan Booth http://kupuguy.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Operator commutativity

2011-09-19 Thread Henrik Faber
On 19.09.2011 13:23, Paul Rudin wrote:
> Henrik Faber  writes:
> 
>> How can I make this commutative?
> 
> Incidentally - this isn't really about commutativity at all - the
> question is how can you define both left and right versions of add,
> irrespective of whether they yield the same result.

Right. The operator+ in my case just happens to be commutative and I
wanted a language way to express this.

> I think __radd__ is what you're after.

It is, thank you very much - I knew there was some way to get this done
nicely. Perfect! :-)

Best regards,
Henrik
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Operator commutativity

2011-09-19 Thread Roy Smith
In article ,
 Henrik Faber  wrote:

> On 19.09.2011 13:23, Paul Rudin wrote:
> > Henrik Faber  writes:
> > 
> >> How can I make this commutative?
> > 
> > Incidentally - this isn't really about commutativity at all - the
> > question is how can you define both left and right versions of add,
> > irrespective of whether they yield the same result.
> 
> Right. The operator+ in my case just happens to be commutative and I
> wanted a language way to express this.
> 
> > I think __radd__ is what you're after.
> 
> It is, thank you very much - I knew there was some way to get this done
> nicely. Perfect! :-)

__radd__() only solves the problem if the left-hand operand has no 
__add__() method itself.

class C1:
def __add__(self, other):
print "C1.__add__()"
def __radd__(self, other):
print "C1.__radd__()"

class C2:
def __add__(self, other):
print "C2.__add__()"
def __radd__(self, other):
print "C2.__radd__()"

c1 = C1()
c2 = C2()

c1 + c2
c2 + c1

$ python radd.py
C1.__add__()
C2.__add__()
-- 
http://mail.python.org/mailman/listinfo/python-list


help needed on decimal formatting issue

2011-09-19 Thread Robin Becker
I'm not really very used to the decimal module so I'm asking here if any one can 
help me with a problem in a well known third party web framework


The code in question is

def format_number(value, max_digits, decimal_places):
"""
Formats a number into a string with the requisite number of digits and
decimal places.
"""
if isinstance(value, decimal.Decimal):
context = decimal.getcontext().copy()
context.prec = max_digits
return u'%s' % str(
 value.quantize(decimal.Decimal(".1") ** decimal_places,
   context=context))
else:
return u"%.*f" % (decimal_places, value)


we have set up decimal fields with max_digits=7 decimal_places=2 and 
max_digits=10, decimal_places=4. We are getting issues with quantize failing 
with the message 'quantize result has too many digits for current context'.


Anyhow, I believe that we need to adjust the above code so that the precision is 
actually set to


context.prec = max_digits+decimal_places

but I'm not certain that is right. Presumably the author thought that the fields 
could have large values of both max_digits and decimal_places. Initially I 
thought precision must be to do with decimal_places only, but changing

context.prec = decimal_places

did not fix the issue. Can someone enlighten me? The failing case for the 
original code was


format_number(Decimal('914146.80'),7,2)

with context.prec = decimal_places we failed differently with

format_number(Decimal('42.7571'),10,4)

so I adopted context.prec = max_digits+decimal_places and that seems to work. If 
this is indeed a proper fix I will send a bug report to the well known jazz 
based framework.

--
Robin Becker

--
http://mail.python.org/mailman/listinfo/python-list


Re: Operator commutativity

2011-09-19 Thread Ethan Furman

Roy Smith wrote:

In article ,
 Henrik Faber  wrote:


On 19.09.2011 13:23, Paul Rudin wrote:

Henrik Faber  writes:


How can I make this commutative?

Incidentally - this isn't really about commutativity at all - the
question is how can you define both left and right versions of add,
irrespective of whether they yield the same result.

Right. The operator+ in my case just happens to be commutative and I
wanted a language way to express this.


I think __radd__ is what you're after.

It is, thank you very much - I knew there was some way to get this done
nicely. Perfect! :-)


__radd__() only solves the problem if the left-hand operand has no 
__add__() method itself.


Only true if the left-hand operand is so ill-behaved it doesn't check to 
see if it makes sense to add itself to the right-hand operand.  If it 
doesn't know how, it should `return NotImplemented` -- Python will then 
try __radd__ on the left-hand operand.


Also, if the right-hand operand is a subclass of the left-hand operand 
then Python will try right-hand_operand.__radd__ first.


Now, if the left-hand operand *does* know how (or thinks it does, which 
could be another matter entirely), and the right-hand operand is *not* a 
subclass of the left-hand operand, then you are correct -- the 
right-hand operand wil not be called.


~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python bug in Windows 8--report now, or later?

2011-09-19 Thread Brian Curtin
On Sat, Sep 17, 2011 at 13:01, Kevin Walzer  wrote:
> I have been testing my Python application on the just-released developer
> preview of Windows 8 and have noted an error: the application does not
> create an app folder in the user's "application data" directory. This causes
> the app to crash on startup. Manually creating the directory solves the
> problem. Since the app uses an os.mkdir() call to create the directory, and
> since the app runs fine on Windows 7, my guess is that the bug lies
> somewhere in the interaction between Python (I'm using ActivePython 2.7) and
> Windows.
>
> Here's the relevant code:
>
>    #make preferences directory if it does not exist
>    def makePrefsDir(self):
>        self.appdir = os.path.join(os.path.join(os.environ['APPDATA'],
> 'MyApp'))
>        if not os.path.exists(self.appdir):
>            os.mkdir(self.appdir)
>
> I realize that this developer preview of Windows is still at somewhere
> between alpha- and beta-level, and it's possible things will get better.
> Should I wait to report this as a bug until Windows 8 is released, or do the
> Python developers test Python on pre-release versions of Windows?

First, is your application actually crashing, or does it just exit due
to an unhandled exception? I suspect the latter, so if that's true,
what's the exception and message?

You said "the application does not create an app folder in the user's
'application data' directory" -- what does this mean, or rather, what
is the specific folder you're expecting to have? If Python can't
create the directory but you can do it manually, there may be some
permission or access differences new to Windows 8. What does "echo
%APPDATA%" give you?

I haven't installed Windows 8 yet, but I'm planning to get it up and
running soon. If you submit issues to http://bugs.python.org,
hopefully with specific test cases that we can run and work with,
it'll be easier to track and fix. If you do that, add me to the nosy
list on the issues - tracker id: brian.curtin, I'm one of the Windows
people around there.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Operator commutativity

2011-09-19 Thread Terry Reedy

On 9/19/2011 8:48 AM, Ethan Furman wrote:

Roy Smith wrote:



__radd__() only solves the problem if the left-hand operand has no
__add__() method itself.


Only true if the left-hand operand is so ill-behaved it doesn't check to
see if it makes sense to add itself to the right-hand operand. If it
doesn't know how, it should `return NotImplemented` -- Python will then
try __radd__ on the left-hand operand.

Also, if the right-hand operand is a subclass of the left-hand operand
then Python will try right-hand_operand.__radd__ first.


The builtin classes like int are (should be, sans bug) well-behaved.


Now, if the left-hand operand *does* know how (or thinks it does, which
could be another matter entirely), and the right-hand operand is *not* a
subclass of the left-hand operand, then you are correct -- the
right-hand operand wil not be called.


So the potential problems arise with two user classes.

--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list


help for the parse of encrypted excel

2011-09-19 Thread Christian Ren
I used xlrd library for the parse of excel before. But now, I
encounter a problem that the file has been encrypted for some security
reason. On the official website, i found "xlrd will not attempt to
decode password-protected (encrypted) files. " :((
And I also tried another library called pyExcelerator, Unfortunately,
it failed all the same.
Is there anybody can tell me what's the solution to the parse of
encrypted excel? Thanks in advance.
(PS: for the user experience reason, I don't hope to save this file as
another copy)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help needed on decimal formatting issue

2011-09-19 Thread Mark Dickinson
On Sep 19, 1:42 pm, Robin Becker  wrote:
> I'm not really very used to the decimal module so I'm asking here if any one 
> can
> help me with a problem in a well known third party web framework
>
> The code in question is
>
> def format_number(value, max_digits, decimal_places):
>      """
>      Formats a number into a string with the requisite number of digits and
>      decimal places.
>      """
>      if isinstance(value, decimal.Decimal):
>          context = decimal.getcontext().copy()
>          context.prec = max_digits
>          return u'%s' % str(
>           value.quantize(decimal.Decimal(".1") ** decimal_places,
>                         context=context))
>      else:
>          return u"%.*f" % (decimal_places, value)

What's the meaning of the 'max_digits' argument here?  Are you
guaranteed that the incoming value is smaller than 10**max_digits in
absolute value?

If so, then a precision of max_digits + decimal_places + 1 should be
enough.  The +1 is there to cover the corner case where a value close
to 10**max_digits is rounded up to 10**max_digits by the quantize
operation.

BTW, that's a fairly horrible way of creating the first argument to
the quantize method, too.  It would be more efficient to do something
like:

>>> decimal_places = 2
>>> decimal.Decimal('0.{}1'.format('0'*(decimal_places-1)))
Decimal('0.01')

(perhaps with suitable special-casing for the case where
decimal_places <= 0;  not sure whether this applies in your context).

--
Mark
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Operator commutativity

2011-09-19 Thread Westley Martínez
On Mon, Sep 19, 2011 at 01:11:51PM +0200, Henrik Faber wrote:
> Hi there,
> 
> when I have a python class X which overloads an operator, I can use that
> operator to do any operation for example with an integer
> 
> y = X() + 123
> 
> however, say I want the "+" operator to be commutative. Then
> 
> y = 123 + X()
> 
> should have the same result. However, since it does not call __add__ on
> an instance of X, but on the int 123, this fails:
> 
> TypeError: unsupported operand type(s) for +: 'int' and 'X'
> 
> How can I make this commutative?
> 
> Best regards,
> Henri

def __radd__(self, other):
return self.__add__(self, other)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python bug in Windows 8--report now, or later?

2011-09-19 Thread Andrew Berg
On 2011.09.19 09:00 AM, Brian Curtin wrote:
> You said "the application does not create an app folder in the user's
> 'application data' directory" -- what does this mean, or rather, what
> is the specific folder you're expecting to have? If Python can't
> create the directory but you can do it manually, there may be some
> permission or access differences new to Windows 8. What does "echo
> %APPDATA%" give you?
I booted up the Win8 dev preview in a VM and os.environ['appdata'] gives
me the same result it would for Windows 7. Perhaps the problem lies in
the os.path.exists() call (that is, Win8 and Win7 react differently to
this call). I personally would try to create the directory and then
catch either a WindowsError (error 183) or an OSError (error 17) if the
directory already exists. I might play around with this later and post
some results.

-- 
CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 6.0.2
PGP/GPG Public Key ID: 0xF88E034060A78FCB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Killing threads (was Re: Cancel or timeout a long running regular expression)

2011-09-19 Thread Nobody
On Sun, 18 Sep 2011 23:41:29 -0600, Ian Kelly wrote:

>> If the transaction object doesn't get its commit() called, it does no
>> actions at all, thus eliminating all issues of locks.
> 
> And what if the thread gets killed in the middle of the commit?

The essence of a commit is that it involves an atomic operation, for which
there is no "middle".

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Killing threads (was Re: Cancel or timeout a long running regular expression)

2011-09-19 Thread Ian Kelly
On Mon, Sep 19, 2011 at 12:25 AM, Chris Angelico  wrote:
> On Mon, Sep 19, 2011 at 3:41 PM, Ian Kelly  wrote:
>> And what if the thread gets killed in the middle of the commit?
>>
>
> Database managers solved this problem years ago. It's not done by
> preventing death until you're done - death can come from someone
> brutally pulling out your power cord. There's no "except
> PowerCordRemoved" to protect you from that!

I'm aware of that.  I'm not saying it's impossible, just that the
example you gave is over-simplified, as writing atomic transactional
logic is a rather complex topic.  There may be an existing Python
library to handle this, but I'm not aware of one.

"PowerCordRemoved" is not relevant here, as that would kill the entire
process, which renders the issue of broken shared data within a
continuing process rather moot.

Cheers,
Ian
-- 
http://mail.python.org/mailman/listinfo/python-list


logging.config and {-style formatting

2011-09-19 Thread Andrew Berg
Is it possible to use {-style formatting with a logging config file? I
can add style='{' to a logging.Formatter() call and it works fine, but I
see no way of doing this from a config file. I tried adding a style
option in the config file, but it has no effect. I see no mention of the
{-style in the logging.config docs, so am I right to assume {-style
formatting is not implemented in logging.config?

-- 
CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 6.0.2
-- 
http://mail.python.org/mailman/listinfo/python-list


Dynamically Cause A Function To Return

2011-09-19 Thread Jordan Evans
I want dynamically place the 'return' statement in a function via user input
or achieve the same through some other means.  If some other means, the user
must be able initiate this at runtime during a raw_input().  This is what I
have so far, this would be an awesome command line debugging tool if I can
get it to work.

def b(label="", *args):
"""Used to create breaks for debugging.  Will break the function or
continue the function it is place within based on user input.  Has as a
input loop for querying variables and executing code before a break or a
continue."""
print label+":",
for arg in args:
print str(arg),
if len(args):
print
x = ""
while x != ".":
command = raw_input()
try:
exec command
except:
pass
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: ActivePython 3.2.2.3 is now available

2011-09-19 Thread Sridhar Ratnakumar
ActiveState is pleased to announce ActivePython 3.2.2.3, a complete, 
ready-to-install binary distribution of Python 3.2.

  http://www.activestate.com/activepython/downloads


What's New in ActivePython-3.2.2.3
==

New Features & Upgrades
---

- Upgrade to Python 3.2.2 (`release notes
 `__)
- [Windows] Security upgrade to openssl-1.0.0e
- Upgraded the following packages:

 - Distribute-0.6.21
 - virtualenv-1.6.4

What is ActivePython?
=

ActivePython is ActiveState's binary distribution of Python. Builds for 
Windows, Mac OS X, Linux are made freely available. Solaris, HP-UX and AIX 
builds, and access to older versions are available in ActivePython Business, 
Enterprise and OEM editions:

  http://www.activestate.com/python

ActivePython includes the Python core and the many core extensions: zlib and 
bzip2 for data compression, the Berkeley DB (bsddb) and SQLite (sqlite3) 
database libraries, OpenSSL bindings for HTTPS support, the Tix GUI widgets for 
Tkinter, ElementTree for XML processing, ctypes (on supported platforms) for 
low-level library access, and others. The Windows distribution ships with 
PyWin32 -- a suite of Windows tools developed by Mark Hammond, including 
bindings to the Win32 API and Windows COM.

ActivePython also includes a binary package manager for Python (PyPM) that can 
be used to install packages much easily. For example:

  C:\>pypm install numpy
  [...]

  C:\>python
  >>> import numpy.linalg
  >>>

See this page for full details:

  http://docs.activestate.com/activepython/3.2/whatsincluded.html

As well, ActivePython ships with a wealth of documentation for both new and 
experienced Python programmers. In addition to the core Python docs, 
ActivePython includes the "What's New in Python" series, "Dive into Python", 
the Python FAQs & HOWTOs, and the Python Enhancement Proposals (PEPs).

An online version of the docs can be found here:

  http://docs.activestate.com/activepython/3.2/

We would welcome any and all feedback to:

  activepython-feedb...@activestate.com

Please file bugs against ActivePython at:

  http://bugs.activestate.com/enter_bug.cgi?product=ActivePython

Supported Platforms
===

ActivePython is available for the following platforms:

- Windows (x86 and x64)
- Mac OS X (x86 and x86_64; 10.5+)
- Linux (x86 and x86_64)

- Solaris/SPARC (32-bit and 64-bit) (Business, Enterprise or OEM edition only)
- Solaris/x86 (32-bit) (Business, Enterprise or OEM edition only)
- HP-UX/PA-RISC (32-bit) (Business, Enterprise or OEM edition only)
- HP-UX/IA-64 (32-bit and 64-bit) (Enterprise or OEM edition only)
- AIX/PowerPC (32-bit and 64-bit) (Business, Enterprise or OEM edition only)

More information about the Business Edition can be found here:

  http://www.activestate.com/business-edition

Custom builds are available in the Enterprise Edition:

  http://www.activestate.com/enterprise-edition

Thanks, and enjoy!

The Python Team

--
Sridhar Ratnakumar
sridharr at activestate.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Killing threads (was Re: Cancel or timeout a long running regular expression)

2011-09-19 Thread Chris Angelico
On Tue, Sep 20, 2011 at 8:04 AM, Ian Kelly  wrote:
> "PowerCordRemoved" is not relevant here, as that would kill the entire
> process, which renders the issue of broken shared data within a
> continuing process rather moot.
>

Assuming that the "broken shared data" exists only in RAM on one
single machine, and has no impact on the state of anything on the hard
disk or on any other computer, yes.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Killing threads (was Re: Cancel or timeout a long running regular expression)

2011-09-19 Thread Gregory Ewing

Antoon Pardon wrote:


int PyThreadState_SetAsyncExc(long id, PyObject *exc)

To prevent
naive misuse, you must write your own C extension to call this.


Not if we use ctypes! Muahahahaaa!

--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: Operator commutativity

2011-09-19 Thread Steven D'Aprano
Westley Martínez wrote:

> def __radd__(self, other):
> return self.__add__(self, other)

Which, inside a class, can be simplified to:

__radd__ = __add__



-- 
Steven

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Operator commutativity

2011-09-19 Thread Roy Smith
In article <4e77eae1$0$29978$c3e8da3$54964...@news.astraweb.com>,
 Steven D'Aprano  wrote:

> Westley Martínez wrote:
> 
> > def __radd__(self, other):
> > return self.__add__(self, other)
> 
> Which, inside a class, can be simplified to:
> 
> __radd__ = __add__

Ooh, I could see that leading to some weird diagnostics.  For example:

class Foo:
def __add__(self, other):
raise Exception

__radd__ = __add__

f1 = Foo()
print 1 + f1

produces:

./add.py
Traceback (most recent call last):
  File "./add.py", line 11, in 
print 1 + f1
  File "./add.py", line 5, in __add__
raise Exception
Exception

which leaves the user wondering why __add__() was called when clearly 
__radd__() should have been.  The way Westley wrote it (modulo fixing 
the __add__() call signature) produces:

./add.py
Traceback (most recent call last):
  File "./add.py", line 11, in 
print 1 + f1
  File "./add.py", line 8, in __radd__
return self.__add__(other)
  File "./add.py", line 5, in __add__
raise Exception
Exception

which at least is a stack trace that shows that __radd__() was called.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Operator commutativity

2011-09-19 Thread Westley Martínez
On Mon, Sep 19, 2011 at 10:26:30PM -0400, Roy Smith wrote:
> In article <4e77eae1$0$29978$c3e8da3$54964...@news.astraweb.com>,
>  Steven D'Aprano  wrote:
> 
> > Westley Mart??nez wrote:
> > 
> > > def __radd__(self, other):
> > > return self.__add__(self, other)
> > 
> > Which, inside a class, can be simplified to:
> > 
> > __radd__ = __add__
> 
> Ooh, I could see that leading to some weird diagnostics.  For example:
> 
> class Foo:
> def __add__(self, other):
> raise Exception
> 
> __radd__ = __add__
> 
> f1 = Foo()
> print 1 + f1
> 
> produces:
> 
> ./add.py
> Traceback (most recent call last):
>   File "./add.py", line 11, in 
> print 1 + f1
>   File "./add.py", line 5, in __add__
> raise Exception
> Exception
> 
> which leaves the user wondering why __add__() was called when clearly 
> __radd__() should have been.  The way Westley wrote it (modulo fixing 
> the __add__() call signature) produces:
> 
> ./add.py
> Traceback (most recent call last):
>   File "./add.py", line 11, in 
> print 1 + f1
>   File "./add.py", line 8, in __radd__
> return self.__add__(other)
>   File "./add.py", line 5, in __add__
> raise Exception
> Exception
> 
> which at least is a stack trace that shows that __radd__() was called.

Calling __radd__ = __add__ simply creates a reference to __add__ named
__radd__, it doesn't create a new method.
-- 
http://mail.python.org/mailman/listinfo/python-list