Re: Project layout / Import files from different subdirectories

2008-11-15 Thread Gabriel Genellina
En Tue, 11 Nov 2008 09:29:44 -0200, Stef Mientki <[EMAIL PROTECTED]>  
escribió:



On Tue, Nov 11, 2008 at 8:46 AM, Markus Mayer <[EMAIL PROTECTED]> wrote:


I'm new to python and have a slight problem importing - or maybe
understanding - modules. I'm writing a GUI application using Qt4 and
wanted to separate the business from the view logic. So I have my folder
structure as following:

project/ main.py
important.py

project/ gui/ __init__.py
 mainwindow.py
 anotherwindow.py

Now I can import mainwindow etc. from main and important, but how do I
do it the other way round?

Also, is there maybe a better project layout? I couldn't find anything
useful on it asking Dr. Google.



Since a couple of days,


(good to know it's not a long established practice!)


I use this construct and it seems to work quite well,
  http://mientki.ruhosting.nl/data_www/pylab_works/pw_importing.html


uhm... I don't think extending sys.path to include every package is a good  
idea. You're basically flattening the directory structure. Just put all  
your stuff in a single directory if this is what you want -- if that's not  
what you want, it is what you are actually doing, anyway.
Among other nasty things, you may end up having multiple copies of the  
same module, when imported using different names.


--
Gabriel Genellina

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


Re: Official definition of call-by-value (Re: Finding the instance reference...)

2008-11-15 Thread Aaron Brady
On Nov 15, 12:51 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Fri, 14 Nov 2008 22:56:52 -0500, Terry Reedy wrote:
snip
> I would say that the answer to this is, "Would you like to include
> behaviour in value?". Let me give you an example:
>
> class String(string):
>     def upper(self):
>         return "spam"
>
> s1 = "Norwegian Blue"
> s2 = String("Norwegian Blue")
>
> Do s1 and s2 have the same value?
>
> Using definition (1) above, we can see that the names s1 and s2 refer to
> different objects, so the names have different values.
>
> Using definition (2), the objects s1 and s2 have different concrete
> expressions, and so they are different values. (Remember: the object is
> the value.) But from definition (3) they both represent that same
> abstract string, so if I care only about that level of description, I'd
> say yes they *have* the same value but *are* different values.
>
> Assuming I cared about the behaviour of upper(), then s2 is probably not
> suitable for my purposes and so I would like to distinguish s1 from s2.
> I'd insist that they have different values which merely looked the same
> under equality. To use the bank note analogy, then s1 is legal tender but
> s2 is just a very good forgery.
>
> But note that to a collector of forgeries, s2 might be more valuable than
> s1, and presumably the writer of class String had a reason for the
> behaviour given. The answer to the question "do s1 and s2 have different
> values" will depend on why you are asking.
>
snip
> I would say that although value is dependent on context, that's no excuse
> for concluding that it has no meaning. If you look too closely at
> *anything*, it becomes fuzzy. (Well, with the possible exception of pure
> mathematics.)
>
> --
> Steven

I'm reading that the result of the __eq__ comparison isn't the only
meaning of value, and that there is more than one.

>>> class String(str):
... def upper(self):
... return "spam"
...
>>> s1 = "Norwegian Blue"
>>> s2 = String("Norwegian Blue")
>>> s1== s2
True
>>> s1.upper()== s2.upper()
False

Murmur, good.  I could see rejecting that two objects of different
types can have the same value.  I could also see rejecting that 'the
value than an object is' is nonsense, permitting only 'the value that
an object has'.  However, as a counterexample, 'x has the value [1, 2,
3]' and 'x is [1, 2, 3]' are both colloquially sensical statements,
though the latter is imprecise, because 'x is [1, 2, 3], y is [1, 2,
3], x is not y'; certainly '[1, 2, 3]' is neither 'x' nor 'y', and
identity is a commutative relation.

If you'll permit a tangent into another (computer) language, I don't
have a problem saying either that the value of x in 'int* x' in C is a
memory address, or that its value is an integer, which stance is
definitely prone to miscommunication.  I still maintain that passing
an object by value calls its copy constructor.
--
http://mail.python.org/mailman/listinfo/python-list


Re: duck-type-checking?

2008-11-15 Thread Arnaud Delobelle

Duck typing...

For a while I thought the word _duck_ was used in the sense of _dodge_.

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


Re: duck-type-checking?

2008-11-15 Thread Steven D'Aprano
On Sat, 15 Nov 2008 20:00:03 +1300, greg wrote:

> Joe Strout wrote:
> 
>> So, in this case, the simplest solution was to have the method that
>> initially accepts and stores the data check to make sure that data
>> satisfies the assumptions of the class.
> 
> In hindsight, yes, but the trouble is that you can't tell ahead of time
> which of the gazillion places in the code that where you store things
> away in containers are likely to cause a problem later.
> 
> I can't imagine myself writing code to check every argument to every
> method to guard against this sort of thing. 

Which is, of course, the weakness of dynamic typed languages like Python. 
With statically typed languages like Pascal and C, you can get the 
compiler to check that for you (often at compile time), but at the cost 
of a lot more effort up front. And with languages like Haskell, the type 
inference engine can do much of that type checking without you needing to 
make explicit type declarations.


> If you're willing to do
> that, it's up to you, but it's far from common practice in Python
> programming.

True. It's generally more efficient for the programmer's time to let the 
function or method fail where ever it happens to fail, rather than trying 
to get it to fail up front. But the cost of this is that sometimes it's 
*less* efficient for the programmer, because he has no idea where the 
offending object was injected into the code.

I wonder whether the best solution is to include all your type checks 
(isinstance or duck-typing) in the unit tests, so you can avoid paying 
the cost of those tests at runtime? If your code passes the unit tests, 
but fails with real data, then your unit tests aren't extensive enough.



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


Re: multiple breaks

2008-11-15 Thread Robert Lehmann
On Thu, 13 Nov 2008 02:16:32 -0800, Chris Rebert wrote:

> On Thu, Nov 13, 2008 at 2:07 AM, TP <[EMAIL PROTECTED]>
> wrote:
>>
>> In the following example, is this possible to affect the two iterators
>> to escape the two loops once one "j" has been printed:
>>
> Non-exception alternative:
> 
> done = False
> for i in range(5):
>for j in range(i):
>   print j
> done = True
> break
> if done:
> break

Another alternative is explicitly jumping in the outer loop::

  for i in range(5): # use xrange for larger ranges
  for j in range(i):
  print j
  break
  else:
  continue # applies already to the outer loop
  break

HTH,

-- 
Robert "Stargaming" Lehmann
--
http://mail.python.org/mailman/listinfo/python-list


Good practice when writing modules...

2008-11-15 Thread r0g
I'm collecting together a bunch of fairly random useful functions I have
written over the years into a module. Generally speaking is it best to

a) Import all the other modules these functions depend on into the
modules global namespace by putting them at the top of the module or
should I...

b) Include them in each function individually.

Stylistically I like the idea of b) better as it makes for easy
refactoring in the future but is there any drawback to doing it this
way? i.e. does it get repeatedly parsed, use more memory, become
inefficient when several functions that use the same includes are
invoked etc Or does it really not matter?

Performance is probably not important for the majority of these
functions but there's the odd one that may end up in an inner loop some day.

Cheers,

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


Re: Good practice when writing modules...

2008-11-15 Thread Arnaud Delobelle
r0g <[EMAIL PROTECTED]> writes:

> I'm collecting together a bunch of fairly random useful functions I have
> written over the years into a module. Generally speaking is it best to
>
> a) Import all the other modules these functions depend on into the
> modules global namespace by putting them at the top of the module or
> should I...
>
> b) Include them in each function individually.
>
> Stylistically I like the idea of b) better as it makes for easy
> refactoring in the future but is there any drawback to doing it this
> way? i.e. does it get repeatedly parsed, use more memory, become
> inefficient when several functions that use the same includes are
> invoked etc Or does it really not matter?

I guess it costs you a dictionary lookup (in sys.modules) and an
assignment every time the import statement is executed.  But the module
is not reimported every time.

> Performance is probably not important for the majority of these
> functions but there's the odd one that may end up in an inner loop some day.

It depends on the function but unless it is a function with special
status (such as testing, or a main() function) I would import stuff at
the top of the module.  I makes it clear what the module depends on.

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


Re: Question: what to do, my Python is getting crazy

2008-11-15 Thread Gabriel Genellina
En Fri, 14 Nov 2008 18:21:17 -0200, Pekeika  
<[EMAIL PROTECTED]> escribió:



Good morning group,

When I open my Python window, this is appearing instead of the command
line >>>. (I'm somehow new to Python).

  File "boot_com_servers.py", line 21, in 
  File "C:\Python25\lib\site-packages\pythoncom.py", line 3, in

pywintypes.__import_pywin32_system_module__("pythoncom", globals
())
  File "C:\Python25\lib\site-packages\win32\lib\pywintypes.py", line
98, in __import_pywin32_system_module__
('.dll', 'rb', imp.C_EXTENSION))
ImportError: DLL load failed: The specified procedure could not be
found.


Do you mean, you just type python  at the command prompt, and get  
the above error?
Please post the *entire* traceback you get - the first lines are important  
too.



I also noticed that the "queue" is not working, along with other basic
commands.


Which "queue"? Which basic commands?


What should I do?
I'm afraid to update and replace all the modules that I have compiled
and installed in my directory, and don't know how to do it without
damaging everything...
PLEASE HELP!


Try starting Python from an empty directory. Maybe you inadvertidly  
aliased some standard module with another module of your own (like  
"site.py", "user.py"...)

Also, try starting Python using: python -v
and look for some module imported from your own directories, not from the  
Python standard library.


--
Gabriel Genellina

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


Re: special editor support for indentation needed.

2008-11-15 Thread John Yeung
This is such a fascinating and compelling thread that it has pulled me
out of lurker mode.

Eric, I would like to say I also admire your initiative, but even more
so your patience.  You seem to handle comments of all types
gracefully.

Perhaps it comes from working with speech recognition so much.  I
imagine that if you are using a speech-based programming environment
and get frustrated with how stupid it is, and tell it off, you only
manage to create more of a mess for yourself to clean up.  I think
most of us who rely on our vision and typing lose our cool more
easily, partly because the penalty for us is not as great.

Anyway, sorry for being a bit off-topic.  I'm afraid I don't have a
lot to offer on the topic.  My thoughts as I was reading the earlier
comments is that Python, by its nature, is extremely flexible and thus
inherently tough to map to a speech-only interface.  "Flatter"
languages would seem better suited, but then they tend to be lower-
level, thus more verbose, thus what you gain in lack of ambiguity
might be lost in having to produce more code.

If it is to be Python after all, it seems the strategy you have in
mind is to make the typical patterns as easy as possible, and either
not allow for the more exotic ones or settle for making them much more
complicated to achieve.  You also seem to have a pretty clear idea of
the behaviors you want already.

I think your best bet is to stick with Emacs.  It's the only editor I
know of which is almost fully programmable without recompiling, and
it's available for Windows.  (I am not clear on whether you already
use Emacs for Windows, or whether you remotely use Emacs on Linux,
from Windows.)

It does sound like you have to do a bit of Emacs Lisp programming to
get what you want, but I'd guess that's easier than modifying some
other editor to do what you want, or modifying the way you issue
instructions to fit a more visually oriented style.

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


Redirect Graphical output

2008-11-15 Thread Indian
Hi Friends,

Is there any way we can redirect graphical output to some file
What i require is to run a test for my function but it involves dialog boxes
but a test shld be run without user intervention :(


import sys
import dialog
import wx
app = wx.PySimpleApp()
sys.stdout = open('c:\\abc.txt','w')
dialog.ConfirmMessageBox('hello','abdul',wx.OK)
sys.stdout=sys.__stdout__

I was trying to use the above code but noticed it was tough to redirect to a
file
Please help :)

Thanks in advance
--
http://mail.python.org/mailman/listinfo/python-list


don't get JPE (Java Python Extension) compiled.

2008-11-15 Thread Tamer Higazi
Hi people!
I want to compile the Java Python Extension which I downloaded through
CVS "http://jpe.cvs.sourceforge.net/jpe/";

Building JPE by bootstrapping the makefile system with the cmd:

"python makefile.py"

from the top source directory.

I receive the following error message:

working in 
use make command 

ksh /home/tamer/JPE/libplus/bin/pybatch.ksh /home/tamer/JPE/libplus
/usr/bin/python -c "import devkit; devkit.pythonexe = None; import imp;
imp.load_source( 'makefile', 'makefile.py', open(
'makefile.py')).genmake()"
/bin/sh: ksh: command not found
make: *** [all] Error 127



for any help solving my problem getting JPE compiled, I would thank you
very much


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


Re: ElementTree XML Namspace

2008-11-15 Thread Stefan Behnel
Hunter wrote:
> We are reviewing a vendor who will output some data in an XML format.
> I will then use python to convert the data to another format for
> upload to another vendor.

Take a look at lxml.objectify, it has a nicer API, especially if you are new
to XML. It also handles loads of namespace issues under the hood, so that you
don't get bothered with them.

http://codespeak.net/lxml/objectify.html#element-access-through-object-attributes
http://codespeak.net/lxml/objectify.html#namespace-handling

You said "reviewing". Does that indicate that you need validation?

http://codespeak.net/lxml/validation.html
http://codespeak.net/lxml/objectify.html#asserting-a-schema

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


Optional parameter object re-used when instantiating multiple objects

2008-11-15 Thread Rick Giuly
Hello All,

Why is python designed so that b and c (according to code below)
actually share the same list object? It seems more natural to me that
each object would be created with a new list object in the points
variable.

class Blob:
def __init__(self, points=[]):
self._points = points


b = Blob()
c = Blob()

b._points.append(1)
c._points.append(2)

print b._points

# this will show that b._points is the same object as c._points









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



Re: Optional parameter object re-used when instantiating multiple objects

2008-11-15 Thread Arnaud Delobelle
Rick Giuly <[EMAIL PROTECTED]> writes:

> Hello All,

Hello,

> Why is python designed so that b and c (according to code below)
> actually share the same list object? It seems more natural to me that
> each object would be created with a new list object in the points
> variable.
>
> class Blob:
> def __init__(self, points=[]):
> self._points = points
>
>
> b = Blob()
> c = Blob()
>
> b._points.append(1)
> c._points.append(2)
>
> print b._points
>
> # this will show that b._points is the same object as c._points

This is probably the MFAQ (Most FAQ)!

Have a look in http://www.python.org/doc/faq/ (I can't point at the
question as my internet pipes to the US are very rusty this morning)

HTH

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


Re: Good practice when writing modules...

2008-11-15 Thread bearophileHUGS
r0g:
> a) Import all the other modules these functions depend on into the
> modules global namespace by putting them at the top of the module or
> should I...
> b) Include them in each function individually.

This is a interesting topic, that requires some care.
Generally I suggest you put them at the top, so they can be found and
seen with less problems (*), it's the standard.
If a function is called only once in a while (like a plotting
function), and to import its module(s) it needs lot of time and memory
(like matplotlib), then you may move the import inside the function
itself, especially if such function isn't speed-critical.


(*)
I generally agree with the PEP8 but regarding this I don't follow it:
I feel free to put more than one of them on the same line:
import os, sys, ...
I generally list the built-in modules first, then the well known one
(pyparsing, numpy, etc), and then my ones or less known ones.

I also put a comment after each import, with the name of the function/
class it is used into:

import foo # used by baz()
import bar # used by spam()

...
def baz(n):
return foo(n) * 10
...
def spam(k):
return bar(k) - 20

Time ago I have read an interesting article that says that comments of
today will often become statements and declaration and tags of
tomorrow, that is stuff that the interpreter/compiler/editor
understands. This means that such annotations of mine may be something
fit to become a syntax of the language. I don't have ideas on how such
syntax can be, if you have suggestions I'm listening.

Finally in modules that contain many different things, and where each
of them uses generally distinct modules, as a compromise I sometimes
write code like this:

import foo # used by baz()

def baz(n):
return foo(n) * 10


import bar # used by spam()

def spam(k):
return bar(k) - 20

My editor has a command that finds and lists me all the global imports
(not indented) of the module.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Redirect Graphical output

2008-11-15 Thread Gabriel Genellina
En Sat, 15 Nov 2008 07:27:47 -0200, Indian <[EMAIL PROTECTED]>  
escribió:



Is there any way we can redirect graphical output to some file
What i require is to run a test for my function but it involves dialog  
boxes

but a test shld be run without user intervention :(


import sys
import dialog
import wx
app = wx.PySimpleApp()
sys.stdout = open('c:\\abc.txt','w')
dialog.ConfirmMessageBox('hello','abdul',wx.OK)
sys.stdout=sys.__stdout__

I was trying to use the above code but noticed it was tough to redirect  
to a

file
Please help :)


(I don't get what the above code is supposed to perform)
You're right, unit tests should run without user intervention. So in  
principle, the function being tested should not call a dialog box  
directly. There are several strategies to deal with that, as a general  
rule, try to separate the user interfase from the "processing" code.


--
Gabriel Genellina

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


Re: Official definition of call-by-value (Re: Finding the instance reference...)

2008-11-15 Thread Arnaud Delobelle
[EMAIL PROTECTED] writes:

> I have yet to see any reasonable definition of a Python
> value in the Python docs or elsewhere, despite the fact
> that a value is one of the three defining characteristics
> of an object, a central concept in Python.

I don't remember how the expression 'object value' is used in the Python
docs (and python.org is unreachable from where I am at the moment) but I
know that I don't need such a concept to understand, or code in, Python.

Objects have a type, may have attributes, and that's it!

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


Re: best python unit testing framwork

2008-11-15 Thread James Harris
On 15 Nov, 01:02, "Brendan Miller" <[EMAIL PROTECTED]> wrote:
> On Thu, Nov 13, 2008 at 3:54 AM, James Harris
>
>
>
> <[EMAIL PROTECTED]> wrote:
> > On 11 Nov, 22:59, Brendan Miller <[EMAIL PROTECTED]> wrote:
> >> What would heavy python unit testers say is the best framework?
>
> >> I've seen a few mentions that maybe the built in unittest framework
> >> isn't that great. I've heard a couple of good things about py.test and
> >> nose. Are there other options? Is there any kind of concensus about
> >> the best, or at least how they stack up to each other?
>
> > You don't mention what you want from testing so it's hard to say which
> > is "best" as it depends on one's point of view.
>
> > For example, I had a requirement to test more than just Python
> > programs. I wanted to test code written in any language. None of the
> > frameworks I found supported this so I wrote my own tester. It
> > interacts with programs via file streams - principally stdin, stdout
> > and stderr though others can be added as needed.
>
> I was speaking to unit tests (tests of individual classes and
> functions in isolation of the rest of the program) and a test driven
> development approach. I find those to be much more useful, and good
> for pinpointing bugs and guiding development. In contrast regression
> tests tend to be slow, and are the programmatic equivalent of kicking
> the tires and seeing if they fall off.

I agree with your points but would add

1. We should write smaller modules than we generally do. It promotes
clear thinking and encourages the production of reusable code. In
Python it is easy to add a __main__ section to interface to the
classes or functions defined in the code. Such code can then be tested
as mentioned. The functions or classes can still be imported into and
used in other code as needed.

2. The example given wasn't intended to be the only way forward but to
highlight that what makes a test package good depends on your
requirements (which I don't think you mentioned). In my case the
desire to test arbitrary languages was a killer blow to various Python-
only frameworks which I wasn't too impressed with anyway. (At least I
saw none that looked worth investing the time to learn.) Similarly an
option for you is to write your own tester. It may be a better fit
than someone else's package and not too hard to do. On the other hand
a pre-written package may be better - depending on what you are
looking for.


> I've also seen regression tests lead to a "sweep the bugs under the
> rug mentality" where developers will code to prevent errors from
> crashing the regression test, e.g. by catching and swallowing all
> exceptions without fixing the underlying problem. It's easy to fool
> regression tests since what it does works at such a high level that
> most aspects of program correctness can't be directly checked. This is
> very frustrating to me because it actually leads to lower code
> quality.


If you have dodgy developers then much is wrong, not just testing. If
the team works well, IMHO, production of test cases should be a
welcome part of the development process. When is it better to find
bugs: before or after shipping to a client? Test cases can be put
together in various ways. For example, if one has the code and chooses
to work this way white-box testing can lead to generation of test
cases. On the other hand if an organisation prefers it can produce
test cases from the spec - or they can do both. It's their choice but
in any case the developers and testers should work together.


> > One nice by-product is that test code does not bloat-out the original
> > source which remains unchanged.
>
> That's the main reason most people don't write unit tests. It forces
> them to properly decouple their code so that parts can be used
> independently of one another. Adding such things to messy ball of mud
> code after the fact is an enourmous pain in the butt. Thankfully,
> since python is duck typed and doesn't require lots of boilerplate
> writing interfaces and abstract factories (since the class object
> itself acts as an abstract factory), writing properly decoupled code
> in the first place doesn't look nearly as hard as in C++ or Java.

You could still import one Python module into another to run test
cases such as

-
import test_support
import 


-

where the tests can interact directly with the components of the code
under test. The test support code can handle things such as collating
results and reporting as well as providing code to directly support
certain tests, handle exceptions etc.

I wouldn't be surprised if good testing code were in many cases to be
significantly longer than the code being tested. Keeping the tests in
a separate file keeps the code being tested shorter which can only
improve clarity. It also allows either the developer or someone else
to write the tests. Putting code and testing code in the same file
almost requires one person to write both parts.

A final thought:

english

2008-11-15 Thread shasha12
En Sat, 15 Nov 2008 07:27:47 -0200, Indian <[EMAIL PROTECTED]>
escribió: ...(I don't get what the above code is supposed to perform)
You're right, unit tests should run without user intervention. So in
principle, the function being tested should not call a dialog box
directly. There are several strategies to deal with that, as a
general... more »
By Gabriel Genellina
--
http://mail.python.org/mailman/listinfo/python-list


comp.lang.python

2008-11-15 Thread shasha12
The Python computer language.
Language: English
--
http://mail.python.org/mailman/listinfo/python-list


Suggest a Labs feature

2008-11-15 Thread shasha12
 Language:English
--
http://mail.python.org/mailman/listinfo/python-list


Re: Good practice when writing modules...

2008-11-15 Thread r0g
[EMAIL PROTECTED] wrote:
> r0g:
>> a) Import all the other modules these functions depend on into the
>> modules global namespace by putting them at the top of the module or
>> should I...
>> b) Include them in each function individually.
> 
> This is a interesting topic, that requires some care.
> Generally I suggest you put them at the top, so they can be found and
> seen with less problems (*), it's the standard.
> If a function is called only once in a while (like a plotting
> function), and to import its module(s) it needs lot of time and memory
> (like matplotlib), then you may move the import inside the function
> itself, especially if such function isn't speed-critical.
> 
> 
> (*)
> I generally agree with the PEP8 but regarding this I don't follow it:
> I feel free to put more than one of them on the same line:
> import os, sys, ...
> I generally list the built-in modules first, then the well known one
> (pyparsing, numpy, etc), and then my ones or less known ones.
> 
> I also put a comment after each import, with the name of the function/
> class it is used into:
> 
> import foo # used by baz()
> import bar # used by spam()
> 
> ...
> def baz(n):
> return foo(n) * 10
> ...
> def spam(k):
> return bar(k) - 20
> 
> Time ago I have read an interesting article that says that comments of
> today will often become statements and declaration and tags of
> tomorrow, that is stuff that the interpreter/compiler/editor
> understands. This means that such annotations of mine may be something
> fit to become a syntax of the language. I don't have ideas on how such
> syntax can be, if you have suggestions I'm listening.
> 
> Finally in modules that contain many different things, and where each
> of them uses generally distinct modules, as a compromise I sometimes
> write code like this:
> 
> import foo # used by baz()
> 
> def baz(n):
> return foo(n) * 10
> 
> 
> import bar # used by spam()
> 
> def spam(k):
> return bar(k) - 20
> 
> My editor has a command that finds and lists me all the global imports
> (not indented) of the module.
> 
> Bye,
> bearophile



Thanks for the suggestions guys. I hadn't thought about putting comments
after the imports, that's a good idea, although I guess you need to be
disciplined in keeping them up to date.  All the same, given the
seemingly negligible performance hit and the nature of this particular
module I think I will probably go with includes within the functions
themselves anyway...

The module I am compiling is kind of a scrapbook of snippets for my own
development use, it has no coherent theme and I wouldn't be distributing
it or using the whole thing in a production environment anyway, just
copying the relevant functions into a new module when needed. I'm
thinking having the imports inline might make that process easier when I
do need to do it and once copied I can always move them out of the
functions declarations.

Having said that, having your editor trace these dependencies for you is
an interesting idea too. Which editor are you using? (not trying to
start an editor flame war anyone, shh!). Can this be done from idle or
are you aware of a python script that can do this maybe?

Thanks again,

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


Re: best python unit testing framwork

2008-11-15 Thread Kay Schluehr
On 11 Nov., 23:59, Brendan Miller <[EMAIL PROTECTED]> wrote:
> What would heavy python unit testers say is the best framework?
>
> I've seen a few mentions that maybe the built in unittest framework
> isn't that great.

The UT frameworks follow the same principles and are all alike more or
less. Of course doctest makes a difference and implies another
approach to testing but whether you use unittest, nosetest or py.test
is mostly a matter of taste. Of course taste matters a lot for various
people and when they have to use CamelCased method names like setUp or
assertEqual in Python they feel alienated and reminded that Java is
out there.

Personally I use unittest.py for a pretty obvious reason: other people
can simply run the test scripts without prior installation of a
testframework.

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


Re: special editor support for indentation needed.

2008-11-15 Thread [EMAIL PROTECTED]
On Nov 14, 9:01 pm, "Eric S. Johansson" <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> >  I don't understand. If you don't want to terminate the "if", why do
> > you hit backspace? What is it that you would like to have happen?
>
> the goal is to make some aspects of indentation behave the same without 
> context
> dependency.  this goal exists for many features of programming assistance
> because it's a prerequisite for lowering the vocal load for this aspect of
> programming by voice
>
> I want three indentation adjustment tools.  Indent to where a class should be,
> indent to where a method should be, and outdent n levels (close block
> (once|twice|thrice)).  This is probably best shown by example although, I'm 
> not
> guaranteeing my example will make it any clearer.  :-)
>
> the current outdent capability conflates multiple outdent events.  The outdent
> events are, at a minimum,:
>
> Close block
> close method
> close class
>
> Another way to look at these events are start method, start class and close
> block.  Now using these events, let's compare a use case against the outdent
> mechanism.
>
> starting with an example of a previous message,
>
> class pet (object):
>     """
>     """
>     def cat(self):
>         """
>         """
>         if food in bowl:
>             self.empty = True
>
>     def dog(self):
>
> to start the dog method, after ending the Method, I would need to say 
> something
> like:
>
> newline tab key Close block close block delta echo foxtrot dog left paren self
> close paren colon...
>
> But if the method ended like:
>
>     ...
>
>     def cat(self):
>         """
>         """
>         self.empty = True
>
>     def dog(self):
>
> I would only want to use a single "close block" to outdent.  unfortunately, 
> this
>  context dependent behavior is frustratingly wrong when it comes to creating
> speech driven macros to enter templates.  it requires user intervention to 
> tell
> you how may times to outdent and that's counterproductive at best and 
> physically
> damaging at worst for a disabled user.
>
> any clearer?
I still don't understand. It seems that you want to be able to do:
"END_CLASS"  to end the current class.

"END_DEF" to end the current function

"END_BLOCK" to end anything else.

This is possible with some emacs lisp but I don't see what this gains
you over
"BACK" "BACK" "BACK"
  where "BACK" sends a backspace to emacs.
  (Actually I'd define an "END" command which you could give at the
end of the last line of a block. That would relieve you of the need to
enter the newline and tab.)
  Yes, it requires a few extra utterances on occasion, but you don't
have to worry about three new (multi-syllabic) verbs to recognize.

 Am I understanding your requirement correctly?
--
http://mail.python.org/mailman/listinfo/python-list


Re: [UnicodeEncodeError] Don't know what else to try

2008-11-15 Thread Gilles Ganault
On Fri, 14 Nov 2008 17:39:00 +0100, "Martin v. Löwis"
<[EMAIL PROTECTED]> wrote:
>Can you first please report what happened when you add the print statement?

Thanks guys, I found how to handle this:

===
for id in rows:
#Says Unicode, but it's actually not
#print type(id[1])
#

try:
print id[1];
except UnicodeEncodeError:
print "Not unicode"
try:
print id[1].encode('iso8859-15')
print "iso"
except UnicodeEncodeError:
print id[1].encode('cp1252')
print "Windows"
===

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


Comparing value in two dictionaries?

2008-11-15 Thread Gilles Ganault
Hello

I fill two dictionaries with the same number of keys, and then need to
compare the value for each key, eg.

#Pour chaque APE, comparaison societe.ape.nombre et verif.ape.nombre
import apsw

#
dic1={}
[...]
rows=list(cursor.execute(sql))
for id in rows:
dic1[id[0]] = id[1]
#
dic2={}
[...]
rows=list(cursor.execute(sql))
for id in rows:
dic2[id[0]] = id[1]
#
#Here, compare each key/value to find values that differ
for i in dic1.items():
[...]

What would be a good way to do this in Python?

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


The Best Way To earn Money From The Internet

2008-11-15 Thread [EMAIL PROTECTED]

http://bux.to/?r=mr-sk8er
At Bux.to, you get paid to click on ads and visit websites. The
process is easy! You simply click a link and view a website for 30
seconds to earn money. You can earn even more by Referring Friends.
You'll get paid $0.01 for each website you personally view and $0.01
for each website your referrals view. Payment requests can be made
every day and are processed through Papal. The minimum payout is
$10.00.
U don’t have a paypal account
Its for free from here www.paypal.com
Earnings Example:
» You click 10 ads per day = $0.10
» 20 referrals click 10 ads per day = $2.00
» Your daily earnings = $2.10
» Your weekly earnings = $14.70
» Your monthly earnings = $63.00
The above example is based only on 20 referrals and 10 daily clicks.
Some days you will have more clicks available, some days you will have
less. What if you had more referrals? What if there were more ads
available?
Click here to sign up http://bux.to/?r=mr-sk8er
How Bux.to works

How you make money
You view websites in 30 second sessions via the "Surf Ads" page. Once
the 30 seconds is up, you'll either get a green tick sign or a red
'X'. The green tick sign means you've earned $0.01 and as premium
member $0.0125 for the visit and the 'X' means you have not earned
money for the visit. You'll get red X's when you have more than one
website from the "Surf Ads" page open. When this happens, you get no
credit.

A valuable benefit to both the members and the advertisers is the
repeat exposure that the advertiser gets. Whenever you click and view
a website, you can visit that website again in 24 hours as long as the
visit cap hasn't been reached. That's right! After 24 hours you can
click and view the website again. This gives the advertiser optimal
exposure by using "repeat advertising" and it further increases the
members earning potential.

you can also buy referrals packages
You can purchase 500 of these un-referred Bux.to members for a price
of only $459.00. This is an extremely low price to pay when you sit
back and imagine your profits. In fact, based on averages, 500 active
referrals can bring you
» 500 referrals click 10 ads per day = $50.00
» Your daily earnings = $50.00
» Your weekly earnings = $350.00
» Your monthly earnings = $1,500.00
Are u still waiting???
Signup from here http://bux.to/?r=mr-sk8er

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


Re: Comparing value in two dictionaries?

2008-11-15 Thread bearophileHUGS
Gilles Ganault:
> I fill two dictionaries with the same number of keys, and then need to
> compare the value for each key, eg.

Probably using the DBMS capabilities you can find a better solution.

Are the keys equal? If you want to do it using dicts, you can iterate
on one dict, with iteritems, and then using the key look for the value
of the second dict, to see if they are the same, to collect
differences, etc.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Regular expression and exception

2008-11-15 Thread Mr . SpOOn
Hi,
I've never used exception before, but I think now it's time to start.

I've seen that there is a list of  the built-in exceptions in the
Python docs, but this explains the meaning of every exception. Does
exist an inverted list? I mean, how may I know what kind of exception
is going to raise my code? Shall I figure out by myself?

Apart from this, in a method I check valid strings with a regular
expression. I pass the string to the method and then Ii have something
like:

m = re.match('[1-9]$', my_string)

I was thinking to put a try except here, so that:

try:
m = re.match('[1-9]$', my_string)
except:
print 'something...'

But actually this doesn't work, because re.match just assign None to
m, without raising anything.

The only way seems to check with m.group(), so after I matched the
string I should have:

try:
   m.group()
except:
   print 'error...'

Or shall I put also the matching inside the try? Or am I completely wrong?
--
http://mail.python.org/mailman/listinfo/python-list


Re: duck-type-checking?

2008-11-15 Thread Paul McGuire
On Nov 15, 2:50 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> I wonder whether the best solution is to include all your type checks
> (isinstance or duck-typing) in the unit tests, so you can avoid paying
> the cost of those tests at runtime? If your code passes the unit tests,
> but fails with real data, then your unit tests aren't extensive enough.
>
> --
> Steven

The real penalties that you pay for static typing are not at compile
time, but at design time.  Because of duck-typing, Python programmers
can skip a lot of the extra hoops/cruft that Java and C++ developers
must jump through, usually to *get around* the restrictions of static
typing.  Imagine how much code is needed in those languages to
implement this simple generic Proxy class:

class Proxy(object):
def __init__(self,other):
self.obj = other
def __getattr__(self,attr):
print "Get attribute '%s'" % attr
return getattr(self.obj,attr)

x = "slfj"
xproxy = Proxy(x)

print xproxy.upper()

# prints:
# Get attribute 'upper'
# SLFJ

I used very similar code to write a CORBA interceptor for a client in
about 15 minutes, which would have taken *much* longer in C++ or Java.

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


Re: Comparing value in two dictionaries?

2008-11-15 Thread Arnaud Delobelle
Gilles Ganault <[EMAIL PROTECTED]> writes:

> Hello
>
> I fill two dictionaries with the same number of keys, and then need to
> compare the value for each key, eg.
>
> #Pour chaque APE, comparaison societe.ape.nombre et verif.ape.nombre
> import apsw
>
> #
> dic1={}
> [...]
> rows=list(cursor.execute(sql))
> for id in rows:
>   dic1[id[0]] = id[1]
> #
> dic2={}
> [...]
> rows=list(cursor.execute(sql))
> for id in rows:
>   dic2[id[0]] = id[1]
> #
> #Here, compare each key/value to find values that differ
> for i in dic1.items():
>   [...]
>   
> What would be a good way to do this in Python?
>
> Thank you.

I think you would be better off writing some SQL query that does it.

If you want to do this in Python, I suppose it depends whether you know
that the two dictionaries have the same set of keys.  If they do you can
simply write something like:

diff = [key for key, val1 in dic1.iteritems() if val1 != dic2[key]]

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


Re: Regular expression and exception

2008-11-15 Thread Arnaud Delobelle
Mr.SpOOn <[EMAIL PROTECTED]> writes:

> Hi,
> I've never used exception before, but I think now it's time to start.
>
> I've seen that there is a list of  the built-in exceptions in the
> Python docs, but this explains the meaning of every exception. Does
> exist an inverted list? I mean, how may I know what kind of exception
> is going to raise my code? Shall I figure out by myself?

The interactive prompt will help you!

E.g. I want to know what exception arises when I try to add an int to a
string:

>>> 42 + 'spam'
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> 

Ah, it's a TypeError!

> Apart from this, in a method I check valid strings with a regular
> expression. I pass the string to the method and then Ii have something
> like:
>
> m = re.match('[1-9]$', my_string)
>
> I was thinking to put a try except here, so that:
>
> try:
> m = re.match('[1-9]$', my_string)
> except:
> print 'something...'
>
> But actually this doesn't work, because re.match just assign None to
> m, without raising anything.
>
> The only way seems to check with m.group(), so after I matched the
> string I should have:
>
> try:
>m.group()
> except:
>print 'error...'
>
> Or shall I put also the matching inside the try? Or am I completely wrong?

In this case re.match has been designed to return None if there are no
matches so there is no need to look for exceptions.  This is probably
because it is very common to use re.match(...) while expecting no match
so it is not really an 'exception'.  Just do

m = re.match(...)
if m is None:
print 'error...'
else:
# Do something with m

HTH

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


Re: Regular expression and exception

2008-11-15 Thread bearophileHUGS
Mr.SpOOn:
> try:
>     m = re.match('[1-9]$', my_string)
> except:
>     print 'something...'
> ...
> try:
>    m.group()
> except:
>    print 'error...'

Generally don't write a nude except, use qualified exceptions, that is
put there one of more exceptions that you want to catch (be careful
with the syntax with more than one exception, see the docs).

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Clustering the keys of a dict according to its values

2008-11-15 Thread Florian Brucker

Wow, thanks everybody! There's a lot to learn for me from these examples...


Enjoy your weekend!
Florian

Florian Brucker wrote:

Hi everybody!

Given a dictionary, I want to create a clustered version of it, 
collecting keys that have the same value:


 >>> d = {'a':1, 'b':2, 'c':1, 'd':1, 'e':2, 'f':3}
 >>> cluster(d)
{1:['a', 'c', 'd'], 2:['b', 'e'], 3:['f']}

That is, generate a new dict which holds for each value of the old dict 
a list of the keys of the old dict that have that very value.


Another requirement is that it should also work on lists, in that case 
with indices instead of keys. We may assume that all values in the 
original dict/list can be used as dict keys.


Right now I'm doing it like this:

   def cluster(d):
 try:
   # is d a dict?
   values = unique(d.values())
   keys = d.keys()
 except AttributeError:
   # assume d is a list
   values = unique(d)
   keys = range(len(d))

 clusters = {}
 for value in values:
   clusters[value] = filter(lambda v: d[v] == value, keys)

 return clusters

where unique() is from O'Reilly's Python Cookbook and returns a list 
containing each item of the given list exactly once.


Now I'm pretty new to Python and chances are rather high that this could 
be done prettier and/or more efficient. Therefore any comment on the 
above code is greatly appreciated.



Regards,
Florian

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


Re: [UnicodeEncodeError] Don't know what else to try

2008-11-15 Thread Marc 'BlackJack' Rintsch
On Sat, 15 Nov 2008 14:12:42 +0100, Gilles Ganault wrote:

> On Fri, 14 Nov 2008 17:39:00 +0100, "Martin v. Löwis"
> <[EMAIL PROTECTED]> wrote:
>>Can you first please report what happened when you add the print
>>statement?
> 
> Thanks guys, I found how to handle this:
> 
> ===
> for id in rows:
>   #Says Unicode, but it's actually not
>   #print type(id[1])
>   #

If it says `unicode` *it is* `unicode`.

>   try:
>   print id[1];
>   except UnicodeEncodeError:
>   print "Not unicode"

But it *is* `unicode` if `type()` says so!

Your code still fails when ``id[1]`` can't be encoded in `sys.encoding`, 
'iso8859-15', or 'cp1252'.  Even worse: The output may be even encoded in 
different encodings this way.  That's garbage you can't decode properly 
with one encoding anymore.

A clean solution would be just one ``print`` with a call of `encode()` 
and an explicit encoding.  I'd use 'utf-8' as default but give the user 
of the program a possibility to make another choice.

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: To throw or to throw not?

2008-11-15 Thread Emanuele D'Arrigo
Thank you all for the insightful replies! Much appreciated!

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


Re: don't get JPE (Java Python Extension) compiled.

2008-11-15 Thread Benjamin Kaplan
On Sat, Nov 15, 2008 at 4:33 AM, Tamer Higazi <[EMAIL PROTECTED]> wrote:

> Hi people!
> I want to compile the Java Python Extension which I downloaded through
> CVS "http://jpe.cvs.sourceforge.net/jpe/";
>
> Building JPE by bootstrapping the makefile system with the cmd:
>
> "python makefile.py"
>
> from the top source directory.
>
> I receive the following error message:
>
> working in 
> use make command 
> 
> ksh /home/tamer/JPE/libplus/bin/pybatch.ksh /home/tamer/JPE/libplus
> /usr/bin/python -c "import devkit; devkit.pythonexe = None; import imp;
> imp.load_source( 'makefile', 'makefile.py', open(
> 'makefile.py')).genmake()"
> /bin/sh: ksh: command not found
> make: *** [all] Error 127
>
>
>
> for any help solving my problem getting JPE compiled, I would thank you
> very much
>
>
> Tamer Higazi
> --
> http://mail.python.org/mailman/listinfo/python-list
>


Whenever a program says something like "ksh: command not found", it usually
means there is a program (ksh) that it needs but that you don't have
installed.
--
http://mail.python.org/mailman/listinfo/python-list


[ANN] TZMud 0.7

2008-11-15 Thread Lee Harr

TZMud is a Python MUD server.
http://tzmud.googlecode.com/
 
A MUD is a text-based virtual environment
accessed via telnet, or with a specialised
MUD client.
 
TZMud development is still in early stages,
focusing on API and server stability.
 
TZMud uses several high-quality Python
libraries to facilitate rapid development:
Twisted, ZODB, and Pyparsing.
 
TZMud is released under GPLv3.
 
Changes in TZMud-0.7:
- new character stats framework
- new wizard powers including studying objects
and changing settings on objects like weight
or character stats
- exits can now react to characters passing through
- exits can also react to actions in the room
- objects can now be used
- simplified weighting of mob actions
- added Camera and Photograph objects
- added Photographer mob
- improved database upgrade mechanism
_
News, entertainment and everything you care about at Live.com. Get it now!
http://www.live.com/getstarted.aspx
--
http://mail.python.org/mailman/listinfo/python-list


Re: Good practice when writing modules...

2008-11-15 Thread Scott David Daniels

[EMAIL PROTECTED] wrote:

r0g:

a) Import all the other modules these functions depend on into the
modules global namespace by putting them at the top of the module or
should I...
b) Include them in each function individually.


This is a interesting topic, that requires some care.
Generally I suggest you put them at the top, so they can be found and
seen with less problems (*), it's the standard.
If a function is called ...[rarely] ... you may move the import inside 

> the function itself, especially if such function isn't speed-critical.

I would amend this advice by adding that you should (in such cases) put
a commented-out import at the top level (so you can look at the top of a 
module's source and see what other modules it relies upon.


--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing value in two dictionaries?

2008-11-15 Thread Scott David Daniels

Arnaud Delobelle wrote:

Gilles Ganault <[EMAIL PROTECTED]> writes:


Hello

I fill two dictionaries with the same number of keys, and then need to
compare the value for each key, ...

if you know set(dic1) == set(dic2)  -- that is that the same keys are
used, you could use:
Setup:
>>> dic1 = dict((c, ord(c)) for c in 'abcdefgh')
>>> dic2 = dic1.copy()
>>> dic2['e'] = 12
>>> dic2['h'] = 13

Comparisons:
>>> differs = dict((p1[0], (p1[1], p2[1]))
  for p1, p2 in zip(sorted(dic1.items()),
sorted(dic2.items()))
  if p1 != p2)

>>> differs
{'h': (104, 13), 'e': (101, 12)}


--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Generators and their next() and send() methods

2008-11-15 Thread Thomas Mlynarczyk

Hello,

I was playing around a bit with generators using next() and send(). And 
I was wondering why an extra send() method was introduced instead of 
simply allowing an argument for next().


Also, I find it a bit counter-intuitive that send(42) not only "sets" 
the generator to the specified value, but yields the next value at the 
same time.


As an exercise, I wanted to somehow "modify" a generator so that it 
would have a next() method accepting an argument, something like


@myway
def gen():
pass

But I failed to come up with an implementation of the myway() function.

Any comments and/or suggestions?

Greetings,
Thomas

--
Ce n'est pas parce qu'ils sont nombreux à avoir tort qu'ils ont raison!
(Coluche)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing value in two dictionaries?

2008-11-15 Thread Arnaud Delobelle
Scott David Daniels <[EMAIL PROTECTED]> writes:

> Arnaud Delobelle wrote:
>> Gilles Ganault <[EMAIL PROTECTED]> writes:
>>
>>> Hello
>>>
>>> I fill two dictionaries with the same number of keys, and then need to
>>> compare the value for each key, ...
> if you know set(dic1) == set(dic2)  -- that is that the same keys are
> used, you could use:
> Setup:
> >>> dic1 = dict((c, ord(c)) for c in 'abcdefgh')
> >>> dic2 = dic1.copy()
> >>> dic2['e'] = 12
> >>> dic2['h'] = 13
>
> Comparisons:
> >>> differs = dict((p1[0], (p1[1], p2[1]))
>   for p1, p2 in zip(sorted(dic1.items()),
> sorted(dic2.items()))
>   if p1 != p2)
>
> >>> differs
> {'h': (104, 13), 'e': (101, 12)}

This may break if two keys are not comparable or if the order on keys is
not total.

Moreover it is O(nlogn) (as sorting is) whereas iterating
over items of one dictionary and looking up the other one will be O(n)
(assuming dictionary lookup is O(1)):

[k for k, v in dic1.iteritems() if dic2[k] != v]

Or to obtain a dictionary of differences:

dict((k, (v, dic2[v]) for k, v in dic1.iteritems()
  if dic2[v] != v)

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


Re: Generators and their next() and send() methods

2008-11-15 Thread Arnaud Delobelle
Thomas Mlynarczyk <[EMAIL PROTECTED]> writes:

> Hello,
>
> I was playing around a bit with generators using next() and
> send(). And I was wondering why an extra send() method was introduced
> instead of simply allowing an argument for next().
>
> Also, I find it a bit counter-intuitive that send(42) not only "sets"
> the generator to the specified value, but yields the next value at the
> same time.

If you want to simply 'set' the generator (by which I take you mean
'change its state') without without iterating it one step, then what you
need is a class with an __iter__() method.  Then you can change the
state of the object between calls to next().  E.g.

>>> class MyGenerator(object):
... def __init__(self, v): self.v = v
... def __iter__(self):
... for x in range(10):
... yield self.v
... 
>>> g = MyGenerator(5)
>>> for i in g:
... g.v = input("val:")
... print i
... 
val:4
5
val:10
4
val:34
10
val:56
34
val:

Etc...

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


Re: Comparing value in two dictionaries?

2008-11-15 Thread Arnaud Delobelle
Arnaud Delobelle <[EMAIL PROTECTED]> writes:

> Or to obtain a dictionary of differences:
>
> dict((k, (v, dic2[v]) for k, v in dic1.iteritems()
>   if dic2[v] != v)
^
  Should be k of course!

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


Re: Official definition of call-by-value (Re: Finding the instance reference...)

2008-11-15 Thread rurpy
On Nov 14, 8:56 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
>> On Nov 13, 4:53 pm, Terry Reedy wrote:
>>> [EMAIL PROTECTED] wrote:
>>>
 I have yet to see any reasonable definition of a Python
 value in the Python docs or elsewhere, despite the fact
 that a value is one of the three defining characteristics
 of an object, a central concept in Python.
>>> I noticed too.  My try:
>>>
>>> The value of an object is the information that the object represents (or
>>> that is stored with the object) that the interpreter uses to compute the
>>> value of a new object when you use the object in an expression.  For
>>> number objects, the number value.  For collection objects, the objects
>>> collected. For functions, the signature and function performed when called.
>>>
>>> How is that?
>>
>> I am starting with the idea that "value" is what we call
>> whatever it is that is the difference between, for example,
>> the objects int(3) and int(4).  While your definition
>> seems to be saying something similar it does not seem
>> very precise.

First of all, thanks.  Thanks to your answers I have
finally been able to formulate a concept of Python
values.  Now we'll see if it is valid/usable... :-)

> I think necessarily so, or rather, it can only be specific for each
> class.  In the formulation: an object has identify, class, and value,
> class and value are separated.  Others have said that type/class is a
> universe of possible values and operations on those values.  Each
> instance has a particular value. 'Universe of possible values' is vague
> until one gets specific.  For some classes, the possible values are
> rather complex.
>
>> How would I use your definition to answer the following
>> questions?
>>
>> * How does an object get a value?
>
> A Python interpreter, human or electronic, creates objects with values
> as directed by Python code.  How it does so is its private secret ;-).
> The directive code includes literals, expressions, and some statements.

OK.

>> * Can I create an object that has a value that
>>  is the same as int(3) without somehow using an
>>  int(3) object in its construction?
>
> Yes: 1 + 2

OK, but my question was too strict.
"1 + 2" is shorthand for: int(1).__add__(int(2))
Rephrasing: is possible to create an object that has
a value that is the same as int(3) without somehow
using a method of the int class (or sub/super-class)
in its construction?
I think it is not possible in the Python language.
That is one could in theory have a float method,
to_int(), but it could not be implemented in the
Python language (as opposed to implemented in the
Python implementation) without using int(), or some
other callable that uses int().

> Yes: mpz(3) where mpz is multi-precision int class with same set of
> possible values as Python ints.

The argument to mpz() is int(3).

> ??? 3.0
> ??? Fraction(3,1)
>
> While Python sees these as *equal*, one could say they are not the same
> because they indicate members of different (non-isomorphic) universes.

At this point, I would so say.

>> * Do all objects have values? (Ignore the Python
>>  docs if necessary.)
>
> If one allows null values, I am current thinking yes.

I don't see a difference between a "null value"
and not having a value.

> Still, numbers, characters, and collections thereof of what code is
> usually about.

Yes, which is why we have int, str, and list classes
which, unlike some others, can have values.

>> * What is the value of object()?
>
> Essentially none, other than bool(object()) == True.
> Ditto for None, other than bool(None) == False.
> Otherwise, None and object convey no information.

A method/function can use whatever characteristic of
its arguments that it wants.  For example, id() pays no
attention to the value of its argument, only its identity.
So we can say that the bool class constructor returns
True for all object except None.  Since None is a
singleton, bool() can identify it by identity, without
consideration of it's (non-existent I propose) value.

>> * Does an object's behavior (methods) affect
>>  its value?
>
> My first answer is No.  Instance methods are attributes of a class and,
> in most cases, the value of a class.

The value of a class is it's attributes?
Are you saying that attributes of an object are
part of its value?  That would mean that 'a'
and b' below have different values?

class My_int(int):
def __init__(self): self.foo = None
a = int(3)
b = My_int(3)

I propose that attributes are not part of a class'
(or any other object's) value and that a class object
has no value.

> of an object can be and is changed to another class, the interpretation
> of the value/info of the instance could change and one might claim that
> the effective value and hence the value of the object has changed and
> hence the answer could be Yes.  But this is extremely rarely done and I
> could claim that this is a shortcut for creating a new object and
> deleting the old.
>
>> 

Re: Little direction please Python MySQL

2008-11-15 Thread Ethan Furman

len wrote:

On Nov 13, 7:32 pm, Ethan Furman <[EMAIL PROTECTED]> wrote:


len wrote:


Hi all;


[snip]



Here is my problem.  I need to start doing this in the really world at
my company converting some older cobol system and data to python
programs and MySQL.  I have gotten past packed decimal fields and
various other little tidbits.  My problem is the data files aren't
little three of four field files but Customer File with 98 fields
etc.  I understand building dictionaries and building with zip and I
have even seen a reference to using __setattr__ in an empty class but
I'm having a hard time moving past the little code snippts to real
code.


[snip]



Thanks Len


I've never had the (mis?)fortune to work with COBOL -- what are the
files like?  Fixed format, or something like a dBase III style?  I
presume also that you only need access to them in COBOL format long
enough to transfer them into MySQL -- true?

~ethan~



Files are fixed format no field delimiters, fields are position and
length
records are terminated by newline.  In cobol the read statement which
read
a record from the file automaticly mapped the date to the fieldnames
in
the cobol file definition.


[snip]



Len


Are the cobol file definitions available in a file that can be parsed, 
or are they buried in the source code?


What type of data is in the files?  Integer, float, character, date, etc.

Once you have the data out, will you need access these same cobol files 
in the future?  (i.e. more data is being added to them that you will 
need to migrate)


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


Re: Building musical chords starting from (a lot of) rules

2008-11-15 Thread Stefaan Himpe

The costrunction of a chord is based on a root note and a structure,
so by default, giving just a note, it creates a major chord adding the
third and fifth note.


Quite some time ago I wrote something to solve the reverse problem: 
given a list of note names, find out a chord name. 
(http://chordrecognizer.sourceforge.net/ )


I used a look-up table to made a correspondence between the chord-name 
and the notes from which the chord is built. The notes are expressed as

a distance from the root note.

E.g. starting from a chromatic scale built on C, the distances would be:
C:0  C#:1  D:2  D#:3  E:4  F:5  F#:6  G:7  G#:8  A:9  A#:10  B:11
(and similar for flats, double sharps and double flats, ...)

Any chord thus can be constructed from a root note + the distance 
information.


example distance information:

 { 'm' : [ 0, 3, 7 ],# minor triad
   ''  : [ 0, 4, 7 ],# major triad
   '7' : [ 0, 4, 7, 10]  # etc...
...
 }

How does one e.g. construct the E7 chord from this information?

1. generate the chromatic scale starting from E, and annotate with note 
distance to root note:


E:0  F:1  F#:2  G:3  G#:4  A:5  A#:6  B:7  C:8  C#:9  D:10  D#:11

2. take the recipe for a '7' chord from the distance information:
[0, 4, 7, 10]

3. map the numbers from step 2. to the note names from step 1.: E G# B D

If you care about proper enharmonic spelling of the chord's note names 
(i.e. do  not confuse F# and Gb), you will need to add some extra 
information in the look-up tables or you need to pass extra information 
to the chord construction recipe at the moment of creating a chord, but 
that is left as an excercise to you - the interested reader ;)


HTH,
Stefaan.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Good practice when writing modules...

2008-11-15 Thread John Machin
On Nov 15, 9:08 pm, [EMAIL PROTECTED] wrote:

> I also put a comment after each import, with the name of the function/
> class it is used into:
>
> import foo # used by baz()
> import bar # used by spam()

Why bother with the ()? Why bother at all? Surely this rapidly becomes
tedious clutter:
import xyz # used by abc(), def(), ghi(), ...
Do you remember to adjust the comment when a function/class is changed
so that it doesn't use the module any more?

> ...
> def baz(n):
>     return foo(n) * 10
> ...
> def spam(k):
>     return bar(k) - 20

Your modules are callable???

> Time ago I have read an interesting article that says that comments of
> today will often become statements and declaration and tags of
> tomorrow, that is stuff that the interpreter/compiler/editor
> understands. This means that such annotations of mine may be something
> fit to become a syntax of the language.

I hope not.

> I don't have ideas on how such
> syntax can be, if you have suggestions I'm listening.

Suggestion: no such syntax!!
--
http://mail.python.org/mailman/listinfo/python-list


Two instances share an attribute

2008-11-15 Thread Filip Gruszczyński
I really don't understand, what's happening with the following code.
Am I doing something wrong?

#!/usr/bin/python

class EnumeratedContent:

def __init__(self, values = []):
self.values_ = values

def values(self):
return self.values_

def addValue(self, value):
self.values_.append(value)

x = EnumeratedContent()
x.addValue('ff')
print x.values()
x = EnumeratedContent()
x.addValue('gg')
print x.values()

This code prints:

['ff']
['ff', 'gg']

Why the heck self.__values keeps old list? Can anyone explain it to me?

I am using:

Python 2.5.2 (r252:60911, Sep 14 2008, 23:49:00)
[GCC 4.1.2 (Gentoo 4.1.2 p1.0.2)] on linux2


-- 
Filip Gruszczyński
--
http://mail.python.org/mailman/listinfo/python-list


Re: Two instances share an attribute

2008-11-15 Thread Cameron Simpson
On 15Nov2008 22:41, Filip Gruszczyński <[EMAIL PROTECTED]> wrote:
| I really don't understand, what's happening with the following code.
| Am I doing something wrong?

Yes. This is a common mistake:

| class EnumeratedContent:
| def __init__(self, values = []):
| self.values_ = values

The "values = []" happens at class definition time, not instance
definition time. So when "values" is not supplied, the same list
is reused as the default value.

The usual idiom is this:

  class EnumeratedContent:
  def __init__(self, values = None):
  if values is None:
  values = []
  self.values_ = values

which makes a new [] during the instance creation.

Cheers,
-- 
Cameron Simpson <[EMAIL PROTECTED]> DoD#743
http://www.cskk.ezoshosting.com/cs/

If you don't live on the edge, you're taking up too much space. - t-shirt
--
http://mail.python.org/mailman/listinfo/python-list


Re: Two instances share an attribute

2008-11-15 Thread Filip Gruszczyński
Every day something new. Thanks a lot :)

2008/11/15 Cameron Simpson <[EMAIL PROTECTED]>:
> On 15Nov2008 22:41, Filip Gruszczyński <[EMAIL PROTECTED]> wrote:
> | I really don't understand, what's happening with the following code.
> | Am I doing something wrong?
>
> Yes. This is a common mistake:
>
> | class EnumeratedContent:
> | def __init__(self, values = []):
> | self.values_ = values
>
> The "values = []" happens at class definition time, not instance
> definition time. So when "values" is not supplied, the same list
> is reused as the default value.
>
> The usual idiom is this:
>
>  class EnumeratedContent:
>  def __init__(self, values = None):
>  if values is None:
>  values = []
>  self.values_ = values
>
> which makes a new [] during the instance creation.
>
> Cheers,
> --
> Cameron Simpson <[EMAIL PROTECTED]> DoD#743
> http://www.cskk.ezoshosting.com/cs/
>
> If you don't live on the edge, you're taking up too much space. - t-shirt
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Filip Gruszczyński
--
http://mail.python.org/mailman/listinfo/python-list


Re: Don't know what else to try

2008-11-15 Thread John Machin
On Nov 16, 12:12 am, Gilles Ganault <[EMAIL PROTECTED]> wrote:
> On Fri, 14 Nov 2008 17:39:00 +0100, "Martin v. Löwis"
>
> <[EMAIL PROTECTED]> wrote:
> >Can you first please report what happened when you add the print statement?
>
> Thanks guys, I found how to handle this:

No you didn't.

>
> ===
> for id in rows:
>         #Says Unicode, but it's actually not

If it's not unicode, what is it? What is your basis for that assertion
(which implies there is a bug in the version of Python that you are
using)? The probability that type() ever become so buggy that it
misreports whether a value is unicode or not, is extremely small.
Further the probability that you or I would be the first to notice the
problem is vanishingly small.

>         #print type(id[1])
>         #

You didn't reply to Martin's question, instead you are tilting at a
windmill whose probability of existence lies between epsilon and zero.
When you ask for help, you should act on reasonable requests from your
helpers. Here's a reasonable request; insert some more verbose
debugging code:
  print 'id[1] is', type(id[1]), repr(id[1])
AND tell us what you see, *before* you try to "fix" it.

For the future, please remember these:
(1) When you are worried about exactly what data some name refers to,
do
   print 'name is', type(name), repr(name)
(2) Examine the more plausible sources of error first ... here's a
partial ordering: Ganault, ..., Gates, ..., Guido, God :-)

HTH,
John
--
http://mail.python.org/mailman/listinfo/python-list


Re: Good practice when writing modules...

2008-11-15 Thread Robert Kern

r0g wrote:


The module I am compiling is kind of a scrapbook of snippets for my own
development use, it has no coherent theme and I wouldn't be distributing
it or using the whole thing in a production environment anyway, just
copying the relevant functions into a new module when needed. I'm
thinking having the imports inline might make that process easier when I
do need to do it and once copied I can always move them out of the
functions declarations.


This is something of a special case, so I don't think the usual style guides 
entirely apply. What I would do is keep the imports outside of the functions, 
but put them before the functions that use them. Repeat the imports as 
necessary. For example, if f() uses modules foo and bar, while g() uses only foo:




import foo
import bar

def f():
...



import foo

def g():
...

--
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: Good practice when writing modules...

2008-11-15 Thread Robert Kern

Robert Kern wrote:

r0g wrote:


The module I am compiling is kind of a scrapbook of snippets for my own
development use, it has no coherent theme and I wouldn't be distributing
it or using the whole thing in a production environment anyway, just
copying the relevant functions into a new module when needed. I'm
thinking having the imports inline might make that process easier when I
do need to do it and once copied I can always move them out of the
functions declarations.


This is something of a special case, so I don't think the usual style 
guides entirely apply. What I would do is keep the imports outside of 
the functions, but put them before the functions that use them.


Actually, I lie. What I really do is keep a Mercurial repository of all of the 
snippets I use in separate files.


--
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: Official definition of call-by-value (Re: Finding the instance reference...)

2008-11-15 Thread Terry Reedy

[EMAIL PROTECTED] wrote:

On Nov 14, 8:56 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:

First of all, thanks.  Thanks to your answers I have
finally been able to formulate a concept of Python
values.  Now we'll see if it is valid/usable... :-)


Good questions help refine a concept.


* Can I create an object that has a value that
 is the same as int(3) without somehow using an
 int(3) object in its construction?

Yes: 1 + 2


OK, but my question was too strict.
"1 + 2" is shorthand for: int(1).__add__(int(2))


Both are shorthand for int.__add__(int(1),int(2)).  Liskov intentionally 
designed CLU with methods belonging to classes, not instances, because 
the binary op case does not fit the idea of some that a method is a 
message to an actor, that 1+2 means 'hey 1, add 2 to yourself'.


...

* Does an object's behavior (methods) affect
 its value?

My first answer is No.  Instance methods are attributes of a class and,
in most cases, the value of a class.


The value of a class is it's attributes?
Are you saying that attributes of an object are
part of its value?


Either: objects have 4 aspects -- id, class, attributes, and value
Or: attributes are included with value, so that obs have 3 aspects -- 
id, class, and value.

[Or: (Aprano) id, class, and attributes are included with value.]

I an not sure yet which viewpoint/formulation is the more useful. I 
answered from the 3-aspect viewpoint.  It is more traditional, but 
probably predates 'objects with attributes' as opposed to 'strucures 
with fields'.  But I suspect that the values of the fields would be 
considered the value of the structure. In any case, I have also 
considered the 4-aspect view also.



That would mean that 'a'
and b' below have different values?

class My_int(int):
def __init__(self): self.foo = None
a = int(3)
b = My_int(3)


Yes, and indeed, a.foo raises an exception and b.foo does not.

If attributes are included with value, then value must be subdivided 
into attributes and private value.  For numbers, the private value is 
the numerical value; it cannot be accessed separate from the number 
object itself.  Strings have a private value which can be exposed a 
character or slice at a time.  Numbers and strings are the two classes 
with literals.



I propose that attributes are not part of a class'
(or any other object's) value and that a class object
has no value.


That is the first choice of the either/or choice above.  It is okay as 
long as it is understood that 'value' is being used in a restrictive sense.


Here is one reason I have not adopted it yet (and I need to make a 
choice for the algorithm book I am writing).  Consider a(b).  This means 
'call a with argument b'.  I would rather say 'the value of a is what it 
does with b (for all possible b), which is to say, the mapping it 
implements', than to explain calling in terms of an 
implementation-dependent, essentially private, attribute structure.


So I am thinking I may go with
class: determines universe of possible values of instances and (with 
superclasses) functions such instances can work with.  'Functions' 
includes all types of syntactic expressions.

value: determine specific result when used as argument in functions

Terry Jan Reedy

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


PP3E error

2008-11-15 Thread ryan payton

How do I fix the PP3E and PP2E errors in Programming Python 3rd Edition?
--
http://mail.python.org/mailman/listinfo/python-list


Re: special editor support for indentation needed.

2008-11-15 Thread Eric S. Johansson
Aaron Brady wrote:
> You see examples here from time to time that don't follow the rigid C+
> + formatting.  Some examples:
> 
> def classmaker( ):
>   class X:
> something
>   return X
> 
> class X:
>   class Y:
> something
> 
> if something:
>   class X:
> pass
> else:
>   def X( ):
> pass
> 
> Some of these are tricky not dirty; some are both, but you don't want
> to tie your hands prematurely, which is one of my favorite features of
> Python.  Long story short, it can get hairy.

somebody should be called a sick bastard.  :-)

I have never seen these forms and I can see how they are syntactically correct,
possibly useful, and mind bogglingly confusing.  ,  having said that
though, my gut reaction would be to try to satisfy the usual case first and
suggest that these forms are a "sucks to be you moment, use your hands because
we saved them from damage elsewhere". case.  Given enough time I think I could
come up with a fairly regular grammar to express both the ordinary and
exceptional cases.  I'd probably use something somewhat more verbose for the
sick and twisted examples you've given me.

> 
> Why aren't you favoring, 'dedent once/twice', 'dedent' repeated,
> 'close class, close function, close if, close for'?  I don't imagine
> that saying 'close' three times in a row would be a strain.
> 
> If the program is clever, it can learn that 'function' and 'method'
> are synonyms, and you can start to think in terms of both.
> 
> You don't need to write 'start method, start class', except as a
> shortcut for spelling the statements out by hand; what type of block
> statement (suite) you are starting is determined by syntax.

I was hoping to avoid this but this is a brain dump on speech or the user
interfaces.  It's evolved over some 15 years of living with speech recognition
and having to take time off because my voice hurts too much to speak in my hands
hurt too much to type.

Hands are robust.  It takes decades of use to make them go bad.  Vocal systems
are fragile.  It takes only one bad day to make them break for weeks.  Once
damaged, neither one fully recovers.

The major problem with using speech recognition with programming is that
keyboards are great at doing fine grained small detail work and lousy at doing
coarse-grained work.  Speech recognition is lousy at doing fine grain detail
work and really good at doing coarse-grained work such as creating large blocks
of text.  This difference in usability is only visible once you have lived in
both worlds.

rule number one: never try to speak the keyboard.

don't ever force a user to control capitalization, concatenation, spelling by
speaking one letter at a time.  Even simple things like Alpha (cap alpha) can
get rather tiring if used a lot.  One of the cruelest things from software
development is mixed case, fractured spelling words such as mixInCntr which I'm
not even going to try to pronounce or spell out.

a more positive way of expressing rule one is allow the user to get what they
want by speaking words in their native language.

Rule number two: never speak small stuff   or why use two or more utterances
when a single one can do

one step up from speaking the keyboard is forcing the user to say the same
command multiple times to achieve a single effect.  For example, if you want to
move to the beginning of the line for the end of the line, you can say "move
word left" as many times as it takes to get to where you want to be or you can
just say "move to start of line".  In the context of the indent outdent control,
I don't really want moving to the right level of indentation for class, method,
function etc..  I want a component to put in the method "new class" which would
put a class definition at the right place with the right indentation in all the
right components so that I don't have to speak the object hierarchy or triple
quotes (in pairs).  It's all done for me.  But a macro like that won't work
right unless I can put the cursor at the right level of indentation.

another reason for this rule is that you want to really minimize load on the
voice.  Remember, the voice is fragile.  If I can say a small sentence and get a
big effect or something that saves me a lot of work, then that's a win.
Otherwise I might as well burn some hand time and hit the backspace key twice,
speak my macro to do whatever I want, and then clean up the macro from its wrong
indentation.  Yes, it saves my throat and my hands but not as much for either as
a good speech macro would.

Rule number three: be careful with your grammar

Speech user interfaces are broad shallow hierarchies.  GUI interfaces are narrow
and deep.  Speech user interfaces do not readily lend themselves to discovery in
the same way that GUI interfaces do.

Be aware of grammar traps such as similar starting points and homonym arguments.
 Usually it's not too bad but, some words just won't be recognized correctly so
there should be an alternative.  For example, Lennox is how NaturallyS

Re: special editor support for indentation needed.

2008-11-15 Thread Eric S. Johansson
John Yeung wrote:
> This is such a fascinating and compelling thread that it has pulled me
> out of lurker mode.
> 
> Eric, I would like to say I also admire your initiative, but even more
> so your patience.  You seem to handle comments of all types
> gracefully.

Should have seen me 20 years ago.  lets just say there are few posts I deeply
regret.

> Perhaps it comes from working with speech recognition so much.  I
> imagine that if you are using a speech-based programming environment
> and get frustrated with how stupid it is, and tell it off, you only
> manage to create more of a mess for yourself to clean up.  I think
> most of us who rely on our vision and typing lose our cool more
> easily, partly because the penalty for us is not as great.

Well, if I lose my temper and yell, I lose the ability to work for a day or two.
 Being self-employed, I can't afford that.  This is not to say I don't get
extremely frustrated.  I just rant off keyboard much to my wife's dismay.
Fortunately, my clients mostly see the calm, cool, only slightly rattled at
times consultant that I am.

> Anyway, sorry for being a bit off-topic.  I'm afraid I don't have a
> lot to offer on the topic.  My thoughts as I was reading the earlier
> comments is that Python, by its nature, is extremely flexible and thus
> inherently tough to map to a speech-only interface.  "Flatter"
> languages would seem better suited, but then they tend to be lower-
> level, thus more verbose, thus what you gain in lack of ambiguity
> might be lost in having to produce more code.

You have hit one of the challenges directly square on the head.   for Chile, one
of the benefits of an extremely flexible language like Python is you can use a
regimented form full of consistent idioms and get your job done.  obviously
these idioms would be the result of whatever tools you use to create code.
> 
> If it is to be Python after all, it seems the strategy you have in
> mind is to make the typical patterns as easy as possible, and either
> not allow for the more exotic ones or settle for making them much more
> complicated to achieve.  You also seem to have a pretty clear idea of
> the behaviors you want already.

Yes.  That was one of the rules I should've put into another post.  Make the
common path simple let the unusual path be complex.


> 
> I think your best bet is to stick with Emacs.  It's the only editor I
> know of which is almost fully programmable without recompiling, and
> it's available for Windows.  (I am not clear on whether you already
> use Emacs for Windows, or whether you remotely use Emacs on Linux,
> from Windows.)
> 
> It does sound like you have to do a bit of Emacs Lisp programming to
> get what you want, but I'd guess that's easier than modifying some
> other editor to do what you want, or modifying the way you issue
> instructions to fit a more visually oriented style.

well, therein lies the rub.  I don't know lisp, I don't know Emacs internals let
alone python mode.  solving the user interface problem by itself is pretty
difficult.  If the universe was granting the wishes, I would hope for a
development partner helping me build these interfaces and integrating them with
vr-mode (Emacs speech recognition mode that has some challenges)


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


Re: special editor support for indentation needed.

2008-11-15 Thread Eric S. Johansson
[EMAIL PROTECTED] wrote:

> I still don't understand. 

I elaborated on some of these points in a post to Aaron Brady.  If you missed it
on the list, let me know and I will forward you a copy.

It seems that you want to be able to do:
> "END_CLASS"  to end the current class.
> 
> "END_DEF" to end the current function
> 
> "END_BLOCK" to end anything else.
> 
> This is possible with some emacs lisp but I don't see what this gains
> you over
> "BACK" "BACK" "BACK"
>   where "BACK" sends a backspace to emacs.
>   (Actually I'd define an "END" command which you could give at the
> end of the last line of a block. That would relieve you of the need to
> enter the newline and tab.)
>   Yes, it requires a few extra utterances on occasion, but you don't
> have to worry about three new (multi-syllabic) verbs to recognize.
> 
>  Am I understanding your requirement correctly?

no but it's not your fault.  I have a bad habit of asking for the component that
I need (i.e. gimme a six-inch 8-32 screw) without telling you what I need it for
because  it is extremely clear in my mind what I need the screw for (i.e. barn
door mount for astrophotography).

All of this navigation stuff was driven by the need to embedded inside of a
larger  command invoked through speech recognition.  I have no conditionals
about the environment so I can't tell whether I need to indent once or twice or
three times to make it go to the right place.  Remember, this is a component in
a blind macro (i.e. one that is not aware of its environment) and therefore must
operate correctly with no knowledge of its environment.

Many of the features speech recognition users need from editors are these smart
navigation commands so that one can perform more complex operations without
worrying about indentation or position or things of that nature.

my voice is wearing out.  More later


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


Re: Optional parameter object re-used when instantiating multiple objects

2008-11-15 Thread Steven D'Aprano
On Sat, 15 Nov 2008 01:40:04 -0800, Rick Giuly wrote:

> Hello All,
> 
> Why is python designed so that b and c (according to code below)
> actually share the same list object? It seems more natural to me that
> each object would be created with a new list object in the points
> variable.

That's not natural *at all*. You're initialising the argument "points" 
with the same list every time. If you wanted it to have a different list 
each time, you should have said so. Don't blame the language for doing 
exactly what you told it to do.


> class Blob:
> def __init__(self, points=[]):
> self._points = points

Let's analyze this. You create a method __init__. That function is 
created *once*. As part of the process of creating the function, the 
argument "points" is given the default value of an empty list. The 
creation of that empty list happens *once*, when the method is created. 
In the body of the function, you set the _points attribute to points. 
Naturally it is the same list object.

Since the method is only created once, it is only natural that the 
default value is also only created once. If you want something to be 
created each time the function is called, you have to put it inside the 
body of the function:

class Blob:
def __init__(self, points=None):
if points is None: 
points = []
self._points = points

Now you will have _points set to a unique empty list each time.



This is no different from doing this:

alist = []
b1 = Blob(alist)
b2 = Blob(alist)

Would you be surprised that b1 and b2 share the same list? If yes, then 
you need to think about how Python really works, rather than how you 
imagine it works.



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


Re: PP3E error

2008-11-15 Thread Steven D'Aprano
On Sat, 15 Nov 2008 16:37:34 -0800, ryan payton wrote:

> How do I fix the PP3E and PP2E errors in Programming Python 3rd Edition?

Liquid Paper?


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


Re: Official definition of call-by-value (Re: Finding the instance reference...)

2008-11-15 Thread rurpy
On Nov 15, 4:12 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
>> On Nov 14, 8:56 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
...snip...
 * Does an object's behavior (methods) affect
  its value?
>>> My first answer is No.  Instance methods are attributes of a class and,
>>> in most cases, the value of a class.

So if method .foo() is an instance attribute it
is part of the object's value, but if it is part
of the object's class, it is part of the object's
behavior?  Even though calling obj.foo() causes
exactly same results?  I can see that a case can
be made for defining things that way, but it doesn't
seem desirable.

>> The value of a class is it's attributes?
>> Are you saying that attributes of an object are
>> part of its value?
>
> Either: objects have 4 aspects -- id, class, attributes, and value
> Or: attributes are included with value, so that obs have 3 aspects --
> id, class, and value.
> [Or: (Aprano) id, class, and attributes are included with value.]

Or: object attributes are considered together with class
attributes to define an object's behavior leading to:
obs have 3 aspects -- id, behavior, and value.
(The definition of "type" might be stretched a little to
make it synonymous with behavior.)

> I an not sure yet which viewpoint/formulation is the more useful. I
> answered from the 3-aspect viewpoint.  It is more traditional, but
> probably predates 'objects with attributes' as opposed to 'strucures
> with fields'.  But I suspect that the values of the fields would be
> considered the value of the structure. In any case, I have also
> considered the 4-aspect view also.
>
>> That would mean that 'a'
>> and b' below have different values?
>>
>> class My_int(int):
>> def __init__(self): self.foo = None
>> a = int(3)
>> b = My_int(3)
>
> Yes, and indeed, a.foo raises an exception and b.foo does not.

But raising an exception is a aspect of behavior,
not of value.

> If attributes are included with value, then value must be subdivided
> into attributes and private value.  For numbers, the private value is
> the numerical value; it cannot be accessed separate from the number
> object itself.  Strings have a private value which can be exposed a
> character or slice at a time.  Numbers and strings are the two classes
> with literals.

It seems to me that what I think of as "value" is
indeed a sort of private attribute (that's how I
am trying out thinking of it.)  But it is its
privateness, its totally different way of getting
created, used, and changed, that is the very thing
that makes it unique and worthy of getting it's
own name.

>> I propose that attributes are not part of a class'
>> (or any other object's) value and that a class object
>> has no value.
>
> That is the first choice of the either/or choice above.  It is okay as
> long as it is understood that 'value' is being used in a restrictive sense.

Which seems to me to most closely match the intuitive
sense of value.  To me it is intuitive that int(3)
and subclass_of_int(3) have the same value, 3.  To
learn that their values are different because one
has an attribute the other didn't, or because the
values in a common (in name) attribute were different,
would be very surprising to me.

> Here is one reason I have not adopted it yet (and I need to make a
> choice for the algorithm book I am writing).  Consider a(b).  This means
> 'call a with argument b'.  I would rather say 'the value of a is what it
> does with b (for all possible b), which is to say, the mapping it
> implements', than to explain calling in terms of an
> implementation-dependent, essentially private, attribute structure.

I can see viewing functions in general as a mapping
of arguments values to results in the context of describing
algorithms.  I am not sure it is the best way to view
them in the context of how objects are manipulated in
the Python runtime environment.

> So I am thinking I may go with
> class: determines universe of possible values of instances and (with
> superclasses) functions such instances can work with.

If attributes are part of an object's value, that
universe is effectively infinite, isn't it?  For
the vast majority of objects (those created in
Python from a class not designed to impose bondage
and discipline by using slots for example) I can
add any attributes I wish with any values I wish
to an object.  So class doesn't really determine
much under that definition, does it?

>  'Functions'
> includes all types of syntactic expressions.

Doesn't that use of the word "function" conflict
with the already established use of "function"
in Python.  I.e., I think of functions as just
another object, albeit one with a code attribute
that the Python VM knows how to call.

I think of evaluation of expressions as a series
of method (or other callable) executions, each
returning an object that is used in the next step
of the series.

> value: determine specific result when used as argument in functions

You are prepa

Re: Official definition of call-by-value (Re: Finding the instance reference...)

2008-11-15 Thread rurpy
[Tried multiple times to post this but Google errors
out so will try posting in two parts... this is part 1]

On Nov 14, 11:51 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Fri, 14 Nov 2008 22:56:52 -0500, Terry Reedy wrote:
>
>> [EMAIL PROTECTED] wrote:
>>> On Nov 13, 4:53 pm, Terry Reedy wrote:
 [EMAIL PROTECTED] wrote:

> I have yet to see any reasonable definition of a Python value in the
> Python docs or elsewhere, despite the fact that a value is one of the
> three defining characteristics of an object, a central concept in
> Python.
 I noticed too.  My try:

 The value of an object is the information that the object represents
 (or that is stored with the object) that the interpreter uses to
 compute the value of a new object when you use the object in an
 expression.  For number objects, the number value.  For collection
 objects, the objects collected. For functions, the signature and
 function performed when called.

 How is that?
>>>
>>> I am starting with the idea that "value" is what we call whatever it is
>>> that is the difference between, for example, the objects int(3) and
>>> int(4).  While your definition seems to be saying something similar it
>>> does not seem very precise.
>>
>> I think necessarily so, or rather, it can only be specific for each
>> class.  In the formulation: an object has identify, class, and value,
>> class and value are separated.  Others have said that type/class is a
>> universe of possible values and operations on those values.  Each
>> instance has a particular value. 'Universe of possible values' is vague
>> until one gets specific.  For some classes, the possible values are
>> rather complex.

I will presume you read my response to Terry Reedy so
I won't repeat everything I said there here.

> I prefer another definition of object: an object *is* a value, rather
> than *has* a value. That value consists of identity, type (or class), and
> everything else of interest which is sometimes also called "value". Since
> identity is usually unimportant, and type is assumed from context, we can
> often get away with stating that the "everything else of interest" is
> *the* value.

The Python Lang. Ref. says:
  object = identity + type + value
You are defining objects as:
  object = identity + type + (object - (identity + type))
  value = object - identity = type + (object - (identity + type))

Seems to me it is easier just to give the "object - (identity + type)"
part a name, say, "value". :-)

I also question, "type is assumed from context".  To
me, type is very objective: it is the set of methods
and other attributes that define the behavior of the
object.

> I usually talk about one of the three levels of value:
>
> (1) The value of the NAME (or variable) x is the object int(3); that is,
> the thing denoted by the symbol x is the object int(3).

OK, but a name is a rather abstract concept, is it
not?  Because of Python's interpreted nature, names
can't be compiled away as in C, they need a concrete
runtime existence, but does the language definition
need to assume that?

And per innumerable previous discussions, is it not
preferable to "bind the name to an object" sidestepping
any need for "value" in this context?

> (2) The value of the OBJECT int(3) is the specific concrete instantiation
> that makes it the thing that it is rather than another thing (a
> complicated way of saying that the value of an object is itself); that
> is, the thing denoted by the symbol int(3) is some specific byte pattern
> in memory which causes that object to be int(3) rather than some other
> object.

I don't see how saying "the value of an object is
itself" is particularly useful.  We already have a
word for what an object is, it is "object". :-)
The point of the word "value" is to describe, in
a general way, without defining implementation
details, what you describe as "some specific byte
pattern in memory which causes that object to be
int(3) rather than some other object" and does not
mix in other bit-pattern differences, such as
differences in type which are not relevant to what
we intuitively think of as "value".

> To put it another way, the value of that object is whatever properties of
> the object distinguish it from any other the whole number 1.

This is saying something different, that the value
of an object depends on how it's type relates to
some non-programming-language concept ("whole numbers"
in this case) that the object attempts to model.

> Since
> identity is (usually) unimportant for distinguishing one object from
> another (we usually care whether x==y, not whether x is y) the identity
> is not part of the value.

The result of x==y depends solely on the behavior (methods)
of x.  (To be anal, the behavior of x might be to delegate
calculating the result to y).  That behavior (if reasonable)
will take into consideration the "value"s of x and y.  This
seems to imply that "valu

Re: Official definition of call-by-value (Re: Finding the instance reference...)

2008-11-15 Thread rurpy
[Tried multiple times to post this but Google errors
out so will try posting in two parts... this is part 2]
On Nov 14, 11:51 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Fri, 14 Nov 2008 22:56:52 -0500, Terry Reedy wrote:
>> [EMAIL PROTECTED] wrote:
>>> On Nov 13, 4:53 pm, Terry Reedy wrote:
 [EMAIL PROTECTED] wrote:

>>> * Can I create an object that has a value that
>>>  is the same as int(3) without somehow using an int(3) object in its
>>>  construction?
>>
>> Yes: 1 + 2
>> Yes: mpz(3) where mpz is multi-precision int class with same set of
>> possible values as Python ints.
>>
>> ??? 3.0
>> ??? Fraction(3,1)
>>
>> While Python sees these as *equal*, one could say they are not the same
>> because they indicate members of different (non-isomorphic) universes.
>
> Whether we wish to say that mpz(3) has the same value as int(3) depends
> on what we care about, and we only care about that because our data types
> are leaky abstractions. In principle, we should be indifferent to whether
> x is int(3), float(3.0), mpz(3), or any other instantiation of the
> abstract numeral three. In practice, we're not indifferent: we prefer
> ints for mpz objects for some purposes, but not for others. If we care
> about the specifics, then we might say they have different values
> (because they have different types, and therefore different
> characteristics). If we care only about the thing they represent, the
> abstract number three, then we'd say that they have the same value.

You are saying there is no objective definition
of "value".  I disagree.  I think one can define
value in a useful way that is precise, objective,
and useful.

>>> * Do all objects have values? (Ignore the Python
>>>  docs if necessary.)
>>
>> If one allows null values, I am current thinking yes. Still, numbers,
>> characters, and collections thereof of what code is usually about.
>
> I would say that all objects *are* values, rather than *have* values. The
> value of None is the object None, which is a concrete instantiation of a
> selected subset of behaviour of the null object pattern.
>
>>> * What is the value of object()?
>>
>> Essentially none, other than bool(object()) == True. Ditto for None,
>> other than bool(None) == False. Otherwise, None and object convey no
>> information.
>
> I would say that the "everything of interest" I referred to above is the
> empty set: object() has little or no state. But of course having no state
> is itself a state, in the same way that 0 is a perfectly good integer.

"interest" is pretty subjective, isn't it?  In the
My_int example above, is the .foo attribute of interest
or not?  How would I decide?  How would you decide?
I was also going to ask about changing methods, but I
see you consider that below.

> In practice, I'd say that object() is one of those cases where we should
> include identity in the value. Although we're indifferent as to *which*
> object() instance we get, once we've got one, we care whether other
> instances are the same instance or different ones. Imagine that object()
> keeps a cache of instances, and returns one instead of creating a brand
> new object. We don't care which instance we get, or even whether it comes
> from the cache or is created fresh. But once we have one, we care about
> the identities of others:
>
> special = object()  # we don't care which object instance we get
> if special is some_other_instance():
> print "Match!"
>
>>> * Does an object's behavior (methods) affect
>>>  its value?
>>
>> My first answer is No.  Instance methods are attributes of a class and,
>> in most cases, the value of a class.  In those cases in which the class
>> of an object can be and is changed to another class, the interpretation
>> of the value/info of the instance could change and one might claim that
>> the effective value and hence the value of the object has changed and
>> hence the answer could be Yes.  But this is extremely rarely done and I
>> could claim that this is a shortcut for creating a new object and
>> deleting the old.
>
> I would say that the answer to this is, "Would you like to include
> behaviour in value?". Let me give you an example:
>
> class String(string):
> def upper(self):
> return "spam"
>
> s1 = "Norwegian Blue"
> s2 = String("Norwegian Blue")
>
> Do s1 and s2 have the same value?

Using my definition of value, the answer is
an unambiguous yes.

> Using definition (1) above, we can see that the names s1 and s2 refer to
> different objects, so the names have different values.

No, they refer to different objects.  The object
str("Norwegian Blue") has a value, tucked away
inside it somewhere, of some implementation defined
bits that encode "Norwegian Blue".

String("Norwegian Blue") is a subclass of str
and has the same value.  (Actually, we don't really
care about bit patterns, it is enough to declare
that the values stored in the objects are the same
because that's how the language is defined.)
If they app

Re: Multiprocessing vs. [Pyro, RPyC]

2008-11-15 Thread J Kenneth King
Jeffrey Barish <[EMAIL PROTECTED]> writes:

> [EMAIL PROTECTED] wrote:
>
>> 
>> Jeffrey> With the release of multiprocessing in Python 2.6, is there
>> any Jeffrey> reason to use Pyro or RPyC?
>> 
>> As far as I know the multiprocessing module only works on one machine
>> (multi-cpu or multi-core), not across machines.
>
> So I thought at first, but then I saw this statement in the documentation:
>
> It is possible to run a manager server on one machine and have clients use
> it from other machines (assuming that the firewalls involved allow it).

Depends. I don't know much about the multiprocessing module in 2.6,
but I have built a distributed application on Pyro.


Pyro has many advantages -- a query-able name server, GUI tools for
monitoring your setup, and remote agents. It is also rather simple in
comparison to other similar tools (*cough*twisted.pb*cough*). However,
it is essentially an RPC style system, so some people might not be too
comfortable with it. YMMV.
--
http://mail.python.org/mailman/listinfo/python-list


Need help in understanding a python code

2008-11-15 Thread [EMAIL PROTECTED]
Hi,

I am trying to understand the following line:
# a is an integer array

max([(sum(a[j:i]), (j,i))

Can you please tell me what that means,
I think sum(a[j:i] means find the some from a[j] to a[i]
But what is the meaning of the part (j,i)?

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


Re: Need help in understanding a python code

2008-11-15 Thread Chris Rebert
On Sat, Nov 15, 2008 at 8:41 PM, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> Hi,
>
> I am trying to understand the following line:
> # a is an integer array
>
> max([(sum(a[j:i]), (j,i))

This code isn't valid. You have a [ with no closing ].

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

>
> Can you please tell me what that means,
> I think sum(a[j:i] means find the some from a[j] to a[i]
> But what is the meaning of the part (j,i)?
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


pyspread 0.0.10 released

2008-11-15 Thread mmanns
Pyspread 0.0.10 has finally been released. 
 
About: 
--
 
Pyspread is a 3D spreadsheet application. Each cell accepts a Python
expression and returns an accessible object. Python modules are usable
from the spreadsheet table without external scripts. 

Changes: 

 
+ Code completely re-structured 
+ Unit tests for main grid functionality 
+ Speed-up by caching of cell results 
+ Change of spread method syntax 
+ Various bug fixes

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


Re: Need help in understanding a python code

2008-11-15 Thread John Machin
On Nov 16, 3:41 pm, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> Hi,
>
> I am trying to understand the following line:
> # a is an integer array
>
> max([(sum(a[j:i]), (j,i))
>
> Can you please tell me what that means,
> I think sum(a[j:i] means find the some from a[j] to a[i]
> But what is the meaning of the part (j,i)?

0. "integer array" is a very loose term in Python. Fortunately the
answer to your question is not affected by that.
1. Sorry, the max... line is not syntactically correct; there are two
[s and only one ]; there are 4 (s and only 3 )s. Try copying the line
and pasting, not re-typing.
2. I'm not going to try to guess how to fix the bracket mismatches.
3. Note that you have left off a ) from your question about "sum" ...
it probably should be sum([j:i]).
4. That is the sum (not "some"!!) of a[j] to a[i-1] both inclusive.
It's a standard idiom in Python for the end of a range to be expressed
as the first unused element.
5. Even after fixing the bracket mismatches, it looks like you will
have an expression whose value is thrown away. Perhaps you might like
to give us a few lines of context before and after the line of
interest.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need help in understanding a python code

2008-11-15 Thread Meryl Silverburgh
This is the full source code:
def A(w, v, i,j):
if i == 0 or j == 0: return 0
if w[i-1] > j:  return A(w, v, i-1, j)
if w[i-1] <= j: return max(A(w,v, i-1, j), v[i-1] + A(w,v, i-1, j - w[i-1]))

I am reading this blog

http://20bits.com/articles/introduction-to-dynamic-programming/


On Sat, Nov 15, 2008 at 10:54 PM, Chris Rebert <[EMAIL PROTECTED]> wrote:
> On Sat, Nov 15, 2008 at 8:41 PM, [EMAIL PROTECTED]
> <[EMAIL PROTECTED]> wrote:
>> Hi,
>>
>> I am trying to understand the following line:
>> # a is an integer array
>>
>> max([(sum(a[j:i]), (j,i))
>
> This code isn't valid. You have a [ with no closing ].
>
> Cheers,
> Chris
> --
> Follow the path of the Iguana...
> http://rebertia.com
>
>>
>> Can you please tell me what that means,
>> I think sum(a[j:i] means find the some from a[j] to a[i]
>> But what is the meaning of the part (j,i)?
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Optional parameter object re-used when instantiating multiple objects

2008-11-15 Thread Aaron Brady
On Nov 15, 3:40 am, Rick Giuly <[EMAIL PROTECTED]> wrote:
> Hello All,
>
> Why is python designed so that b and c (according to code below)
> actually share the same list object? It seems more natural to me that
> each object would be created with a new list object in the points
> variable.
>
> class Blob:
>     def __init__(self, points=[]):
>         self._points = points
>
> b = Blob()
> c = Blob()
>
> b._points.append(1)
> c._points.append(2)
>
> print b._points
>
> # this will show that b._points is the same object as c._points

Hi Rick,

I don't think Dennis or Steven read your post very well.  You said
'Why does Python do X?', and 'It seems natural to you to do not X'.
Dennis and Steven both said, 'Python does X'.

Steven did get around to suggesting an answer though.  He said:

> If you want something to be
> created each time the function is called, you have to put it inside the
> body of the function:

Taking this to be true, the answer to your question is, 'Because the
object isn't created inside the body of the function,' or, 'Because
the argument list is outside the body of the function'.

>From your post, it's hard to tell whether this 'duh'-type observation
would point out the salient feature of the construct, or whether
you're after something deeper.

If you're asking, 'Why isn't the argument list considered to be inside
the body?', then the answer is, it's pretty much arbitrary.
Regardless of which one the author of Python chose, the other's
workaround would be equally short, and neither one is obviously
indicated by the syntax.

And until someone sends you a link to Python's author's blog that
gives the answer, 'To make creating static variables really easy',
don't let them tell you so.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need help in understanding a python code

2008-11-15 Thread Aaron Brady
See below.

On Nov 15, 11:15 pm, "Meryl Silverburgh" <[EMAIL PROTECTED]>
wrote:
> This is the full source code:
> def A(w, v, i,j):
>     if i == 0 or j == 0: return 0
>     if w[i-1] > j:  return A(w, v, i-1, j)
>     if w[i-1] <= j: return max(A(w,v, i-1, j), v[i-1] + A(w,v, i-1, j - 
> w[i-1]))
>
> I am reading this blog
>
> http://20bits.com/articles/introduction-to-dynamic-programming/
>
> On Sat, Nov 15, 2008 at 10:54 PM, Chris Rebert <[EMAIL PROTECTED]> wrote:
> > On Sat, Nov 15, 2008 at 8:41 PM, [EMAIL PROTECTED]
> > <[EMAIL PROTECTED]> wrote:
> >> Hi,
>
> >> I am trying to understand the following line:
> >> # a is an integer array
>
> >> max([(sum(a[j:i]), (j,i))
>
> > This code isn't valid. You have a [ with no closing ].
>
> > Cheers,
> > Chris
> > --
> > Follow the path of the Iguana...
> >http://rebertia.com
>
> >> Can you please tell me what that means,
> >> I think sum(a[j:i] means find the some from a[j] to a[i]
> >> But what is the meaning of the part (j,i)?
>
> >> --
> >>http://mail.python.org/mailman/listinfo/python-list
>
>


> if w[i-1] <= j: return max(A(w,v, i-1, j), v[i-1] + A(w,v, i-1, j - 
> w[i-1]))

This means:

Calculate 'A(w,v, i-1, j)', calculate 'v[i-1] + A(w,v, i-1, j - w
[i-1])', and return whichever is larger.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Official definition of call-by-value (Re: Finding the instance reference...)

2008-11-15 Thread Steven D'Aprano
On Sat, 15 Nov 2008 11:17:07 -0800, rurpy wrote:

>>> * Can I create an object that has a value that
>>>  is the same as int(3) without somehow using an int(3) object in its
>>>  construction?
[...]
>> Yes: mpz(3) where mpz is multi-precision int class with same set of
>> possible values as Python ints.
> 
> The argument to mpz() is int(3).

Does mpz take string arguments? If it doesn't, it is easy to imagine a 
version that does.

mpz("3")



>>> * Do all objects have values? (Ignore the Python
>>>  docs if necessary.)
>>
>> If one allows null values, I am current thinking yes.
> 
> I don't see a difference between a "null value" and not having a value.

Ah, the Medieval concept of numbers. Of course it's very much older than 
Medieval. Roman and Greek mathematics was bedeviled by their philosophy 
that one is the smallest number. (In fact, some early mathematicians 
argued that *two* was the smallest number, for the reason that if you 
have only one sheep (say) it would be unnatural to say that "I have a 
number of sheep") It wasn't until the fifth century C.E. that Indian 
mathematicians invented the concept of zero, and it took many centuries 
for the idea to get to Europe via the Arabs.

If you wish to say that null values aren't values at all, you will find 
that you have many conceptual difficulties. Given:

x = 5
y = 5
z = x - y

you will be forced to say that x and y have values but z does not. But 
that doesn't mean that z is undefined -- it means that z is defined and 
has no value, which makes communication very much more complicated. You 
are forced to say things like:

"The value of the object is the number of sheep in the paddock, unless 
the number of sheep is zero, in which case the object has no value..."

which is needlessly complicated.

I say that 0 is a perfectly fine value. So is None, [], {}, and any other 
null-value. I recommend you don't complicate and confuse matters by 
trying to treat them differently.


 
>> Still, numbers, characters, and collections thereof of what code is
>> usually about.
> 
> Yes, which is why we have int, str, and list classes which, unlike some
> others, can have values.

What classes do you think have no values?


 
[snip]
>>> * Does an object's behavior (methods) affect
>>>  its value?
>>
>> My first answer is No.  Instance methods are attributes of a class and,
>> in most cases, the value of a class.
> 
> The value of a class is it's attributes? Are you saying that attributes
> of an object are part of its value?  That would mean that 'a' and b'
> below have different values?
> 
> class My_int(int):
> def __init__(self): self.foo = None

That won't work you know.

> a = int(3)
> b = My_int(3)


That depends on whether the existence of foo makes a difference to you or 
not. Consider pickle. Since pickle can't predict what aspects of the 
object are important, it must treat *everything* as significant, and 
pickle will absolutely treat a and b as having different values.

(Actually, that's not quite true: by necessity pickle *cannot* treat 
identity as important. If your application requires object identity to be 
persistent over execution session, you can't do so in Python. Hence 
pickle and related serialisers can afford to ignore identity.)

Given input of b, the round-trip of pickle/unpickle must return an object 
with a foo attribute. If the round-trip merely returns a My_int instance 
without the foo attribute, we would rightly consider it a bug, that the 
output doesn't have the same value as the input. Likewise if it returned 
int(3) instead of My_int(3).

But other functions may have weaker constraints. Consider sum([a, b]). 
The function sum makes no promises that it will return the same type as 
it's arguments. Since, *for the purposes of addition*, the foo attribute 
has no significance, sum() makes no promise whether the sum of a and b 
will include the foo attribute. In fact it does not. As far as addition 
is concerned, a and b have the same value, and the foo attribute is lost.

In general, Python makes the fewest possible promises of that nature. If 
you want to treat foo as having a significant part of the value of b, 
then you need to deal with it yourself, perhaps by writing __add__ and 
__radd__ methods to My_int.

But from a philosophical position, as opposed to a practical one, of 
course a and b have different values. The value of a is (the integer 3), 
and the value of b is (the integer 3 together with an attribute foo), 
even if foo is a mere decoration, a stripe of red paint on an otherwise 
identical object. Since they are different, the objects a and b have 
different values. This is a valid philosophical position, although in 
practice we often lower our expectations, especially when duck-typing. We 
don't care about the red stripe or not, and so we are indifferent to 
whether we get int(3) or My_int(3).


 
> I propose that attributes are not part of a class' (or any other
> object's) value and that a class object ha

Palette-mode PNG images

2008-11-15 Thread Lawrence D'Oliveiro
I'm trying to create PNG files to use in menus for authoring DVDs. As you
may know, these menus are only allowed to have limited numbers of colours.

Ideally I'd like to create a PNG file with just two bits per pixel, with
four colour-table entries of my choice. I'm using PyCairo
 to do the drawing, but that doesn't
seem to support colour-table images as far as I can tell. So I'm trying to
figure out how to use PIL
 to save the
images to PNG files with a suitable format.

However, it looks like PIL wants 256 colour-table entries. When I try to
pass fewer, e.g.

ThePix = array.array("B", '\0' * ImageWidth * ImageHeight * 4)
ThePixSurface = cairo.ImageSurface.create_for_data(ThePix,
cairo.FORMAT_ARGB32, ImageWidth, ImageHeight, ImageWidth * 4)
  # can't find format_stride_for_width?
TheDraw = cairo.Context(ThePixSurface)
...
ThePixSurface.flush() # prior to writing out pixels myself
TheImage = Image.frombuffer("RGBA", (ImageWidth, ImageHeight),
 ThePix, "raw", "RGBA", 0, 1)
TheImage = TheImage.convert("P")
TheImage.putpalette([(0, 0, 0), (255, 255, 255), (0, 255, 0),
(0, 255, 255)])
TheImage.save("png_palette_test.png")

it dies with the following, on the putpalette line:

Traceback (most recent call last):
  File "./png_palette_test", line 41, in 
TheImage.putpalette([(0, 0, 0), (255, 255, 255), (0, 255, 0),
(0, 255, 255)])
  File "/usr/lib64/python2.5/site-packages/PIL/Image.py", line 1205,
  in putpalette
  data = string.join(map(chr, data), "")
  TypeError: an integer is required

Cairo also supports FORMAT_A8 and FORMAT_A1 images--should I be using the
latter, perhaps?

Also I see that the PIL PNG encoder/decoder supports a "bits" output option
 which is
marked as "experimental". Can this be useful for constraining the pixel
depth of the output image?

Thanks for any suggestions.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Building musical chords starting from (a lot of) rules

2008-11-15 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Mr.SpOOn
wrote:

> C 9 is a base chord plus a the ninth note, but this implies the
> presence of the seventh too, so it results in: C E G B D

I don't recall such meanings in the chord names I came across. If you wanted
both a seventh and ninth, you had to say so: "C7+9" or "Cmaj7+9".
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python have Multiple Inheritance ?

2008-11-15 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Larry Bates
wrote:

> Lawrence D'Oliveiro wrote:
>
>> In message <[EMAIL PROTECTED]>, Steve
>> Holden wrote:
>> 
>>> Lawrence D'Oliveiro wrote:
>>>
 Not to mention duck typing, which does away with the need for
 inheritance altogether.
>>>
>>> That seems a somewhat extreme point of view.
>> 
>> Hey, I didn't design the language, I just use it. :)
> 
> I'm with Steve.  Multiple inheritance is still a "good" thing, especially
> for mixin-classes.  wxPython, for instance, wouldn't be nearly so flexible
> without it.

Sure. But Python doesn't _force_ you to do things that way.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Optional parameter object re-used when instantiating multiple objects

2008-11-15 Thread Steven D'Aprano
On Sat, 15 Nov 2008 21:29:22 -0800, Aaron Brady wrote:

> I don't think Dennis or Steven read your post very well.

It's possible.

> You said 'Why
> does Python do X?', and 'It seems natural to you to do not X'. Dennis
> and Steven both said, 'Python does X'.

I also disputed that it is natural to do not-X (runtime creation of 
default arguments), and explained why such an interpretation doesn't 
match with the way Python operates. I admit I didn't answer the "why" 
part.

 
> Steven did get around to suggesting an answer though.  He said:
> 
>> If you want something to be
>> created each time the function is called, you have to put it inside the
>> body of the function:

If you want to be pedantic, then my "answer" (which you seem to approve 
of) doesn't correspond to either of the original poster's questions. If 
you're going to be pedantic, then be pedantic all the way, and criticize 
me for answering a question that wasn't asked :-P


> Taking this to be true, the answer to your question is, 'Because the
> object isn't created inside the body of the function,' or, 'Because the
> argument list is outside the body of the function'.

Actually, the correct answer to "Why?" would be "Because that's the 
decision Guido van Rossum made back in the early 1990s when he first 
started designing Python". That of course leads to the obvious question 
"Why did he make that decision?", and the answer to that is:

* it leads to far more efficient performance when calling functions;

E.g. if the default value is expensive to calculate, it is better to 
calculate it once, when the function is created, than every single time 
the function is called.

Additionally, the effbot once mentioned in a similar thread that there 
are real performance benefits in the Python VM from binding the default 
value once only. I don't know the exact details of that, but I trust 
Fredrik knows what he's talking about.


* it has less scope for surprise when calling functions.

E.g. I would argue that most people would be surprised, and dismayed, if 
this code fails:

x = 1
def foo(a, b=x):
   return a+b

del x
print foo(2)


> From your post, it's hard to tell whether this 'duh'-type observation
> would point out the salient feature of the construct, or whether you're
> after something deeper.
> 
> If you're asking, 'Why isn't the argument list considered to be inside
> the body?', then the answer is, it's pretty much arbitrary.

No, it is not an arbitrary choice. I've given practical reasons why the 
Python choice is better. If you want default argument to be created from 
scratch when the function is called, you can get it with little 
inconvenience, but the opposite isn't true. It is very difficult to get 
static default arguments given a hypothetical Python where default 
arguments are created from scratch. There's no simple, easy idiom that 
will work. The best I can come up with is a convention:

# Please don't change this, or strange things will happen.
_private = ResultOfExpensiveCalculation()

def foo(a, b=_private):
return a+b

The above is still vulnerable to code accidentally over-writing _private 
with some other value, or deleting it, but at least we avoid the 
expensive calculation every time.

Or possibly:

def foo(a, b=foo._private):
return a+b

foo._private = ResultOfExpensiveCalculation()

which has obvious disadvantages with regard to shadowing, renaming, 
anonymous functions, and so forth.



> Regardless
> of which one the author of Python chose, the other's workaround would be
> equally short, 

Not true. One has an obvious workaround, the other only has a *partial* 
workaround.

> and neither one is obviously indicated by the syntax.

I would disagree, but not enough to argue.


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


Re: Building musical chords starting from (a lot of) rules

2008-11-15 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Dennis Lee
Bieber wrote:

> On Sun, 16 Nov 2008 19:21:49 +1300, Lawrence D'Oliveiro
> <[EMAIL PROTECTED]> declaimed the following in
> comp.lang.python:
> 
>> In message <[EMAIL PROTECTED]>,
>> Mr.SpOOn wrote:
>> 
>> > C 9 is a base chord plus a the ninth note, but this implies the
>> > presence of the seventh too, so it results in: C E G B D
>> 
>> I don't recall such meanings in the chord names I came across. If you
>> wanted both a seventh and ninth, you had to say so: "C7+9" or "Cmaj7+9".
> 
> My books on harmony and such do indicate that a Cx implies all the
> intervening odd values up to x... But they also tend to indicate that
> (especially for guitar) the intervening can be left out...

Well, I did pick up chord notation mainly from guitar-playing friends.
Myself I was learning classical piano, where we didn't have much need for
such things. :)
--
http://mail.python.org/mailman/listinfo/python-list


about escape string store in mysql

2008-11-15 Thread ylj798
this string from web by the Regular Expression,
−−−
href="#" onClick="ConvertURL2FG('Flashget://
W0ZMQVNIR0VUXWh0dHA6Ly9tb3YuM2dwLmNuL2d1aWxpbi8yMDA4LzExLzExL3l1ZWhvdWppZmVuMDIuM2dwW0ZMQVNIR0VUXQ==&233','',
233)" oncontextmenu="Flashget_SetHref(this)" fg="Flashget://
W0ZMQVNIR0VUXWh0dHA6Ly9tb3YuM2dwLmNuL2d1aWxpbi8yMDA4LzExLzExL3l1ZWhvdWppZmVuMDIuM2dwW0ZMQVNIR0VUXQ==&233"

my code:

**
# -*- coding: utf8 -*-
#!/usr/bin/python

import MySQLdb
conn=MySQLdb.connect
(host="localhost",user="root",passwd="ylj",db="net", charset="utf8")
cur = conn.cursor()
s="""href="#" onClick="ConvertURL2FG('Flashget://
W0ZMQVNIR0VUXWh0dHA6Ly9tb3YuM2dwLmNuL2d1aWxpbi8yMDA4LzExLzExL3l1ZWhvdWppZmVuMDIuM2dwW0ZMQVNIR0VUXQ==&233','',
233)" oncontextmenu="Flashget_SetHref(this)" fg="Flashget://
W0ZMQVNIR0VUXWh0dHA6Ly9tb3YuM2dwLmNuL2d1aWxpbi8yMDA4LzExLzExL3l1ZWhvdWppZmVuMDIuM2dwW0ZMQVNIR0VUXQ==&233
s=mysqldb.escape_string(s)
sql='insert into download(lines) values(%s)'
cur.execute(sql, s)



when I used the mysqldb.escape_string(),but eric gave me a error,tell
me that my sql strings have escape string.
how can i put the strings in database.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Optional parameter object re-used when instantiating multiple objects

2008-11-15 Thread Arnaud Delobelle
Steven D'Aprano <[EMAIL PROTECTED]> writes:

> On Sat, 15 Nov 2008 01:40:04 -0800, Rick Giuly wrote:
>
>> Hello All,
>> 
>> Why is python designed so that b and c (according to code below)
>> actually share the same list object? It seems more natural to me that
>> each object would be created with a new list object in the points
>> variable.
>
> That's not natural *at all*. You're initialising the argument "points" 
> with the same list every time. If you wanted it to have a different list 
> each time, you should have said so. Don't blame the language for doing 
> exactly what you told it to do.

Come on.  The fact that this questions comes up so often (twice in 24h)
is proof that this is a surprising behaviour.  I do think it is the
correct one but it is very natural to assume that when you write

def foo(bar=[]):
 bar.append(6)
 ...

you are describing what happens when you _call_ foo, i.e.:

1. if bar is not provided, make it equal to []
2. Append 6 to bar
3. ...

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


py2exe 0.6.9 released

2008-11-15 Thread Jimmy Retzlaff
py2exe 0.6.9 released
=

py2exe is a Python distutils extension which converts Python scripts
into executable Windows programs, able to run without requiring a
Python installation. Console and Windows (GUI) applications, Windows
NT services, exe and dll COM servers are supported.

Changes in 0.6.9:

* Binaries for Python 2.6 and Python 2.7.

* Fixed a modulefinder crash on certain relative imports.

* Changed the py2exe\samples\singlefile\gui\test_wx.py sample to
  use the wx package instead of the old wxPython package.

* Copy the manifest, if any, from the 'template' into the targets
  to ensure embedded assembly references, as required for python 2.6
  based apps, are copied.

* Allow each target to specify Vista User Access Control flags. For
  example, specifying 'uac_execution_info="requireAdministrator"' would
  force elevation for the final executable.


Changes in 0.6.8:

* Support for relative imports.

* Fix MemoryLoadLibrary to handle loading function addresses by ordinal
  numbers. Patch and test by Matthias Miller.

* Using the options compressed=1, bundle_files=3, and zipfile=None at
  the same time now works; patch from Alexey Borzenkov.

* Allow renaming of single-executable files; patch from Alexey
  Borzenkov.

* Embedding icon resources into the image now works correctly even for
  ico files containing multiple images.

* pyd files from different packages with the same filename no longer
  conflict. Patch from Grant Edwards.

* There are new samples for the 'typelibs' support, including the new
  option of pre-generating a typelib and specifying the file as an
  input to py2exe.

* The test suite is now included in the source distribution.


Changes in 0.6.6:

* Better support for Python 2.5.

* Experimental support for 64-bit builds of Python on win64.

* Better ISAPI support.

* New samples for ISAPI and COM servers.

* Support for new "command-line styles" when building Windows services.

Changes in 0.6.5:

* Fixed modulefinder / mf related bugs introduced in 0.6.4. This
  will be most evident when working with things like
  win32com.shell and xml.xpath.

* Files no longer keep read-only attributes when they are copied
  as this was causing problems with the copying of some MS DLLs.

Changes in 0.6.4:

* New skip-archive option which copies the Python bytecode files
  directly into the dist directory and subdirectories - no
  archive is used.

* An experimental new custom-boot-script option which allows a
  boot script to be specified (e.g., --custom-boot-script=cbs.py)
  which can do things like installing a customized stdout
  blackhole. See py2exe's boot_common.py for examples of what can
  be done. The custom boot script is executed during startup of
  the executable immediately after boot_common.py is executed.

* Thomas Heller's performance improvements for finding needed
  modules.

* Mark Hammond's fix for thread-state errors when a py2exe
  created executable tries to use a py2exe created COM DLL.

Changes in 0.6.3:

* First release assembled by py2exe's new maintainer, Jimmy
  Retzlaff. Code changes in this release are from Thomas Heller
  and Gordon Scott.

* The dll-excludes option is now available on the command line.
  It was only possible to specify that in the options argument to
  the setup function before.

  The dll-excludes option can now be used to filter out dlls like
  msvcr71.dll or even w9xpopen.exe.

* Fix from Gordon Scott: py2exe crashed copying extension modules
  in packages.

Changes in 0.6.2:

* Several important bugfixes:

  - bundled extensions in packages did not work correctly, this
made the wxPython single-file sample fail with newer wxPython
versions.

  - occasionally dlls/pyds were loaded twice, with very strange
effects.

  - the source distribution was not complete.

  - it is now possible to build a debug version of py2exe.

Changes in 0.6.1:

* py2exe can now bundle binary extensions and dlls into the
  library-archive or the executable itself.  This allows to
  finally build real single-file executables.

  The bundled dlls and pyds are loaded at runtime by some special
  code that emulates the Windows LoadLibrary function - they are
  never unpacked to the file system.

  This part of the code is distributed under the MPL 1.1, so this
  license is now pulled in by py2exe.

* By default py2exe now includes the codecs module and the
  encodings package.

* Several other fixes.

Homepage:



Download from the usual location:



Enjoy,
Jimmy

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


Re: Clustering the keys of a dict according to its values

2008-11-15 Thread bearophileHUGS
Bruno Desthuilliers:
> What is data is another type of sequence or iterable ?-)<

The original problem statement was:

Florian Brucker:
>Given a dictionary, I want to create a clustered version of it, collecting 
>keys that have the same value: [...] Another requirement is that it should 
>also work on lists, in that case with indices instead of keys. We may assume 
>that all values in the original dict/list can be used as dict keys.<

If the problem changes, then the code has to/can change. When you
write code it's better to avoid over-generalization (this is also a
rule in Agile programming practices).

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need help in understanding a python code

2008-11-15 Thread bearophileHUGS
silverburgh:
> max([(sum(a[j:i]), (j,i))

Other people have already answered you so I'll add only a small note:
today the max() function has a key optional attribute, so that code
can also be written as:

max(((j, i) for ...), key=lambda (j, i): sum(a[j : i]))

I think you have copied that part from code that runs in O(n^2);
remember that you can find the max subarray with a well known O(n)
algorithm too.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list