Re: Comparison with False - something I don't understand

2010-12-03 Thread Tim Harig
On 2010-12-03, Paul Rubin  wrote:
> Steven D'Aprano  writes:
>>> There are better ways to handle errors than Python's exception system.
>> I'm curious -- what ways would they be?
>> I'm aware of three general exception handling techniques: ...
>> What else is there?
>
> The Erlang approach is to chop the application into a lot of very
> lightweight processes, and let any process that encounters an error
> simply crash.  A monitoring process notices the crashed process and
> restarts it.  There is a "supervision tree" of uber-monitor processes
> that restart crashed monitor proceses.  I haven't programmed in that
> style myself and I'm not persuaded that it's better than what Python
> does, but I think it's different from the stuff on your list, which is

Erlang also offers an exception syntax almost identical to Python's for use
within a single process.

What makes Erlang's supervisor mode of error handling superior is that it
works for more then just the current vm.  If a process throws an exception,
the supervisor catches and handles it.  If a vm dies, a supervisor from
another vm takes over.  If an entire computer dies, a supervisor on another
computer takes over.  OTP provides some extremely advanced support for
supervisory structures.

> an answer to your "what else is there".  I do know that they write some
> complex, very high reliability systems (phone switches) in Erlang.

Erlang isn't what I would call a very general purpose programming language
like Python; but, if you want to build highly scalable and/or highly
available systemes, there really isn't anything else that comes close
to it.  I am not really a huge fan of the purely functional nature of
the language; but, light weight processes using the actor model is the
way to go for concurrent processing.

The BEAM virtual machine is also a powerful system with its ability to
patch systems on the fly.  It has start to become the target for other
languages.  I know of two that are in current developement.  I wouldn't
mind seeing a version of Python that could leverage the power of the
BEAM vm.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparison with False - something I don't understand

2010-12-03 Thread Mel
Harishankar wrote:

> I think I understand the general trend of what you're saying. It
> definitely requires a mindset change. I still feel that user-defined
> exception classes might not be the way, but maybe I should allow the
> built-in exceptions which are thrown by library functions to follow its
> natural path upwards till it reaches the top level where it could be
> handled.

User-defined exception classes are no big deal, and I think they're helpful.  
At the minimum, they're just a few lines in a module, e.g.:

class SumpError (StandardError): '''Errors raised by the SUMP client.'''
class SumpIdError (SumpError): '''The wrong string was returned by an ID 
request.'''
class SumpFlagsError (SumpError): '''Illegal combination of flags.'''
class SumpStageError (SumpError): '''Illegal trigger stage setting.'''

This is from a module to drive some special hardware through a serial 
connection.  At this stage in development, I don't even have try/except 
statements for these.  It's enough that some typo will not silently put the 
hardware into an illegal state, and instead will report

Traceback (most recent call last):
  File "logic_sniffer.py", line 184, in OnDeviceCapture
set_sump_options (grabber)
  File "logic_sniffer.py", line 21, in set_sump_options
sump.set_flags (demux=True, filter=True, channel_groups=0x0, 
external=False, inverted=False) # only 1 channel group
  File "/home/mwilson/sandbox/sump-analyzer/sump.py", line 160, in set_flags
raise SumpFlagsError
sump.SumpFlagsError

Because these are subclasses of StandardError, they'll be caught by any 
`except StandardError`, which may or may not turn out to be a mistake.

Once development is done, try/except for these will be in some window 
methods as part of a wxPython GUI, several call levels above the code that 
would raise the exceptions, up where a human user would take steps to change 
the way things are being done, or submit a bug report (more likely), or 
something.

> Maybe I should handle the error only at the highest level (UI level)
> rather than returning False to flag errors.
> 
> One of the reasons why I feared to do this is because I need to know each
> and every exception that might be thrown by the function and litter my
> top-level code with too many exception handlers.

The advantage to the exceptions, is that they only need to be recognized and 
caught and handled at the UI level.  They don't have to be recognized and 
passed back up the call chain from level to level till they get to the right 
place -- the way out-of-band error returns have to be.

Mel.

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


Exception handling in Python 3.x

2010-12-03 Thread Steven D'Aprano
Consider the following common exception handling idiom:

def func(iterable):
it = iter(iterable)
try:
x = next(it)
except StopIteration:
raise ValueError("can't process empty iterable")
print(x)

The intention is:

* detect an empty iterator by catching StopIteration;
* if the iterator is empty, raise a ValueError;
* otherwise process the iterator.

Note that StopIteration is an internal detail of no relevance whatsoever 
to the caller. Expose this is unnecessary at best and confusing at worst.


In Python 2.6 this idiom works as intended:

>>> func([])
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 6, in func
ValueError: can't process empty iterable

There is no sign of the StopIteration, and nor should there be.

But Python 3.1 changes this behaviour, exposing the unimportant 
StopIteration and leading to a more complicated and confusing traceback:

>>> func([])
Traceback (most recent call last):
  File "", line 4, in func
StopIteration

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "", line 1, in 
  File "", line 6, in func
ValueError: can't process empty iterable


I understand the rational of this approach -- it is to assist in 
debugging code where the except block is buggy and raises an error. But a 
deliberate and explicit call to raise is not a buggy except block. It is 
terribly inappropriate for the common use-case of catching one exception 
and substituting another.

I note that the PEP explicitly notes this use-case, but merely sweeps it 
under the carpet:

Open Issue: Suppressing Context
As written, this PEP makes it impossible to suppress '__context__',
since setting exc.__context__ to None in an 'except' or 'finally'
clause will only result in it being set again when exc is raised.

http://www.python.org/dev/peps/pep-3134/


Apart from this horrible idiom:

def func(iterable):
it = iter(iterable)
failed = False
try:
x = next(it)
except StopIteration:
failed = True
if failed:
raise ValueError("can't process empty iterable")
print(x)


or similar, is there really no way to avoid these chained exceptions?



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


Re: Reading by positions plain text files

2010-12-03 Thread javivd
On Dec 1, 3:15 am, Tim Harig  wrote:
> On 2010-12-01, javivd  wrote:
>
>
>
> > On Nov 30, 11:43 pm, Tim Harig  wrote:
> >> On 2010-11-30, javivd  wrote:
>
> >> > I have a case now in wich another file has been provided (besides the
> >> > database) that tells me in wich column of the file is every variable,
> >> > because there isn't any blank or tab character that separates the
> >> > variables, they are stick together. This second file specify the
> >> > variable name and his position:
>
> >> > VARIABLE NAME      POSITION (COLUMN) IN FILE
> >> > var_name_1                 123-123
> >> > var_name_2                 124-125
> >> > var_name_3                 126-126
> >> > ..
> >> > ..
> >> > var_name_N                 512-513 (last positions)
>
> >> I am unclear on the format of these positions.  They do not look like
> >> what I would expect from absolute references in the data.  For instance,
> >> 123-123 may only contain one byte??? which could change for different
> >> encodings and how you mark line endings.  Frankly, the use of the
> >> world columns in the header suggests that the data *is* separated by
> >> line endings rather then absolute position and the position refers to
> >> the line number. In which case, you can use splitlines() to break up
> >> the data and then address the proper line by index.  Nevertheless,
> >> you can use file.seek() to move to an absolute offset in the file,
> >> if that really is what you are looking for.
>
> > I work in a survey research firm. the data im talking about has a lot
> > of 0-1 variables, meaning yes or no of a lot of questions. so only one
> > position of a character is needed (not byte), explaining the 123-123
> > kind of positions of a lot of variables.
>
> Then file.seek() is what you are looking for; but, you need to be aware of
> line endings and encodings as indicated.  Make sure that you open the file
> using whatever encoding was used when it was generated or you could have
> problems with multibyte characters affecting the offsets.

Ok, I will try it and let you know. Thanks all!!
-- 
http://mail.python.org/mailman/listinfo/python-list


is id(self) constant over an object lifetime ?

2010-12-03 Thread Jean-Michel Pichavant

Hello fellows,

I would need a unique internal identifier to an object. Can I use the 
object python id ?


class Foo:
   def getUniqueIdentifier():
  return id(self)


This id needs to be unique and constant over the python process lifetime.

JM

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


Re: is id(self) constant over an object lifetime ?

2010-12-03 Thread Jean-Michel Pichavant

Jean-Michel Pichavant wrote:

Hello fellows,

I would need a unique internal identifier to an object. Can I use the 
object python id ?


class Foo:
   def getUniqueIdentifier():
  return id(self)


This id needs to be unique and constant over the python process lifetime.

JM


erratum

python process lifetime => object lifetime
--
http://mail.python.org/mailman/listinfo/python-list


Re: is id(self) constant over an object lifetime ?

2010-12-03 Thread Adam Tauno Williams
On Fri, 2010-12-03 at 14:44 +0100, Jean-Michel Pichavant wrote: 
> Hello fellows,
> I would need a unique internal identifier to an object. Can I use the 
> object python id ?
> class Foo:
> def getUniqueIdentifier():
>return id(self)
> This id needs to be unique and constant over the python process lifetime.




Return the “identity” of an object. This is an integer (or long integer)
which is guaranteed to be unique and constant for this object during its
lifetime. Two objects with non-overlapping lifetimes may have the same
id() value.


Of course, "lifetime" is an interesting concept.  If an object is
serializable then this id cannot be used as an idempotent value.

Personally I would never use this; if an object needs an idempotent
value - create one.  "import uuid"

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


Re: is id(self) constant over an object lifetime ?

2010-12-03 Thread Jean-Michel Pichavant

Jean-Michel Pichavant wrote:

Hello fellows,

I would need a unique internal identifier to an object. Can I use the 
object python id ?


class Foo:
def getUniqueIdentifier():
return id(self)


This id needs to be unique and constant over the python process lifetime.

JM


sorry guys

"

id(/object/)¶ 

   Return the “identity” of an object. This is an integer (or long
   integer) which is guaranteed to be unique and constant for this
   object during its lifetime. Two objects with non-overlapping
   lifetimes may have the same id()
    value.

"


Next time I promise to look at the doc before actually asking the 
question here :)


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


Python assignments

2010-12-03 Thread Sverker Nilsson
Dear friends,

This is Sverker from Sweden. You probably know me better as the guy
who made Guppy/Heapy:  http://guppy-pe.sf.net

I am currently in the process of preparing version 0.1.10 with support
for Python 2.7. I will let you know when it is updated.

For those who don’t know, I work as a consultant and I am looking for
new assignments and I really wish to work with Heapy/Python instead of
regular programming in eg Java or C++.

Therefore I was wondering if any of you know any companies in the
States or anywhere else that need my services.

Further information about who I am and what I can do you can find on
my website:

http://sncs.se

I appreciate all advice and information you can provide me with.

So long my friends,

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


Re: is id(self) constant over an object lifetime ?

2010-12-03 Thread Jean-Michel Pichavant

Adam Tauno Williams wrote:
On Fri, 2010-12-03 at 14:44 +0100, Jean-Michel Pichavant wrote: 
  

Hello fellows,
I would need a unique internal identifier to an object. Can I use the 
object python id ?

class Foo:
def getUniqueIdentifier():
   return id(self)
This id needs to be unique and constant over the python process lifetime.






Return the “identity” of an object. This is an integer (or long integer)
which is guaranteed to be unique and constant for this object during its
lifetime. Two objects with non-overlapping lifetimes may have the same
id() value.


Of course, "lifetime" is an interesting concept.  If an object is
serializable then this id cannot be used as an idempotent value.

Personally I would never use this; if an object needs an idempotent
value - create one.  "import uuid"

  

Yep I saw that on the doc sorry for asking here before checking it.
Anyway your uuid is an awesome suggestion.

However since I'll need to send the id over xmlrpc, it needs to be 
marshallable, so I would need to send uuid1().hex, or something liek that.


JM

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


New to Jython - how to install setuptools?

2010-12-03 Thread Dobedani
Hi folks,

I'm new to Jython - not to Python. The good thing about Python is that
there are many packages available which can be installed easily by
means of setuptools. Today I installed Jython, because I'm thinking of
integrating some Python code into a web application which will be
hosted on a web server with Tomcat behind it plus Jython.

I found this webpage and followed the instructions about installing
setuptools:
http://www.jython.org/jythonbook/en/1.0/appendixA.html

Unfortunately, it did not work for me. These are the errors I got:
C:\TEMP\jython>java -jar D:\usr\lib\jython25\jython.jar ez_setup.py
Downloading 
http://pypi.python.org/packages/2.5/s/setuptools/setuptools-0.6c11-py2.5.egg
Traceback (most recent call last):
  File "ez_setup.py", line 278, in  main(sys.argv[1:])
  File "ez_setup.py", line 212, in main from
setuptools.command.easy_install import main
  File "C:\TEMP\jython\setuptools-0.6c11-py2.5.egg\setuptools
\__init__.py", line 2, in 
  File "C:\TEMP\jython\setuptools-0.6c11-py2.5.egg\setuptools
\extension.py", line 2, in 
  File "C:\TEMP\jython\setuptools-0.6c11-py2.5.egg\setuptools
\dist.py", line 5, in 
  File "C:\TEMP\jython\setuptools-0.6c11-py2.5.egg\setuptools\command
\install.py", line 2, in 
  File "D:\usr\lib\jython25\Lib\distutils\command\install.py", line
15, in 
from distutils.sysconfig import get_config_vars
  File "D:\usr\lib\jython25\Lib\distutils\sysconfig.py", line 29, in

argv0_path = os.path.dirname(os.path.abspath(sys.executable))
  File "D:\usr\lib\jython25\Lib\ntpath.py", line 492, in abspath
if not isabs(path):
  File "D:\usr\lib\jython25\Lib\ntpath.py", line 55, in isabs
s = splitdrive(s)[1]
  File "D:\usr\lib\jython25\Lib\ntpath.py", line 121, in splitdrive
if p[1:2] == ':':
TypeError: 'NoneType' object is unsubscriptable

I'm suspecting the installation failed because I did not apply certain
settings, but I don't even know how to go about that! Any help will be
appreciated. As you'll understand I'm using Windows XP ;-)

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


Re: Exception handling in Python 3.x

2010-12-03 Thread Hrvoje Niksic
Steven D'Aprano  writes:

> Consider the following common exception handling idiom:
>
> def func(iterable):
> it = iter(iterable)
> try:
> x = next(it)
> except StopIteration:
> raise ValueError("can't process empty iterable")
> print(x)

Not exactly what you're looking for, but another way to express the
above is:

def func(iterable):
for x in iterable:
break
else:
raise ValueError("can't process empty iterable")
print(x)

Otherwise, I completely agree that being unable to completely replace
the original exception is an annoyance at best.
-- 
http://mail.python.org/mailman/listinfo/python-list


Great chance for Management work.

2010-12-03 Thread gaurav
Best site for management careers. Career in Management.
http://jobscore.webs.com/executivemanager.htm
http://topcareer.webs.com/businessmanagement.htm

Chances for banking career listing to all over cites person can get
work as bank employee.
http://rojgars1.webs.com/gov.htm http://printmediajobs.webs.com/fl.htm

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


Re: Exception handling in Python 3.x

2010-12-03 Thread Peter Otten
Steven D'Aprano wrote:

> Consider the following common exception handling idiom:
> 
> def func(iterable):
> it = iter(iterable)
> try:
> x = next(it)
> except StopIteration:
> raise ValueError("can't process empty iterable")
> print(x)
> 
> The intention is:
> 
> * detect an empty iterator by catching StopIteration;
> * if the iterator is empty, raise a ValueError;
> * otherwise process the iterator.
> 
> Note that StopIteration is an internal detail of no relevance whatsoever
> to the caller. Expose this is unnecessary at best and confusing at worst.

http://mail.python.org/pipermail/python-list/2010-October/1258606.html
http://mail.python.org/pipermail/python-list/2010-October/1259024.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparison with False - something I don't understand

2010-12-03 Thread Mark Wooding
Steven D'Aprano  writes:

> On Thu, 02 Dec 2010 16:35:08 +, Mark Wooding wrote:
> > There are better ways to handle errors than Python's exception system.
>
> I'm curious -- what ways would they be?

The most obvious improvement is resumable exceptions.

In general, recovering from an exceptional condition requires three
activities:

  * doing something about the condition so that the program can continue
running;

  * identifying some way of rejoining the program's main (unexceptional)
flow of control; and

  * actually performing that transfer, ensuring that any necessary
invariants are restored.

Python's `try ... finally' helps with the last; but Python intertwines
the first two, implementing both with `try ... except'.  The most
important consequence of this is that the logic which contains knowledge
about how to fix the condition must be closer to the code that
encountered the condition than the resume point is.  It's therefore hard
to factor out high-level policy about fixing conditions from the
relatively tedious business of providing safe points at which to resume
main execution.  (Effectively, each section of your program which wants
to avail itself of some high-level condition-fixing policy has to
provide its own protocol for expressing and implementing them.)

Phew.  That was abstract.  Can I come up with some examples?

I've been writing a (sort of) compiler recently.  When it encounters
errors, it reports a message to the user containing the position it had
reached in the source, updates a counter so that it can report a summary
at the end of the run and produce a sensible exit status, and then
attempts to carry on compiling as best it can.

The last bit -- attempting to carry on as best it can -- needs local
knowledge of what the compiler's doing and what actually went wrong.  If
the parser expected to find a delimiter, maybe it should pretend that it
found one, for example.

The other stuff, printing messages, updating counters, and so on, is all
done with some condition handlers wrapped around the meat of the
compiler.  That's written only once.  Everything that signals errors,
including standard I/O functions like open-a-file, gets the same
treatment.

(The remaining missing ingredient is a fluid variable which tracks the
current position in the source and is updated by the scanner; bits of
the compiler's semantic analysis machinery will temporarily focus
attention on other parts of the source using locations they saved during
the parse.  Implementing fluids in Python can be done with a context
manager: if you don't care about concurrency then you can use simple
variables; otherwise it's little fiddly and the syntax isn't very
comfortable, but it's still possible.)

A more familiar example, maybe, is the good old DOS `abort/retry/fail'
query.  Implementing such a thing in Python, as a general policy for
handling I/O errors, isn't possible.  Viewed narrowly, this is probably
a good thing: the old DOS query was very annoying.  But the difficulty
of implementing this policy illustrates the missing functionality.  And,
of course, if DOS had a proper resumable exception system, programs
could have overridden the annoying query.

In general, the code which discovers an exceptional condition may have
several options for how to resume.  It might be possible to ignore the
situation entirely and carry on regardless (`false alarm!').  It might
be possible to try again (`transient failure').  Alas, the logic which
is capable of implementing these options is usually too low-level and
too close to the action to be able to decide among them sensibly.
(Maybe a human user should be consulted -- but that can drag in user
interface baggage into a low-level networking library or whatever.)
Resumable exceptions provide a way out of this mess by separating the
mechanics of resumption from policy of which resumption option to
choose.

It's easy to show that a resumable exception system can do everything
that a nonresumable system (like Python's) can do (simply put all of the
recovery logic at the resume point); but the converse is not true.

There are some other fringe benefits to resumable exceptions.

  * It's usual to report a stack backtrace or similar if an exception
occurs but nothing manages to resume execution.  If unwinding the
stack is intertwined with working out how to resume execution, then
whenever you /try/ to run an applicable handler, you have to reify
the stack context and stash it somewhere in case the handler doesn't
complete the job.  This makes raising exceptions more expensive than
they need to be.

  * You can use the same mechanism for other kinds of communication with
surrounding context.  For example, Python occasionally emits
`warnings', which have their own rather simple management system
(using global state, so it's hard to say `don't issue MumbleWarnings
while we frob the widgets' in a concurrent program).  A resumable
ex

Re: Google AI challenge: planet war. Lisp won.

2010-12-03 Thread namekuseijin
On 2 dez, 15:06, Xah Lee  wrote:
> discovered this rather late.
>
> Google has a AI Challenge: planet wars.http://ai-contest.com/index.php
>
> it started sometimes 2 months ago and ended first this month.
>
> the winner is Gábor Melis, with his code written in lisp.
>
> Congrats lispers!
>
> Gábor wrote a blog about it 
> herehttp://quotenil.com/Planet-Wars-Post-Mortem.html
>
> (not sure if this has been mentioned here but quick search didn't find
> it)
>
>  Xah ∑http://xahlee.org/☄

definitely cool!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is id(self) constant over an object lifetime ?

2010-12-03 Thread Christian Heimes
Am 03.12.2010 14:53, schrieb Jean-Michel Pichavant:
> Next time I promise to look at the doc before actually asking the 
> question here :)

You are misinterpreting the excerpt. You are right that the id of an
object doesn't change during the lifetime of a Python process and as
long as it stays inside a single process. However if you use some sort
of persistence layer like pickles or an IPC mechanism like
multiprocessing the id is definitely not constant. If you need something
stable, I suggest you look at the uuid module.

Christian

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


Using python for web IM?

2010-12-03 Thread Kechagias Apostolos
Hello,
   We are currently working on a project which needs video and audio
streaming(peer to peer). We need to know if there are any available open
source libraries to embed video,audio,p2p transfer in our client OR if there
is any available framework which could help us with our project. It would
bereally helpful if you could also provide us some feedback on what we can
use as XMPP server.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception handling in Python 3.x

2010-12-03 Thread Hrvoje Niksic
Peter Otten <__pete...@web.de> writes:

>> Note that StopIteration is an internal detail of no relevance whatsoever
>> to the caller. Expose this is unnecessary at best and confusing at worst.
>
> http://mail.python.org/pipermail/python-list/2010-October/1258606.html
> http://mail.python.org/pipermail/python-list/2010-October/1259024.html

Both of these involve suppressing the chaining at the wrong place,
namely in the outer handler or, worse yet, in the exception display
mechanism.  Steven, on the other hand, wants his *inner* handler to
express that the original exception was an implementation detail, a
business exception such as StopIteration, that is completely irrelevant
to the actual exception being raised.  The outer handler is the wrong
place to suppress the chaining because it has no way of distinguishing
Steven's case from a genuine case of a new exception unexpectedly
occurring during handling of the original exception.

One solution would be for "raise" inside except to not use the context.
For example:

try:
  {}[1]
except KeyError:
  1/0

would behave as before, but:

But:

try:
  {}[1]
except KeyError:
  raise Exception("my error")

...would raise the custom error forgetting the KeyError.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: position independent build of python

2010-12-03 Thread Diez B. Roggisch
erikj  writes:

> If my understanding is correct, the sys.prefix variable holds the root
> directory python uses to find related files, and eg its site-packages.
>
> the value of sys.prefix is specified at compile time.
>
> it seems that on windows, when I build/install python at one location,
> and
> later move it to another location, python will find all its needs
> relative to the new location.
>
> however, when I do the same on linux, python keeps looking for
> its dependencies in the build location.
>
> is there a possibility to have it always look at a position relative
> to the location of the executable ?  the goal is to be able to build
> python on one machine, and then simply copy the build tree to
> other machines at other locations.

Maybe looking at virtualenv, especially with the --no-site-packages
variable set gives you a hint. AFAIK there are some hard-coded paths
involved, but not inside compiled code. Maybe you can remedy that somehow.

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


Re: Exception handling in Python 3.x

2010-12-03 Thread Peter Otten
Hrvoje Niksic wrote:

> Peter Otten <__pete...@web.de> writes:
> 
>>> Note that StopIteration is an internal detail of no relevance whatsoever
>>> to the caller. Expose this is unnecessary at best and confusing at
>>> worst.
>>
>> http://mail.python.org/pipermail/python-list/2010-October/1258606.html
>> http://mail.python.org/pipermail/python-list/2010-October/1259024.html
> 
> Both of these involve suppressing the chaining at the wrong place,
> namely in the outer handler or, worse yet, in the exception display
> mechanism.  Steven, on the other hand, wants his *inner* handler to
> express that the original exception was an implementation detail, a
> business exception such as StopIteration, that is completely irrelevant
> to the actual exception being raised.  The outer handler is the wrong
> place to suppress the chaining because it has no way of distinguishing
> Steven's case from a genuine case of a new exception unexpectedly
> occurring during handling of the original exception.

To quote the Rolling Stones: You can't always get what you want. 

After rereading the original post I still don't get why the workarounds 
provided in those links aren't worth considering.

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


Using a window style in a Toplevel window

2010-12-03 Thread craf
Hi.

I use Python 3.1 and Tkinter.ttk 8.5 on Ubuntu 9.10.

CODE:

module:FMain.py

from tkinter import ttk
from FSecondWindow import *

class App:
def __init__(self,master):

button1 = ttk.Button(master,text='Show
TopLevel',command=lambda:window())
button1.pack()

   
master = Tk()
app = App(master)
style = ttk.Style()
style.theme_use('clam')
master.mainloop()


module:FSecondWindow.py

from tkinter import *
from tkinter import ttk

def window():
t = Toplevel()
button2 = Button(t,text='Hello').pack()


CODE EXPLANATION:---

1. From the main module FMain.py call the window function that is
located in FSecondWindow module and create a toplevel window.

2.I apply a theme called 'clam' to the master window to improve the
appearance of their widgets.

QUERY:--

How I can make the toplevel window also take the theme 'clam'?

Thanks in advance.

Regards.

Cristian Abarzúa.

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


Re: Comparison with False - something I don't understand

2010-12-03 Thread Harishankar
On Fri, 03 Dec 2010 14:31:43 +, Mark Wooding wrote:

> The most obvious improvement is resumable exceptions.

This is probably what I had in mind but I just couldn't explain it the 
way you did below.

> 
> In general, recovering from an exceptional condition requires three
> activities:
> 
>   * doing something about the condition so that the program can continue
> running;
> 
>   * identifying some way of rejoining the program's main (unexceptional)
> flow of control; and
> 
>   * actually performing that transfer, ensuring that any necessary
> invariants are restored.

This really sums up my thoughts about exceptions better than I could have 
explained! I just felt instinctively that I had missed something, but it 
appears to be a break in logic of the code somewhere which I thought was 
my fault. Seems that exception handling requires a lot of forethought 
since the control of program execution breaks at the point of exception 
with no obvious way to rejoin it seamlessly whereas with an error, a 
simple if condition could handle the error state and resume execution 
from that point forward. This is the main reason why I think I used 
simple error codes to handle certain recoverable conditions and avoided 
exceptions.   

I quite enjoyed your post. Thank you for explaining a lot of issues which 
I probably could not have figured out on my own.
-- 
Harishankar (http://harishankar.org http://lawstudentscommunity.com)

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


How to add data into exisitng Excel file at next open row?

2010-12-03 Thread noydb
How can you determine the next open row in an existing Excel file such
that you can start adding data to the cells in that row?  As in below,
I want a variable in place of the 6 (row 6 in the four ws1.Cells(x,1)
lines), but have no other way of knowing what row I am on besides
looking to the first free cell in column A.  How to do?  Examples I
see make it seem really complicated - this can't be that hard.

Thanks for any help.

worksheet = "C:\\Excel_Reports\\ea" + ea + "report"# + ".xls"
xlApp = win32com.client.Dispatch("Excel.Application")
xlApp.Visible = 1
xlApp.Workbooks.Open(worksheet) ## for existing file
##xlApp.SheetsInNewWorkbook = 1
##wb = xlApp.Workbooks()
ws1 = xlApp.Worksheets(1)

ws1.Cells(6,1).Value = "selection"
ws1.Cells(6,2).Value = count
ws1.Cells(6,3).Value = epcFloat
ws1.Cells(6,8).Value = currentGMT

wb.SaveAs(worksheet)
wb.Close(False) ## False/1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparison with False - something I don't understand

2010-12-03 Thread Harishankar
On Thu, 02 Dec 2010 17:33:47 -0800, Aahz wrote:

> Please demonstrate that using ``if`` blocks for True/False is impler and
> cleaner than using ``try`` blocks to handle exceptions.

It is my personal preference and coding style for certain situations I 
encounter in my own programs and not something that I could prove to 
anybody else by theory.

But anyway, in certain circumstances, exceptions create a break in flow 
of the execution of a program that makes it non-obvious as to how to 
resume flow at the point of disruption especially when the exception 
handling mechanism is at a higher level. While an error flag can simply 
set an alarm and allow other code to continue and allow the calling 
higher-level code to handle the alarm/flag as it sees fit.


-- 
Harishankar (http://harishankar.org http://lawstudentscommunity.com)

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


Re: Exception handling in Python 3.x

2010-12-03 Thread Paul Rubin
Steven D'Aprano  writes:
> def func(iterable):
> it = iter(iterable)
> failed = False
> try:
> x = next(it)
> except StopIteration:
> failed = True
> if failed:
> raise ValueError("can't process empty iterable")
> print(x)

Untested:

from itertools import islice

def func(iterable):
   xs = list(islice(iter(iterable), 1))
   if len(xs) == 0:
  raise ValueError(...)
   print xs[0]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparison with False - something I don't understand

2010-12-03 Thread Emile van Sebille

On 12/3/2010 6:31 AM Mark Wooding said...


It's easy to show that a resumable exception system can do everything
that a nonresumable system (like Python's) can do (simply put all of the
recovery logic at the resume point); but the converse is not true.

There are some other fringe benefits to resumable exceptions.


I do a lot of work in a variant of Business Basic that has always 
offered resumable exceptions.  The closest I get in python is using 
import pdb;pdb.set_trace().  I wonder what it would take to allow for 
any exceptions occurring outside a try/except context to dump the 
traceback, then invoke pdb.set_trace() before bailing to allow for both 
investigation and possible recovery and continuance?


Emile



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


Re: Twisted and txJSON-RPC

2010-12-03 Thread jaime
did you fix it? I have the same problem


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


Assigning to __class__ attribute

2010-12-03 Thread kj


I have a couple of questions regarding assigning to an instance's
__class__ attribute.

The first is illustrated by the following interaction.  First I
define an empty class:

>>> class Spam(object): pass
... 

Now I define an instance of Spam and an instance of Spam's superclass:
>>> x = Spam()
>>> y = Spam.__mro__[1]() # (btw, is there a less uncouth way to do this???)
>>> [z.__class__.__name__ for z in x, y]
['Spam', 'object']

Now I define a second empty class:
>>> class Ham(object): pass
... 

Next, I attempt to assign the value Ham to x.__class__:

>>> x.__class__ = Ham
>>> [isinstance(x, z) for z in Spam, Ham]
[False, True]

This was the first surprise for me: assigning to the __class__
attribute not only isn't vetoed, but in fact changes the instances
class:

Oh-ky...

First question: how kosher is this sort of class transmutation
through assignment to __class__?  I've never seen it done.  Is this
because it considered something to do only as a last resort, or is
it simply because the technique is not needed often, but it is
otherwise perfectly ok?

The second, and much bigger, surprise comes when I attempt to do
the same class-switching with y:

>>> y.__class__ = Ham
Traceback (most recent call last):
  File "", line 1, in 
TypeError: __class__ assignment: only for heap types

(If you recall, y's class is object, the superclass of x.) Apparently
Spam is a "heap type" (whatever that is) but its superclass, object,
isn't.  This definitely rattles my notions of inheritance: since
the definition of Spam was empty, I didn't expect it to have any
significant properties that are not already present in its superclass.
What's going on here? Is this a bug, or a feature? I can see no
logical justification for allowing such class switching for only
some class and not others.

One last question:  as the questions above make clear, I have a
colossal muddle inside my head regarding Python's model of classes
and inheritance.  This is not for lack of trying to understand it,
but, rather, for exactly the opposite reason: in my zeal to gain
the fullest understanding of this topic, I think I have read too
much that is incorrect, or obsolete, or incomplete...

What is the most complete, definitive, excruciatingly detailed
exposition of Python's class and inheritance model?  I'm expressly
avoiding Google to answer this question, and instead asking it
here, because I suspect that there's some connection between my
state of utter confusion on this topic and the ease with which the
complete/definitive/highest-quality information can get lost among
a huge number of Google hits to popular-but-only-partially-correct
sources of information.  (In fact, I *may* have already read the
source I'm seeking, but subsequent readings of incorrect stuff may
have overwritten the correct information in my brain.)

TIA!

~kj

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


Re: Exception handling in Python 3.x

2010-12-03 Thread Ethan Furman

Peter Otten wrote:
 > http://mail.python.org/pipermail/python-list/2010-October/1258606.html

http://mail.python.org/pipermail/python-list/2010-October/1259024.html


I found #6210 on bugs.python.org -- does anyone know if there are any 
others regarding this issue?  Or any progress on MRAB's idea?


MRAB wrote:
> Suggestion: an explicit 'raise' in the exception handler excludes the
> context, but if you want to include it then 'raise with'. For example:
>
> # Exclude the context
> try:
> command_dict[command]()
> except KeyError:
> raise CommandError("Unknown command")
>
> # Include the context
> try:
> command_dict[command]()
> except KeyError:
> raise with CommandError("Unknown command")

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


Re: Exception handling in Python 3.x

2010-12-03 Thread Ethan Furman

Peter Otten wrote:

Hrvoje Niksic wrote:


Peter Otten <__pete...@web.de> writes:


Note that StopIteration is an internal detail of no relevance whatsoever
to the caller. Expose this is unnecessary at best and confusing at
worst.

http://mail.python.org/pipermail/python-list/2010-October/1258606.html
http://mail.python.org/pipermail/python-list/2010-October/1259024.html

Both of these involve suppressing the chaining at the wrong place,
namely in the outer handler or, worse yet, in the exception display
mechanism.  Steven, on the other hand, wants his *inner* handler to
express that the original exception was an implementation detail, a
business exception such as StopIteration, that is completely irrelevant
to the actual exception being raised.  The outer handler is the wrong
place to suppress the chaining because it has no way of distinguishing
Steven's case from a genuine case of a new exception unexpectedly
occurring during handling of the original exception.


To quote the Rolling Stones: You can't always get what you want. 

After rereading the original post I still don't get why the workarounds 
provided in those links aren't worth considering.


For me at least it's a matter of simplicity, clarity, and the Way of the 
Python  ;)


The workarounds are boiler-plate for a fairly common situation, and one 
of the things i _love_ about python is the *lack* of boilerplate.


I think the real question is is there any progress on dealing with the 
Open Issue in the PEP?


Open Issue: Suppressing Context
As written, this PEP makes it impossible to suppress '__context__',
since setting exc.__context__ to None in an 'except' or 'finally'
clause will only result in it being set again when exc is raised.

http://www.python.org/dev/peps/pep-3134/

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


import module doesn't work for new package

2010-12-03 Thread goldtech
I tried install a Python - would the word be "package"? - on Ubuntu
10.10. Could you tell me how to fix? I would be grateful, is it a path
problem? Thanks. Lee

gi...@giga1:~/Desktop/pykhtml-0.2$ sudo python setup.py install
[sudo] password for giga1:
running install
running build
running build_py
creating build
creating build/lib.linux-i686-2.6
creating build/lib.linux-i686-2.6/pykhtml
copying pykhtml/dom.py -> build/lib.linux-i686-2.6/pykhtml
copying pykhtml/__init__.py -> build/lib.linux-i686-2.6/pykhtml
running install_lib
running install_egg_info
Removing /usr/local/lib/python2.6/dist-packages/PyKHTML-0.2.egg-info
Writing /usr/local/lib/python2.6/dist-packages/PyKHTML-0.2.egg-info

then:

>>> import pykhtml
Traceback (most recent call last):
  File "", line 1, in 
  File "pykhtml/__init__.py", line 3, in 
import khtml, kdecore, kdeui, kio, dcopext
ImportError: No module named khtml
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Assigning to __class__ attribute

2010-12-03 Thread Robert Kern

On 12/3/10 1:28 PM, kj wrote:



I have a couple of questions regarding assigning to an instance's
__class__ attribute.

The first is illustrated by the following interaction.  First I
define an empty class:


class Spam(object): pass

...

Now I define an instance of Spam and an instance of Spam's superclass:

x = Spam()
y = Spam.__mro__[1]() # (btw, is there a less uncouth way to do this???)
[z.__class__.__name__ for z in x, y]

['Spam', 'object']

Now I define a second empty class:

class Ham(object): pass

...

Next, I attempt to assign the value Ham to x.__class__:


x.__class__ = Ham
[isinstance(x, z) for z in Spam, Ham]

[False, True]

This was the first surprise for me: assigning to the __class__
attribute not only isn't vetoed, but in fact changes the instances
class:

Oh-ky...

First question: how kosher is this sort of class transmutation
through assignment to __class__?  I've never seen it done.  Is this
because it considered something to do only as a last resort, or is
it simply because the technique is not needed often, but it is
otherwise perfectly ok?


Last resort for very special purposes, and only extremely rarely in production.


The second, and much bigger, surprise comes when I attempt to do
the same class-switching with y:


y.__class__ = Ham

Traceback (most recent call last):
   File "", line 1, in
TypeError: __class__ assignment: only for heap types

(If you recall, y's class is object, the superclass of x.) Apparently
Spam is a "heap type" (whatever that is) but its superclass, object,
isn't.  This definitely rattles my notions of inheritance: since
the definition of Spam was empty, I didn't expect it to have any
significant properties that are not already present in its superclass.
What's going on here? Is this a bug, or a feature? I can see no
logical justification for allowing such class switching for only
some class and not others.


Feature. When you have C-implemented types, you cannot safely swap out their 
instance's __class__. There are memory issues involved. Only subclasses of 
object made by the class statement (or the equivalent type(...) call), i.e. 
"heap types", permit this modification. object is a C-implemented type. 
Importantly, as for most other C-implemented types, plain object instances have 
no __dict__.


Types and classes were unified a long time ago in Python 2.2, but there are 
still relevant distinctions between C-implemented types and Python-implemented 
types.



One last question:  as the questions above make clear, I have a
colossal muddle inside my head regarding Python's model of classes
and inheritance.  This is not for lack of trying to understand it,
but, rather, for exactly the opposite reason: in my zeal to gain
the fullest understanding of this topic, I think I have read too
much that is incorrect, or obsolete, or incomplete...

What is the most complete, definitive, excruciatingly detailed
exposition of Python's class and inheritance model?  I'm expressly
avoiding Google to answer this question, and instead asking it
here, because I suspect that there's some connection between my
state of utter confusion on this topic and the ease with which the
complete/definitive/highest-quality information can get lost among
a huge number of Google hits to popular-but-only-partially-correct
sources of information.  (In fact, I *may* have already read the
source I'm seeking, but subsequent readings of incorrect stuff may
have overwritten the correct information in my brain.)


http://www.python.org/download/releases/2.2.3/descrintro/

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Assigning to __class__ attribute

2010-12-03 Thread Arnaud Delobelle
kj  writes:

> I have a couple of questions regarding assigning to an instance's
> __class__ attribute.
>
> The first is illustrated by the following interaction.  First I
> define an empty class:
>
 class Spam(object): pass
> ... 
>
> Now I define an instance of Spam and an instance of Spam's superclass:
 x = Spam()
 y = Spam.__mro__[1]() # (btw, is there a less uncouth way to do this???)

Yes:

y = object()

 [z.__class__.__name__ for z in x, y]
> ['Spam', 'object']
>
> Now I define a second empty class:
 class Ham(object): pass
> ... 
>
> Next, I attempt to assign the value Ham to x.__class__:
>
 x.__class__ = Ham
 [isinstance(x, z) for z in Spam, Ham]
> [False, True]
>
> This was the first surprise for me: assigning to the __class__
> attribute not only isn't vetoed, but in fact changes the instances
> class:
>
> Oh-ky...
>
> First question: how kosher is this sort of class transmutation
> through assignment to __class__?  I've never seen it done.  Is this
> because it considered something to do only as a last resort, or is
> it simply because the technique is not needed often, but it is
> otherwise perfectly ok?

It's OK as long as the slots defined in the classes are the same (using
Python 3 below so no need for specifying that classes derive from object):

>>> class Foo: pass
... 
>>> class Bar: __slots__ = 'x', 'y'
... 
>>> foo = Foo()
>>> foo.__class__ = Bar
Traceback (most recent call last):
  File "", line 1, in 
TypeError: __class__ assignment: 'Foo' object layout differs from 'Bar'
>>> class Baz: __slots__ = 'x', 'y'
... 
>>> bar = Bar()
>>> bar.__class__ = Baz


> The second, and much bigger, surprise comes when I attempt to do
> the same class-switching with y:
>
 y.__class__ = Ham
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: __class__ assignment: only for heap types

y is of type object, which is a builtin type.  You can only switch the
__class__ of an instance of a user-defined class.

> (If you recall, y's class is object, the superclass of x.) Apparently
> Spam is a "heap type" (whatever that is) but its superclass, object,
> isn't.  This definitely rattles my notions of inheritance: since
> the definition of Spam was empty, I didn't expect it to have any
> significant properties that are not already present in its superclass.
> What's going on here? Is this a bug, or a feature? I can see no
> logical justification for allowing such class switching for only
> some class and not others.

There is a big difference:

>>> class Foo: pass
>>> x, y = Foo(), object()
>>> x.__dict__
{}
>>> y.__dict__
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'object' object has no attribute '__dict__'

This means that you can have instance attributes for x but not for y:

>>> x.myattr = 123
>>> y.myattr = 123
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'object' object has no attribute 'myattr'

This reflects the fact that x and y are a different kind of
object, with a different layout so you can't hotswap their types. 

I imagine that the term "heap type" is used to types which are objects
that live on the heap (in practice they are types defined in Python,
by using a "class" statement or calling type(name, bases, attrs)) as
opposed to builtin types such as object, int, str, etc... which don't
live on the heap.

> One last question:  as the questions above make clear, I have a
> colossal muddle inside my head regarding Python's model of classes
> and inheritance.  This is not for lack of trying to understand it,
> but, rather, for exactly the opposite reason: in my zeal to gain
> the fullest understanding of this topic, I think I have read too
> much that is incorrect, or obsolete, or incomplete...
> What is the most complete, definitive, excruciatingly detailed
> exposition of Python's class and inheritance model?

I learnt by reading Guido's "Unifying types and classes in Python 2.2",
available here:

http://www.python.org/download/releases/2.2.3/descrintro/

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


Re: Comparison with False - something I don't understand

2010-12-03 Thread Aahz
In article ,
Harishankar   wrote:
>On Thu, 02 Dec 2010 17:33:47 -0800, Aahz wrote:
>>
>> Please demonstrate that using ``if`` blocks for True/False is impler and
>> cleaner than using ``try`` blocks to handle exceptions.
>
>It is my personal preference and coding style for certain situations I 
>encounter in my own programs and not something that I could prove to 
>anybody else by theory.

Note carefully that I said "demonstrate", not "prove".  If using ``if``
is so clearly better in some situations, you should be able to provide an
example.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"Think of it as evolution in action."  --Tony Rand
-- 
http://mail.python.org/mailman/listinfo/python-list


class attribute confusion

2010-12-03 Thread OAN

Hi,

i was having a problem with class attributes initiated outside of 
__init__. This code is a demonstration of what i mean:


class A():
mylist = []
def __init__(self):
self.mylist.append(1)
pass

class B(A):
def __init__(self):
A.__init__(self)
self.mylist.append(2)

v = A()
print 'v:',v.mylist
x = B()
print 'x:',x.mylist
y = B()
print 'y:',y.mylist
z = A()
print 'z:',z.mylist
print 'v:',v.mylist

I would expect the following result:

v: [1]
x: [1, 2]
y: [1, 2]
z: [1]
v: [1]

Who wouldn't, right? But actually python 2.6(.6) gives me the following 
result:


v: [1]
x: [1, 1, 2]
y: [1, 1, 2, 1, 2]
z: [1, 1, 2, 1, 2, 1]
v: [1, 1, 2, 1, 2, 1]

The four variables v,x,y and z now actually share the same 'mylist'!! To 
get the correct results, i have to initialize 'mylist' inside of the 
__init__ method!


I think this behaviour is totally wrong, since it seems A.__init__(self) 
is changing the value inside of A() not inside of the object variable 
'self' (that should be x or y)!!



Could someone explain this to me, please?

regards.



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


Re: class attribute confusion

2010-12-03 Thread Arnaud Delobelle
OAN  writes:

> Hi,
>
> i was having a problem with class attributes initiated outside of
> __init__. This code is a demonstration of what i mean:
>
> class A():
> mylist = []
> def __init__(self):
> self.mylist.append(1)
> pass
>
> class B(A):
> def __init__(self):
> A.__init__(self)
> self.mylist.append(2)
>
> v = A()
> print 'v:',v.mylist
> x = B()
> print 'x:',x.mylist
> y = B()
> print 'y:',y.mylist
> z = A()
> print 'z:',z.mylist
> print 'v:',v.mylist
>
> I would expect the following result:
>
> v: [1]
> x: [1, 2]
> y: [1, 2]
> z: [1]
> v: [1]
>
> Who wouldn't, right? But actually python 2.6(.6) gives me the
> following result:
>
> v: [1]
> x: [1, 1, 2]
> y: [1, 1, 2, 1, 2]
> z: [1, 1, 2, 1, 2, 1]
> v: [1, 1, 2, 1, 2, 1]
>
> The four variables v,x,y and z now actually share the same 'mylist'!!
> To get the correct results, i have to initialize 'mylist' inside of
> the __init__ method!

Yes.  See below.

> I think this behaviour is totally wrong, since it seems
> A.__init__(self) is changing the value inside of A() not inside of the
> object variable 'self' (that should be x or y)!!

It's not wrong at all.  You expect "mylist" to behave as an instance
attribute, but you defined it as a class attribute.  Instance attributes
are naturally initialised in the __init__() method.

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


Re: Assigning to __class__ attribute

2010-12-03 Thread Mark Wooding
kj  writes:

> >>> class Spam(object): pass
>
> Now I define an instance of Spam and an instance of Spam's superclass:
> >>> x = Spam()
> >>> y = Spam.__mro__[1]() # (btw, is there a less uncouth way to do this???)

There's the `__bases__' attribute, which is simply a tuple of the
class's direct superclasses in order.  Spam.__bases__[0] will always be
equal to Spam.__mro__[1] because of the way the linearization works.

There's also `__base__' attribute, which seems to correspond to a
PyTypeObject's `tp_base' slot; this /isn't/ always the first direct
superclass; I'm not quite sure what the rules are, and it doesn't seem
to be documented anywhere.

> >>> [z.__class__.__name__ for z in x, y]
> ['Spam', 'object']
>
> >>> class Ham(object): pass
> ... 
>
> >>> x.__class__ = Ham
> >>> [isinstance(x, z) for z in Spam, Ham]
> [False, True]
>
> First question: how kosher is this sort of class transmutation
> through assignment to __class__?  

Yep.  That's allowed, and useful.  Consider something like a red/black
tree: red and black nodes behave differently from one another, and it
would be convenient to make use of method dispatch rather than writing a
bunch of conditional code; unfortunately, nodes change between being red
and black occasionally.  Swizzling classes lets you do this.

Various other languages have similar features.  The scariest is probably
Smalltalk's `become: anObject' method, which actually swaps two objects.
Python `__class__' assignment is similarly low-level: all it does is
tweak a pointer, and it's entirely up to the program to make sure that
the object's attributes are valid according to the rules for the new
class.  The Common Lisp Object System has CHANGE-CLASS, which is a
rather more heavyweight and hairy procedure which tries to understand
and cope with the differences between the two classes.

> I've never seen it done.  Is this because it considered something to
> do only as a last resort, or is it simply because the technique is not
> needed often, but it is otherwise perfectly ok?

It's not needed very often, and can be surprising to readers who aren't
familiar with other highly dynamic object systems, so I don't think it's
particularly encouraged; but it seems like it might be the best approach
in some cases.  I think it's one of those things where you'll just
/know/ when it's the right answer, and if you don't know that it's the
right answer, it isn't.

> >>> y.__class__ = Ham
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: __class__ assignment: only for heap types

`Heap types' are types which are allocated dynamically.  Non-heap types
are ones which are dreamt up by C extensions or built into Python.

I suspect that the logic here is that non-heap types in general are
magical and weird, and their instances might have special C stuff
attached to them, so changing their classes is a Bad Idea, though
there's an extra check which catches most problems:

In [1]: class foo (str): pass
In [2]: class bar (object): pass
In [3]: x = foo()
In [4]: x.__class__ = bar
TypeError: __class__ assignment: 'foo' object layout differs from 'bar'

Anyway, I'd guess it's just a bug that `object' is caught this way, but
it doesn't seem an especially important one.

> This definitely rattles my notions of inheritance: since the
> definition of Spam was empty, I didn't expect it to have any
> significant properties that are not already present in its superclass.

Yes, sorry.  I think this is a bit poor, really, but it's hard to do a
much better job.

Pure Python objects are pretty simple things, really: they have a
pointer to their class, and a bunch of attributes stored in a
dictionary.  What other languages call instance variables or methods are
found using attribute lookup, which just searches the object, and then
its class and its superclasses in the method resolution order.  If you
fiddle with `__class__', then attribute lookup searches a different
bunch of classes.  Nothing else needs to change -- or, at least, if it
does, then you'd better do it yourself.

Types implemented in C work by extending the underlying Python object
structure.  The magical type-specific stuff is stored in the extra
space.  Unfortunately, changing classes is now hard, because Python code
can't even see the magic C stuff -- and, besides, a different special C
type may require a different amount of space, and the CPython
implementation can't cope with the idea that objects might move around
in memory.

Similar complications occur if one of the classes has a `__slots__'
attribute: in this case, both the original and new class must have a
`__slots__' attribute and they must be the same length and have the same
names.

> What is the most complete, definitive, excruciatingly detailed
> exposition of Python's class and inheritance model?

It's kind of scattered.  The language reference sections 3.3 and 3.4
contain some useful information, but it's rather detailed and it's a
(mostly) comprehensive list

Re: class attribute confusion

2010-12-03 Thread Steven D'Aprano
On Fri, 03 Dec 2010 22:54:19 +0100, OAN wrote:

> Hi,
> 
> i was having a problem with class attributes initiated outside of
> __init__. This code is a demonstration of what i mean:
[...]
> I would expect the following result:
> 
> v: [1]
> x: [1, 2]
> y: [1, 2]
> z: [1]
> v: [1]
> 
> Who wouldn't, right? 

Everybody who actually understands Python's object model.


> The four variables v,x,y and z now actually share the same 'mylist'!! To
> get the correct results, i have to initialize 'mylist' inside of the
> __init__ method!

Right. If you define a *class* attribute, it lives in the class, not the 
instance, and so all instances share the same value.

> I think this behaviour is totally wrong, since it seems A.__init__(self)
> is changing the value inside of A() not inside of the object variable
> 'self' (that should be x or y)!!

A.__init__(self) calls A's init method with self (either x or y) as the 
self parameter, but A's init method merely modifies the class attribute 
mylist in place. It doesn't create a new list.

The behaviour you're seeing is no different from this:

shared = []
a = {"spam": shared, "ham": 23}
b = {"spam": shared, "ham": 42}
a["spam"].append("parrot")

What would you expect the value of b["spam"] to be?


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


Re: Assigning to __class__ attribute

2010-12-03 Thread Steven D'Aprano
On Fri, 03 Dec 2010 19:28:00 +, kj wrote:

> This was the first surprise for me: assigning to the __class__ attribute
> not only isn't vetoed, but in fact changes the instances class:
> 
> Oh-ky...
> 
> First question: how kosher is this sort of class transmutation through
> assignment to __class__?  I've never seen it done.  Is this because it
> considered something to do only as a last resort, or is it simply
> because the technique is not needed often, but it is otherwise perfectly
> ok?

While not exactly encouraged, it is a deliberate feature. It's not a good 
idea to go around randomly monkey-patching instances with a new class, 
and in fact Python makes some attempts to protect you from the most 
egregious errors, but the technique has its uses. Especially if you're 
swapping between two classes which you have designed to be swapped 
between.

For instance, if you have an object that needs to display two distinct 
behaviours during different times of its life, then a good technique is 
to write two classes, one for each set of behaviours, and automatically 
switch between them as needed. A ring buffer is a common example:

http://code.activestate.com/recipes/68429-ring-buffer/

This made it into the Python Cookbook, so it comes with the approval of 
Alex Martelli, which is nearly as good as the approval of Guido :)



> The second, and much bigger, surprise comes when I attempt to do the
> same class-switching with y:
> 
 y.__class__ = Ham
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: __class__ assignment: only for heap types
> 
> (If you recall, y's class is object, the superclass of x.) Apparently
> Spam is a "heap type" (whatever that is) but its superclass, object,
> isn't.  This definitely rattles my notions of inheritance: since the
> definition of Spam was empty, I didn't expect it to have any significant
> properties that are not already present in its superclass. What's going
> on here? Is this a bug, or a feature? I can see no logical justification
> for allowing such class switching for only some class and not others.

That is more of a design compromise than a feature... it is unsafe to 
change the class of types implemented in C, for various implementation-
related reasons, and so Python prohibits it.

Heap types are dynamically allocated types that you create using the 
class statement (or the type function). They're so-called because they 
live in the heap. The builtin types defined in C presumably aren't 
dynamically allocated, but statically. Presumably they have a fixed 
layout in memory and don't live in the heap. Not being a C programmer, 
I've never cared about the implementation, only that you can't sensibly 
turn a str instance into an int instance by assigning to __class__ and so 
Python prohibits it.


> One last question:  as the questions above make clear, I have a colossal
> muddle inside my head regarding Python's model of classes and
> inheritance.  This is not for lack of trying to understand it, but,
> rather, for exactly the opposite reason: in my zeal to gain the fullest
> understanding of this topic, I think I have read too much that is
> incorrect, or obsolete, or incomplete...

I suspect you're trying to make this more complicated than it actually 
is. You keep finding little corner cases that expose implementation 
details (such as the heap-types issue above) and leaping to the erroneous 
conclusion that because you didn't understand this tiny little corner of 
Python's class model, you didn't understand any of it. Python's object 
model is relatively simple, but it does occasionally expose a few messy 
corners.


> What is the most complete, definitive, excruciatingly detailed
> exposition of Python's class and inheritance model?

That would be the source code.



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


Re: Exception handling in Python 3.x

2010-12-03 Thread Steven D'Aprano
On Fri, 03 Dec 2010 10:15:58 -0800, Paul Rubin wrote:

> Steven D'Aprano  writes:
>> def func(iterable):
>> it = iter(iterable)
>> failed = False
>> try:
>> x = next(it)
>> except StopIteration:
>> failed = True
>> if failed:
>> raise ValueError("can't process empty iterable")
>> print(x)
> 
> Untested:
> 
> from itertools import islice
> 
> def func(iterable):
>xs = list(islice(iter(iterable), 1))
>if len(xs) == 0:
>   raise ValueError(...)
>print xs[0]


If you're intention was to make me feel better about the version above 
that sets a flag, you succeeded admirably!

:)


-- 
Steven



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


Re: [Python-es] Uso de variable Global

2010-12-03 Thread Guillermo Candia Huerta
El 02/12/10 19:04, Pau Cervera escribió:
> Ni idea de Tkinter, pero ¿no puedes almacenar *valor* en una variable de
> instancia de App y convertir la función *muestra* en un método de la classe
> App que teng aceso a las variables de instancia de App?
> 
> -
> Pau
> 
> Python..., what else?
> 
> 
> 2010/12/2 craf 
> 
>> Hola.
>>
>>
>> Estoy probando Tkinter y escribí este pequeño código el cual crea un
>> formulario con un textbox y un botón. Al ingresar un dato en el textbox
>> y presionar el botón, se imprime en la consola el valor.
>>
>>
>> ---CODE
>>
>> from Tkinter import *
>>
>> def muestra():
>>print(valor.get())
>>
>> class App:
>>def __init__(self,master):
>>global valor
>>valor = StringVar()
>>e = Entry(master,textvariable=valor).pack()
>>b = Button(master,text='Mostrar',command=muestra).pack()
>>
>>
>> master = Tk()
>> app = App(master)
>> master.mainloop()
>>
>> -
>>
>> Funciona, pero tuve que hacer uso de una variable Global.
>>
>> Pregunta: ¿Es valida esta forma?, ¿Se puede hacer de otra forma, sin
>> ocuparla?.
>>
>> Saludos.
>>
>> Cristian
>>
>>
>>
>> ___
>> Python-es mailing list
>> python...@python.org
>> http://mail.python.org/mailman/listinfo/python-es
>> FAQ: http://python-es-faq.wikidot.com/
>>
> 
puede heredar el botón y agregas los atributos y métodos que necesites,
en el constructor le pasas las variables que necesitas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception handling in Python 3.x

2010-12-03 Thread Steven D'Aprano
On Fri, 03 Dec 2010 16:26:19 +0100, Hrvoje Niksic wrote:

> Peter Otten <__pete...@web.de> writes:
> 
>>> Note that StopIteration is an internal detail of no relevance
>>> whatsoever to the caller. Expose this is unnecessary at best and
>>> confusing at worst.
>>
>> http://mail.python.org/pipermail/python-list/2010-October/1258606.html
>> http://mail.python.org/pipermail/python-list/2010-October/1259024.html

Thanks for the links Peter.

 
> Both of these involve suppressing the chaining at the wrong place,
> namely in the outer handler or, worse yet, in the exception display
> mechanism.  Steven, on the other hand, wants his *inner* handler to
> express that the original exception was an implementation detail, a
> business exception such as StopIteration, that is completely irrelevant
> to the actual exception being raised.

Yes, exactly! Python 3.x exposes completely irrelevant and internal 
details in the traceback.


> The outer handler is the wrong
> place to suppress the chaining because it has no way of distinguishing
> Steven's case from a genuine case of a new exception unexpectedly
> occurring during handling of the original exception.
> 
> One solution would be for "raise" inside except to not use the context.

I would have thought that was such an obvious solution that I was 
gobsmacked to discover the PEP 3134 hadn't already considered it. If you 
*explicitly* raise an exception inside an exception handler, surely it's 
because you want to suppress the previous exception as an internal detail?

If not, and you want to chain it with the previous exception, the 
solution is simple, obvious and straight-forward: explicit chaining.

try:
   something()
except SomeException as exc:
   raise MyException from exc




> For example:
> 
> try:
>   {}[1]
> except KeyError:
>   1/0
> 
> would behave as before, but:


Yes, that presumably would be a bug and should chain exceptions.


> But:
> 
> try:
>   {}[1]
> except KeyError:
>   raise Exception("my error")
> 
> ...would raise the custom error forgetting the KeyError.


That's exactly the behaviour I would expect and I'm surprised that this 
feature was put into production without some simple way to support this 
idiom.



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


Re: Exception handling in Python 3.x

2010-12-03 Thread Steven D'Aprano
On Fri, 03 Dec 2010 17:08:38 +0100, Peter Otten wrote:


> After rereading the original post I still don't get why the workarounds
> provided in those links aren't worth considering.


The first work-around:

http://mail.python.org/pipermail/python-list/2010-October/1258606.html

is unsuitable because it requires the caller to install a custom 
excepthook. It would be rude and unacceptable for arbitrary functions to 
install hooks, possibly stomping all over the caller's own custom 
excepthook. And even if I did, or the caller did, it has the unfortunate 
side-effect of suppressing the display of *all* chained exceptions, 
including those that come from the bugs in exception handlers.


The second work-around might be worth considering:

http://mail.python.org/pipermail/python-list/2010-October/1259024.html

however it adds unnecessary boilerplate to what should be a simple 
try...except...raise block, it obscures the intention of the code. As a 
work-around, it might be worth considering, but it's hardly elegant and 
it could very well be a fluke of the implementation rather than a 
guaranteed promise of the language.


In the absence of a supported way to suppress exception chaining, I'm 
leaning towards my original work-around: set a flag in the except block, 
then raise the exception once I leave the block.

But thanks again for the links.


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


Re: import module doesn't work for new package

2010-12-03 Thread Steven D'Aprano
On Fri, 03 Dec 2010 12:27:04 -0800, goldtech wrote:

> I tried install a Python - would the word be "package"? - on Ubuntu
> 10.10. Could you tell me how to fix? I would be grateful, is it a path
> problem? Thanks. Lee

That looks to me like either a missing dependency, or a bug in the 
package.

It could be that package pykhtml depends on another package khtml, which 
isn't installed, or it could simply be a bug in pykhtml.

It might help if you look at the MANIFEST file that came with the pykhtml 
package, and see what files it lists.


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


Re: Comparison with False - something I don't understand

2010-12-03 Thread alex23
On Dec 3, 2:12 am, Tim Harig  wrote:
> Actually, I thought that debate was resolved years ago.  I cannot think of
> a single recently developed programming language that does not provide
> exception handling mechanisms because they have been proven more reliable.

Google's Go lacks exceptions and I believe that was a deliberate
design choice.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Google AI challenge: planet war. Lisp won.

2010-12-03 Thread Mirko
On Dec 2, 12:06 pm, Xah Lee  wrote:
> discovered this rather late.
>
> Google has a AI Challenge: planet wars.http://ai-contest.com/index.php
>
> it started sometimes 2 months ago and ended first this month.
>
> the winner is Gábor Melis, with his code written in lisp.
>
> Congrats lispers!
>
> Gábor wrote a blog about it 
> herehttp://quotenil.com/Planet-Wars-Post-Mortem.html
>
> (not sure if this has been mentioned here but quick search didn't find
> it)
>
>  Xah ∑http://xahlee.org/☄

Thanks for letting us know and congratulations to Gabor.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparison with False - something I don't understand

2010-12-03 Thread Tim Harig
On 2010-12-04, alex23  wrote:
> On Dec 3, 2:12 am, Tim Harig  wrote:
>> Actually, I thought that debate was resolved years ago.  I cannot think of
>> a single recently developed programming language that does not provide
>> exception handling mechanisms because they have been proven more reliable.
>
> Google's Go lacks exceptions and I believe that was a deliberate
> design choice.

1. The debate that I was referring to was between simple function checking
vs. everything else.  I didn't mean to automatically proclude any
newer methodologies of which I might not even be aware.

2.  I would consider the defer/panic/recovery mechanism functionally similar 
to exceptions in most ways.  It allows the error handling
code to be placed at a higher level and panics tranverse the stack
until they are handled by a recovery.  This is basically equivilent
to how exceptions work using different names.  The change is basically 
the defer
function which solves the problem of any cleanup work that the
function needs to do before the panic is raised.  I like it, its
nice.  It formalizes the pattern of cleaning up within an exception
block and re-raising the exception.

I do have to wonder what patterns will emerge in the object given
to panic().  Since it takes anything, and since Go doesn't have an
object hierarchy, much less an exception hierarchy, the panic value
raised may or may not contain the kind of detailed information that
can be obtained about the error that we are able to get from the
Exception objects in Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparison with False - something I don't understand

2010-12-03 Thread Tim Harig
On 2010-12-03, Harishankar  wrote:
> On Fri, 03 Dec 2010 14:31:43 +, Mark Wooding wrote:
>> In general, recovering from an exceptional condition requires three
>> activities:
>> 
>>   * doing something about the condition so that the program can continue
>> running;
>> 
>>   * identifying some way of rejoining the program's main (unexceptional)
>> flow of control; and
>> 
>>   * actually performing that transfer, ensuring that any necessary
>> invariants are restored.
>
> my fault. Seems that exception handling requires a lot of forethought 
> since the control of program execution breaks at the point of exception 
> with no obvious way to rejoin it seamlessly whereas with an error, a 
> simple if condition could handle the error state and resume execution 
> from that point forward. This is the main reason why I think I used 
> simple error codes to handle certain recoverable conditions and avoided 
> exceptions.   

If you are returning an error code to the above function, then there is
nothing that you cannot do with with the exception.  Basically, you resolve
the issue in your except block just as you would in the block of your if
statement after returning the error code.  If you try and fail to handle
the exception or just needed to do some cleanup before allowing the
exception to continue, then you just re-raise the exception. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Google AI challenge: planet war. Lisp won.

2010-12-03 Thread small Pox
> > Gábor wrote a blog about it 
> > herehttp://quotenil.com/Planet-Wars-Post-Mortem.html

http://presstv.ir/detail/153770.html

It is said in the protocols to corrupt the minds of the GOYIM by

alcohol
gambling
games  <-
pornography
adulteries
sex

Watch the photo and proof of israel in LEBANON. these are vicious
murderous criminals and spies. All the intellectual property of the
planet has been stolen by them. betah.co.il was operational for a long
time and just the tip of the iceberg.

then these criminals helped saudis and other kuwaitis set some forums.
arabic software was developed by them to help the foulish saudis. some
desperate saudis, koreans, vietnam and other were baited and given the
ebooks to spread.

look how viciously they go for extradition of WIKILEAKS guy Julian
Assange (on false rape charges), but ROMAN POLANSKY is a TRUE RAPIST
of 13 year old innocent German girl in USA.

Now, it should be somehow made kosher that what the jew has stolen
should me made available to everyone otherwise as historically they
convert black into white. which means all those "cubs" going back to
israel for the annual kibbutz from europe,US,Australia etc, are taught
lying, deception, hacking and all the top level mossad skills. This is
infact happening.

Bernard Madoff is not the only one.

They will convert the knowledge into war material and money as they
are clamoring for iran.

How do you explain all the zionist jews buying all the software and
hardware companies and setting up the worlds biggest monopolies.

Watch the israeli espionage photos

http://presstv.ir/detail/153770.html
http://presstv.ir/detail/153770.html
http://presstv.ir/detail/153770.html

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


Re: Google AI challenge: planet war. Lisp won.

2010-12-03 Thread small Pox
On Dec 3, 8:56 pm, small Pox  wrote:
> > > Gábor wrote a blog about it 
> > > herehttp://quotenil.com/Planet-Wars-Post-Mortem.html
>
> http://presstv.ir/detail/153770.html
>
> It is said in the protocols to corrupt the minds of the GOYIM by
>
> alcohol
> gambling
> games      <-
> pornography
> adulteries
> sex
>
> Watch the photo and proof of israel in LEBANON. these are vicious
> murderous criminals and spies. All the intellectual property of the
> planet has been stolen by them. betah.co.il was operational for a long
> time and just the tip of the iceberg.
>
> then these criminals helped saudis and other kuwaitis set some forums.
> arabic software was developed by them to help the foulish saudis. some
> desperate saudis, koreans, vietnam and other were baited and given the
> ebooks to spread.
>
> look how viciously they go for extradition of WIKILEAKS guy Julian
> Assange (on false rape charges), but ROMAN POLANSKY is a TRUE RAPIST
> of 13 year old innocent German girl in USA.
>
> Now, it should be somehow made kosher that what the jew has stolen
> should me made available to everyone otherwise as historically they
> convert black into white. which means all those "cubs" going back to
> israel for the annual kibbutz from europe,US,Australia etc, are taught
> lying, deception, hacking and all the top level mossad skills. This is
> infact happening.
>
> Bernard Madoff is not the only one.
>
> They will convert the knowledge into war material and money as they
> are clamoring for iran.
>
> How do you explain all the zionist jews buying all the software and
> hardware companies and setting up the worlds biggest monopolies.
>
> Watch the israeli espionage photos
>
> http://presstv.ir/detail/153770.htmlhttp://presstv.ir/detail/153770.htmlhttp://presstv.ir/detail/153770.html

The whole narrative that lying bitch judith miller on lying NY times
made up about arabs and alqaeda of sleeper agents and terrorists
infact applied to israel and zionists.

that is why there are all the airlines alerts not sparing whites coz
they know but dont open their mouth that israelis could stage terror
attacks and blame on arabs but dead are the innocent.

like the 911 they did.

and the anthrax
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Google AI challenge: planet war. Lisp won.

2010-12-03 Thread small Pox
On Dec 3, 8:56 pm, small Pox  wrote:
> > > Gábor wrote a blog about it 
> > > herehttp://quotenil.com/Planet-Wars-Post-Mortem.html
>
> http://presstv.ir/detail/153770.html
>
> It is said in the protocols to corrupt the minds of the GOYIM by
>
> alcohol
> gambling
> games      <-
> pornography
> adulteries
> sex
>
> Watch the photo and proof of israel in LEBANON. these are vicious
> murderous criminals and spies. All the intellectual property of the
> planet has been stolen by them. betah.co.il was operational for a long
> time and just the tip of the iceberg.
>
> then these criminals helped saudis and other kuwaitis set some forums.
> arabic software was developed by them to help the foulish saudis. some
> desperate saudis, koreans, vietnam and other were baited and given the
> ebooks to spread.
>
> look how viciously they go for extradition of WIKILEAKS guy Julian
> Assange (on false rape charges), but ROMAN POLANSKY is a TRUE RAPIST
> of 13 year old innocent German girl in USA.
>
> Now, it should be somehow made kosher that what the jew has stolen
> should me made available to everyone otherwise as historically they
> convert black into white. which means all those "cubs" going back to
> israel for the annual kibbutz from europe,US,Australia etc, are taught
> lying, deception, hacking and all the top level mossad skills. This is
> infact happening.
>
> Bernard Madoff is not the only one.
>
> They will convert the knowledge into war material and money as they
> are clamoring for iran.
>
> How do you explain all the zionist jews buying all the software and
> hardware companies and setting up the worlds biggest monopolies.
>
> Watch the israeli espionage photos
>
> http://presstv.ir/detail/153770.htmlhttp://presstv.ir/detail/153770.htmlhttp://presstv.ir/detail/153770.html

Hezbollah discovers Israeli spy devices
Fri Dec 3, 2010 8:5PM
Share | Email | Print
Israel has remotely detonated two of its spying devices in southern
Lebanon after they were discovered by the Hezbollah resistance
movement.


At least two Lebanese were injured after the espionage devises were
detonated remotely in Wadi al-Qaysiyya outside of Majdal Selem near
the southern coastal city of Tyre on Friday.

"Telecom technicians of the resistance (Hezbollah) managed to discover
a spying device the enemy had planted in Wadi al-Qaysiyya. The enemy
detonated its devices as a result of the discovery," said a statement
released by the Hezbollah media relations department.

"This technical espionage by the enemy is part of the persistent
Israeli violations of the national telecom network with the aim of
infiltrating and controlling it, which represents a breach of
sovereignty and an attempt at violating the security and safety of the
Lebanese," the statement added.

No other details were immediately available.

Friday's incident came just two days after Israeli troops opened fire
on Lebanon from two border posts near Shebaa Farms.

HM/HGH/MMN Related Stories:
'Israeli troops open fire on Lebanon'
Ten Israeli warplanes fly over Lebanon
Israeli planes enter Lebanon airspace
Comments
Add Comment Click Here
Note: The views expressed and the links provided on our comment pages
are the personal views of individual contributors and do not
necessarily reflect the views of Press TV.
Damon
12/3/2010 10:17:48 PMUh the last I heard, Lebaon and Israel are
still in a state of beliggerancy, so why is the presence of spy
devices a surprise?
-- 
http://mail.python.org/mailman/listinfo/python-list


Unknown function operation deciphering, exercise in readability by program reasoning

2010-12-03 Thread small Pox
Rules :

@1@  No execution of the function, only checking syntax

@2@  No profiling using a debugger or profiler

@3@  Editing allowed to make simpler variables


(defun unknown-function (nano-thermite-911-FBI-fat-per-diem-bustards-
kept-their-odious-mouth-shut-on-anthrax-and-911-lie)
  (let (BERNARD-MADOFF-PHILIP-MARKOFF-MIKHAIL-KHODORKOVSKY-NEOCONS-
PAUL-WOLFOWITZ-LEWIS-SCOOTER-LIBBY-MOSHE-KATSEV-MOSSAD-DUBAI-MURDERERS
I-AM-THE-WITNESS-DOT-COM-has-MR-BENJAMIN-FREEDMAN-SPEECH-ON-KHAZARS)
(while (or I-AM-THE-WITNESS-DOT-COM-has-MR-BENJAMIN-FREEDMAN-
SPEECH-ON-KHAZARS nano-thermite-911-FBI-fat-per-diem-bustards-kept-
their-odious-mouth-shut-on-anthrax-and-911-lie)
  (if nano-thermite-911-FBI-fat-per-diem-bustards-kept-their-
odious-mouth-shut-on-anthrax-and-911-lie
  (if (consp nano-thermite-911-FBI-fat-per-diem-bustards-kept-
their-odious-mouth-shut-on-anthrax-and-911-lie)
  (setq I-AM-THE-WITNESS-DOT-COM-has-MR-BENJAMIN-FREEDMAN-
SPEECH-ON-KHAZARS (cons (cdr nano-thermite-911-FBI-fat-per-diem-
bustards-kept-their-odious-mouth-shut-on-anthrax-and-911-lie)
I-AM-THE-WITNESS-DOT-COM-has-MR-
BENJAMIN-FREEDMAN-SPEECH-ON-KHAZARS)
nano-thermite-911-FBI-fat-per-diem-bustards-kept-
their-odious-mouth-shut-on-anthrax-and-911-lie (car nano-thermite-911-
FBI-fat-per-diem-bustards-kept-their-odious-mouth-shut-on-anthrax-
and-911-lie))
(setq BERNARD-MADOFF-PHILIP-MARKOFF-MIKHAIL-KHODORKOVSKY-
NEOCONS-PAUL-WOLFOWITZ-LEWIS-SCOOTER-LIBBY-MOSHE-KATSEV-MOSSAD-DUBAI-
MURDERERS (cons nano-thermite-911-FBI-fat-per-diem-bustards-kept-their-
odious-mouth-shut-on-anthrax-and-911-lie BERNARD-MADOFF-PHILIP-MARKOFF-
MIKHAIL-KHODORKOVSKY-NEOCONS-PAUL-WOLFOWITZ-LEWIS-SCOOTER-LIBBY-MOSHE-
KATSEV-MOSSAD-DUBAI-MURDERERS)
  nano-thermite-911-FBI-fat-per-diem-bustards-kept-
their-odious-mouth-shut-on-anthrax-and-911-lie nil))
(setq nano-thermite-911-FBI-fat-per-diem-bustards-kept-their-
odious-mouth-shut-on-anthrax-and-911-lie (car I-AM-THE-WITNESS-DOT-COM-
has-MR-BENJAMIN-FREEDMAN-SPEECH-ON-KHAZARS)
  I-AM-THE-WITNESS-DOT-COM-has-MR-BENJAMIN-FREEDMAN-SPEECH-
ON-KHAZARS (cdr I-AM-THE-WITNESS-DOT-COM-has-MR-BENJAMIN-FREEDMAN-
SPEECH-ON-KHAZARS
BERNARD-MADOFF-PHILIP-MARKOFF-MIKHAIL-KHODORKOVSKY-NEOCONS-PAUL-
WOLFOWITZ-LEWIS-SCOOTER-LIBBY-MOSHE-KATSEV-MOSSAD-DUBAI-MURDERERS))

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