substituting list comprehensions for map()

2009-11-01 Thread Jon P.
I'd like to do:

resultlist = operandlist1 + operandlist2

where for example

operandlist1=[1,2,3,4,5]
operandlist2=[5,4,3,2,1]

and resultlist will become [6,6,6,6,6].  Using map(), I
can do:

map(lambda op1,op2: op1 + op2, operandlist1, operandlist2)

Is there any reasonable way to do this via a list comprehension ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stdin in embedded python

2009-11-01 Thread Gabriel Genellina

En Sun, 01 Nov 2009 23:13:10 -0300, Dave Angel  escribió:

Gabriel Genellina wrote:
En Sun, 01 Nov 2009 13:34:44 -0300, KillSwitch  
 escribió:

On Nov 1, 5:34 am, Dave Angel  wrote:

KillSwitch wrote:


> I have a C++ program, with a GUI, into which I have embedded  
python. I

> have made several python functions in C++, one of which I use to
> override the normal stdout and stderr so that they print to a text  
box
> of my GUI. One thing I cannot think of how to do is to redefine  
stdin
> so that it pauses the program, waits for a user to type input into  
the
> box, hit enter, and takes input from another text element and sends  
it

> to python like it was the console.

I suspect you don't really want to redirect stdin, but instead  
implement

raw_input().


But what would the function do? How would it pause python and wait for
it to have text to send?


Whatever you want. You don't have to "pause python", Python itself  
won't resume until your function doesn't return. [example using  
Tkinter.askstring]


I think I see the OP's problem.  He has written a GUI program in C++,  
and is using (embedding) Python functions into it.  So presumably those  
functions are being called from events in the C++ event loop.


If one of those functions tries to call back into C++ code, the event  
loop will never get control, to process the events from the standard UI  
controls.


So if the input is to be handled as an integral part of the C++ UI,  
there's a distinct problem.


On the other hand, Gabriel's dialog box should work fine, as long as you  
don' t mind a modal dialog box as a solution.  I don't know tkinter's  
askstring, but I suspect it'd work.  However, the rest of the C++ GUI  
would be frozen, which could be a problem.


Perhaps looking a other examples may help. Both IDLE and PythonWin replace  
raw_input with a message box; IDLE is a Tkinter application, and PythonWin  
wraps MFC. Both have a main message loop and use a modal message box.


--
Gabriel Genellina

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


Re: About one class/function per module

2009-11-01 Thread Gabriel Genellina

En Sun, 01 Nov 2009 22:27:32 -0300, Peng Yu  escribió:

On Sun, Nov 1, 2009 at 7:02 PM, alex23  wrote:

On Nov 2, 8:11 am, Peng Yu  wrote:



I prefer organized my code one class/function per file (i.e per module
in python). I know the majority of programmers don't use this
approach. Therefore, I'm wondering what its disadvantage is.


You mean, what disadvantages it has _other_ than the ones you've been
experiencing?

Aren't those enough to warrant actually working with Python's import
mechanism rather than against it?


At least, I can use the following for now with one class/function per
module. Unless this one class/function per module style have other
disadvantages in term software engineering, I still can live with
typing the class name (e.g. 'A') twice.

 import test.A
 a=test.A.A()

So I am asking disadvantages besides python import mechanism is not
friendly to it.


You don't type the class name twice. One 'A' is a module name, the other  
'A' is the class name.
In C++, a source file is just a compilation unit, only relevant for  
certain rules regarding visibility; it doesn't matter really in which  
source file the code is written in.
In Python, a source file becomes a module. A module is an object: it is  
created (usually by importing it), it has attributes, there are module  
hierarchies (packages), contains other objects... A module is an important  
object in Python. You should not confuse the module with the class (or  
classes) that are defined inside it. In your example above, test.A is a  
module, test.A.A is a class; they're not the same thing. You may put one  
class per file, nobody forbids that - but remember that the class and the  
module are different objects.
If you follow PEP8 conventions, module names are all in lowercase, and  
class names use TitleCase. This helps avoid confusion.


--
Gabriel Genellina

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


Re: import bug

2009-11-01 Thread Gabriel Genellina
En Sun, 01 Nov 2009 19:51:04 -0300, Steven D'Aprano  
 escribió:

On Sun, 01 Nov 2009 17:34:19 -0300, Gabriel Genellina wrote:

En Sun, 01 Nov 2009 02:54:15 -0300, Steven D'Aprano escribió:



Shadowing a standard library module
is no different.


But that's what namespaces are for; if the standard library had its own
namespace, such collisions would not occur.


Sure. But that's not a bug in the import system. If it's a bug, it's a
bug in the layout of the standard library.


Half and half? The standard library cannot have a different structure  
because the import system cannot handle it in a backgwards compatible way?


--
Gabriel Genellina

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


Re: import bug

2009-11-01 Thread Gabriel Genellina
En Sun, 01 Nov 2009 19:01:42 -0300, MRAB   
escribió:

Gabriel Genellina wrote:



One way to avoid name clashes would be to put the entire standard
library under a package; a program that wants the standard re
module would write "import std.re" instead of "import re", or
something similar.

 You could do it in a backwards compatible way, by adding the std
package directory into the path.

 Unfortunately you can't, at least not without some special treatment
of the std package. One of the undocumented rules of the import
system is that you must not have more than one way to refer to the
same module (in this case, std.re and re). [...]

Couldn't the entry in sys.modules be where the module was found, so that
if 're' was found in 'std' then the entry is 'std.re' even if the import
said just 're'?


What about a later 'import re'? 're' would not be found in sys.modules  
then.
In any case, it requires a change in the current behavior, a PEP, and a  
lot of discussion...


--
Gabriel Genellina

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


Re: About one class/function per module

2009-11-01 Thread Steven D'Aprano
On Sun, 01 Nov 2009 18:33:57 -0800, alex23 wrote:

> Peng Yu  wrote:
>> So I am asking disadvantages besides python import mechanism is not
>> friendly to it.
> 
> Which part of "name collisions have to be resolved somehow" isn't
> explicit enough for you?
> 
> You can't keep saying "this works in C++" while refusing to accept that
> this is an implementation decision with Python.

Oh, it doesn't work to Peng Yu's satisfaction in C++ either. In an 
earlier email, he wrote:


"I'm not complaining. I just wish there is a walkaround. In C++, I
still have to write some script to make sure the directory hierarchy
is consistent with the namespace, because C++ doesn't impose the
constraint that the directory hierarchy is the same as the namespace.
But it seems that is no such walkaround in python for my case, because
python binds namespace to directory hierarchy."

You got that? In Python, which forces the namespace and directory 
hierarchy to be the same, he wants them to be independent; in C++, which 
relaxes that restriction, he writes scripts to force them to be the same.


[Aside: the word is "work-around" not "walk-around". Easy mistake to 
make.]



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


Re: spring effect in Python

2009-11-01 Thread Cleber Santos
You can try this: http://processingjs.org


On Fri, Oct 30, 2009 at 5:26 AM, pochis40  wrote:

> I'm trying to write in Python something similar to this:
> (Java)
> http://java.sun.com/applets/jdk/1.4/demo/applets/GraphLayout/example1.html
> or these:
> (Proce55ing)
> http://www.cricketschirping.com/processing/ExportAtlas/
> or
>
> http://www.cricketschirping.com/weblog/2005/12/11/force-directed-graph-layout-with-proce55ing/
> or
>
> http://www.cricketschirping.com/weblog/2007/02/26/force-directed-graph-layout-with-processing-take-2/
>
> I've problem to find something that give that physical effect (like a
> spring).
>
> Any idea?
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Cleber Santos
website: binho.net
skype: binhoweb
msn: m...@binho.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter callback arguments

2009-11-01 Thread Lord Eldritch
Alf P. Steinbach wrote:

> * MRAB:

Thank you all! It is working now nicely! God! I love usenet..:D
-- 
Lord Eldritch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regular express question

2009-11-01 Thread alex23
On Oct 31, 12:48 pm, elca  wrote:
> Hello,
> i have some text document to parse.
> sample text is such like follow
> in this document, i would like to extract such like
> SUBJECT = 'NETHERLANDS MUSIC EPA'
> CONTENT = 'Michael Buble performs in Amsterdam Canadian singer Michael Buble
> performs during a concert in Amsterdam, The Netherlands, 30 October 2009.
> Buble released his new album entitled 'Crazy Love'. EPA/OLAF KRAAK '
>
> if anyone help me,much appreciate
>
> "
> NETHERLANDS MUSIC EPA | 36 before
> Michael Buble performs in Amsterdam Canadian singer Michael Buble performs
> during a concert in Amsterdam, The Netherlands, 30 October 2009. Buble
> released his new album entitled 'Crazy Love'. EPA/OLAF KRAAK
> "

You really don't need regular expressions for this:

>>> import os
>>> eol = os.linesep
>>> text = '''
... NETHERLANDS MUSIC EPA | 36 before
... Michael Buble performs in Amsterdam Canadian singer Michael Buble
performs
... during a concert in Amsterdam, The Netherlands, 30 October 2009.
Buble
... released his new album entitled 'Crazy Love'. EPA/OLAF KRAAK
... '''
>>> text = text.strip() # remove eol markers
>>> subject = text.split(' | ')[0]
>>> content = ' '.join(text.split(eol)[1:])
>>> subject
'NETHERLANDS MUSIC EPA'
>>> content
"Michael Buble performs in Amsterdam Canadian singer Michael Buble
performs during a concert in Amsterdam, The Netherlands, 30 October
2009. Buble released his new album entitled 'Crazy Love'. EPA/OLAF
KRAAK"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: About one class/function per module

2009-11-01 Thread rustom
On Nov 2, 3:11 am, Peng Yu  wrote:
> I recently asked how to support one class/function per module under
> the title 'How to import only one module in a package when the package
> __init__.py has already imports the modules?' I summarize my key
> points below. In particular, I have to two questions:
> 1. What disadvantages there are to enforce one class/function per file?
> 2. How to better support one class/function per file in python?

Others have told you to discard your biases.
I would tell you to suspend them for a while (including our biases
against your biases)
and try to use emacs+ecb

>
> --
> I prefer organized my code one class/function per file (i.e per module
> in python). I know the majority of programmers don't use this
> approach. Therefore, I'm wondering what its disadvantage is.
>
> The advantages of one-function/class-per-file that I am aware of are
> the following items (maybe incomplete).
>   1. It is easy to see what functions and classes there are just by
> browsing the source directory, without the need of opening the file by
> an editor.

Primary intention of ecb

>   2. Testing code for a function/class can be organized along with the
> module for the function/class, which also makes it easier to keep
> track of the testing code for any function/class.
>   3. It is easy to move a function/class from one package to another
> by just moving files around.
If an editing task is found hard it just means youve never used emacs!

>   4. It is easy change variable names, etc., for a function/class by
> replacement in a file without worrying accidentally change variable
> names in other functions.
> I have used the above approach on a C++ project. And I use vim + ctags
> to navigate from a reference of a class/funciton to its definition. So
> far it works fine.
Should be possible to code this up in about 10 lines of emacs
Simple workaround is to select the function/class and run search-
replace on the selection
-- 
http://mail.python.org/mailman/listinfo/python-list


disable image loading to speed up webpage load

2009-11-01 Thread elca

Hi,
im using win32com 's webbrowser module.
i have some question about it..
is it possible to disable image loading to speed up webpage load?
any help ,much appreciate
thanks in advance
-- 
View this message in context: 
http://old.nabble.com/disable-image-loading-to-speed-up-webpage-load-tp26155440p26155440.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Feedback wanted on programming introduction (Python in Windows)

2009-11-01 Thread Pascal J. Bourguignon
Thad Smith  writes:

> Richard Heathfield wrote:
>
>> ... so I cheerfully installed it on the user's desktop machine
>> (Windows ME, would you believe), and then set about configuring the
>> reader, when... ouch! No PDF reader on the machine. Not even an
>> ancient Adobe version. Oh dear. Program suddenly rendered completely
>> useless for that person.
>
> There is a Catch 22 for installing Adobe Reader from the Adobe site (
> http://get.adobe.com/reader/ ) for the first time, without making a
> blind promise: "By clicking the Download button you agree to the
> License Agreements and Privacy Policies for the software included."
> Guess what format the license agreement is in.  ;-)

Use xpdf to read it!

Then use xpdf to read the other pdf documents, and forget about
proprietary software?

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


Re: spring effect in Python

2009-11-01 Thread Cousin Stanley

> 
> I've problem to find something that give that physical effect 
> ( like a spring).
>
> Any idea?

  You may find VPython useful for simulating physical effects  

  http://www.vpython.org/

  Examples including a couple that are spring-related 

  http://matterandinteractions.org/Content/Materials/programs1.html

-- 
Stanley C. Kitching
Human Being
Phoenix, Arizona

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


Re: self.__dict__ tricks

2009-11-01 Thread Steven D'Aprano
On Sat, 31 Oct 2009 11:15:48 -0500, Tim Johnson wrote:

> Many programmers I know stay away from 'lists' such as this, because
> they are afraid to show their ignorance. Me, I'm fearless, and I have
> learned a lot that I might not have otherwise.

The only stupid question is the one you are afraid to ask.

Good luck!


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


Re: list comprehension problem

2009-11-01 Thread Mel
Steven D'Aprano wrote:

> (6) Metaphoric equivalence:
> Kali is death.
> Life is like a box of chocolates.

OK to here, but this one switches between metaphor and simile, and arguably, 
between identity and equality.

Mel.


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


Re: list comprehension problem

2009-11-01 Thread Cousin Stanley

> 
> There are an infinite number of empty sets 
> that differ according to their construction:
> 
> The set of all fire-breathing mammals.
> 

  Apparently, you have never been a witness
  to someone who recently ingested one of
  Cousin Chuy's Super-Burritos .. :-)


-- 
Stanley C. Kitching
Human Being
Phoenix, Arizona

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


Re: Pyfora, a place for python

2009-11-01 Thread Ben Finney
Saketh  writes:

> If you have any suggestions, let me know -- this is a community
> effort!

Suggestion: Please don't make efforts to fragment the community.

Rather, please direct seekers to the existing forums (the IRC channel,
the Usenet groups and mailing lists) rather than setting up new walled
gardens.

-- 
 \“None can love freedom heartily, but good men; the rest love |
  `\   not freedom, but license.” —John Milton |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


The Python: Rag November issue available

2009-11-01 Thread Bernie
The November issue of The Python: Rag is available at:

http://www.pythonrag.org

A monthly, free, community run, Python magazine - issues are in pdf 
format, intended for anyone interested in Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: python-ldap-2.3.10

2009-11-01 Thread Michael Ströder
Find a new release of python-ldap:

  http://www.python-ldap.org/

python-ldap provides an object-oriented API to access LDAP directory
servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for
that purpose. Additionally it contains modules for other LDAP-related
stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema).

Ciao, Michael.

-- 
Michael Ströder
E-Mail: mich...@stroeder.com
http://www.stroeder.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Regular express question

2009-11-01 Thread elca

Hello,
i have some text document to parse.
sample text is such like follow
in this document, i would like to extract such like
SUBJECT = 'NETHERLANDS MUSIC EPA' 
CONTENT = 'Michael Buble performs in Amsterdam Canadian singer Michael Buble
performs during a concert in Amsterdam, The Netherlands, 30 October 2009.
Buble released his new album entitled 'Crazy Love'. EPA/OLAF KRAAK '

if anyone help me,much appreciate 

"
NETHERLANDS MUSIC EPA | 36 before
Michael Buble performs in Amsterdam Canadian singer Michael Buble performs
during a concert in Amsterdam, The Netherlands, 30 October 2009. Buble
released his new album entitled 'Crazy Love'. EPA/OLAF KRAAK 
"
-- 
View this message in context: 
http://old.nabble.com/Regular-express-question-tp26139434p26139434.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: About one class/function per module

2009-11-01 Thread Dave Angel

Peng Yu wrote:



Some people mentioned an good IDE can do 1 and 4. But I'm not aware of
an IDE that can allow me to change file name freely. I tried Visual
Studio long time ago, I have to delete a file, change the file name
and add the file back in order to change the file.

  
I use Komodo IDE version 5, where right-click->Rename works fine on 
files within a project.

Now let us consider how well python can support one function/class per
file style. I encounter the following problems. Suppose that the
parent directory of 'test' is in $PYTHONPATH and __init__.py is empty,

test/
|-- __init__.py
|-- A.py
`-- B.py

where A.py has only class A and B.py has only class B.

The end user of the test package has to either

  import test.A
  a=test.A.A()

or

  from test.A import A
  a=A()


I'm neither agreeing nor disagreeing with the self-imposed restriction 
of one class per module.  But I'd like to jump in with an idea on 
dealing with the namespaces involved.


How about a two-line import, where the second line is a simple assignment?


import test.A
test.A = test.A.A

Now, you can use the class A just as you wanted --
obj = test.A()

This has the disadvantage that the module itself is no longer 
addressable from here.  But since the only symbol you apparently want 
from the module is the one class, it should be fine.  And you could 
presumably have saved it in a module-specific global anyway.


Note that I did not test whether other modules that also import test.A 
are affected.  So some further study would be necessary.  Also, I tried 
it only in CPython 2.6.2



DaveA

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


Re: Feedback wanted on programming introduction (Python in Windows)

2009-11-01 Thread Thad Smith

Richard Heathfield wrote:

... so I cheerfully installed it on the 
user's desktop machine (Windows ME, would you believe), and then set 
about configuring the reader, when... ouch! No PDF reader on the 
machine. Not even an ancient Adobe version. Oh dear. Program suddenly 
rendered completely useless for that person.


There is a Catch 22 for installing Adobe Reader from the Adobe site ( 
http://get.adobe.com/reader/ ) for the first time, without making a 
blind promise: "By clicking the Download button you agree to the License 
Agreements and Privacy Policies for the software included."  Guess what 
format the license agreement is in.  ;-)


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


Re: About one class/function per module

2009-11-01 Thread alex23
Peng Yu  wrote:
> So I am asking disadvantages besides python import mechanism is not
> friendly to it.

Which part of "name collisions have to be resolved somehow" isn't
explicit enough for you?

You can't keep saying "this works in C++" while refusing to accept
that this is an implementation decision with Python.

At least be honest about what you're asking for, which is confirmation
of your existing bias.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stdin in embedded python

2009-11-01 Thread Dave Angel

Gabriel Genellina wrote:
En Sun, 01 Nov 2009 13:34:44 -0300, KillSwitch 
 escribió:

On Nov 1, 5:34 am, Dave Angel  wrote:

KillSwitch wrote:


> I have a C++ program, with a GUI, into which I have embedded 
python. I

> have made several python functions in C++, one of which I use to
> override the normal stdout and stderr so that they print to a text 
box

> of my GUI. One thing I cannot think of how to do is to redefine stdin
> so that it pauses the program, waits for a user to type input into 
the
> box, hit enter, and takes input from another text element and 
sends it

> to python like it was the console.

I suspect you don't really want to redirect stdin, but instead 
implement
raw_input(). [...]Try changing __builtins__.raw_input  to reference 
your new

function.


But what would the function do? How would it pause python and wait for
it to have text to send?


Whatever you want. You don't have to "pause python", Python itself 
won't resume until your function doesn't return. (You should release 
the GIL if your C++ function doesn't call back to Python code, to 
allow other threads to continue, but that's another story).
This is a raw_input replacement written in Tkinter; it shows a dialog 
box instead of reading from stdin:


py> from Tkinter import *
py> from tkSimpleDialog import askstring
py> def my_raw_input(prompt):
...   return askstring("Python", prompt)
...
py> root = Tk()
py> import __builtin__
py> __builtin__.raw_input = my_raw_input
py>
py> raw_input("What's your name?")
'Gabriel'




I think I see the OP's problem.  He has written a GUI program in C++, 
and is using (embedding) Python functions into it.  So presumably those 
functions are being called from events in the C++ event loop.


If one of those functions tries to call back into C++ code, the event 
loop will never get control, to process the events from the standard UI 
controls.


So if the input is to be handled as an integral part of the C++ UI, 
there's a distinct problem.


On the other hand, Gabriel's dialog box should work fine, as long as you 
don' t mind a modal dialog box as a solution.  I don't know tkinter's 
askstring, but I suspect it'd work.  However, the rest of the C++ GUI 
would be frozen, which could be a problem.


DaveA

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


Re: Pyfora, a place for python

2009-11-01 Thread alex23
Saketh  wrote:
> If you have any suggestions, let me know -- this is a community
> effort!

I'd like to suggest Pyaspora as a more apropos name ;)

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


Re: About one class/function per module

2009-11-01 Thread metal
On 11月2日, 上午9时27分, Peng Yu  wrote:
> On Sun, Nov 1, 2009 at 7:02 PM, alex23  wrote:
> > On Nov 2, 8:11 am, Peng Yu  wrote:
> >> I prefer organized my code one class/function per file (i.e per module
> >> in python). I know the majority of programmers don't use this
> >> approach. Therefore, I'm wondering what its disadvantage is.
>
> > You mean, what disadvantages it has _other_ than the ones you've been
> > experiencing?
>
> > Aren't those enough to warrant actually working with Python's import
> > mechanism rather than against it?
>
> At least, I can use the following for now with one class/function per
> module. Unless this one class/function per module style have other
> disadvantages in term software engineering, I still can live with
> typing the class name (e.g. 'A') twice.
>
>  import test.A
>  a=test.A.A()
>
> So I am asking disadvantages besides python import mechanism is not
> friendly to it.

I recommand you double check django project, to learn how to organize
python project
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: About one class/function per module

2009-11-01 Thread Peng Yu
On Sun, Nov 1, 2009 at 7:02 PM, alex23  wrote:
> On Nov 2, 8:11 am, Peng Yu  wrote:
>> I prefer organized my code one class/function per file (i.e per module
>> in python). I know the majority of programmers don't use this
>> approach. Therefore, I'm wondering what its disadvantage is.
>
> You mean, what disadvantages it has _other_ than the ones you've been
> experiencing?
>
> Aren't those enough to warrant actually working with Python's import
> mechanism rather than against it?

At least, I can use the following for now with one class/function per
module. Unless this one class/function per module style have other
disadvantages in term software engineering, I still can live with
typing the class name (e.g. 'A') twice.

 import test.A
 a=test.A.A()

So I am asking disadvantages besides python import mechanism is not
friendly to it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list comprehension problem

2009-11-01 Thread Mick Krippendorf
Steven D'Aprano wrote:
> On Sun, 01 Nov 2009 21:32:15 +0100, Mick Krippendorf wrote:
>>
>> (Ax)(x is a fire-breathing animal <-> x is a real number equal to
>> sqrt(-1)).
>>
>> And since there are neither such things, it follows that s1 = s2.
> 
> That assumes that all({}) is defined as true. That is a common definition 
> (Python uses it), it is what classical logic uses, and it often leads to 
> the "obvious" behaviour you want, but there is no a priori reason to 
> accept that all({}) is true, and indeed it leads to some difficulties:
> 
> All invisible men are alive.
> All invisible men are dead.
> 
> are both true. Consequently, not all logic systems accept vacuous truths.
> 
> http://en.wikipedia.org/wiki/Vacuous_truth

You're right, of course, but I'm an oldfashioned quinean guy :-) Also,
in relevance logic and similar systems my beloved proof that there are
no facts (Davidson's Slingshot) goes down the drain. So I think I'll
stay with classical logic FTTB.

Regards,
Mick.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: About one class/function per module

2009-11-01 Thread alex23
On Nov 2, 8:11 am, Peng Yu  wrote:
> I prefer organized my code one class/function per file (i.e per module
> in python). I know the majority of programmers don't use this
> approach. Therefore, I'm wondering what its disadvantage is.

You mean, what disadvantages it has _other_ than the ones you've been
experiencing?

Aren't those enough to warrant actually working with Python's import
mechanism rather than against it?

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


Re: Feedback wanted on programming introduction (Python in Windows)

2009-11-01 Thread Alf P. Steinbach

* Rhodri James:
On Sun, 01 Nov 2009 21:20:20 -, Alf P. Steinbach  
wrote:



* Rhodri James:


This is a weird attribution style, by the way.  I don't think it helps.


That's a pretty weird thing to comment on.

And as far as I can see the comment doesn't make sense except as an attempt to 
find something negative to say.


But anyway, the point about '*' was, once upon a time, that it made for a very 
clear style of quoting in old newsreaders. Nowadays the tools are generally of 
lesser quality (e.g. I'm using Thunderbird). And so it doesn't really have much 
of that advantage left, but I'm using it anyway; I can be pretty stubborn about 
issues of quality.



On Fri, 30 Oct 2009 03:26:45 -, Alf P. Steinbach  
wrote:



* Rhodri James:
On Thu, 29 Oct 2009 16:53:05 -, Alf P. Steinbach 
 wrote:
with the best knowledge of the program's environment, is unable to 
handle (such as delete) files or folders with paths greater than 
some 260 characters, is unable to handle filenames that differ 
only in case and are in the same directory, and is unable to e.g. 
delete a folder called "con"  --  although such files & folders 
can very easily be created.
 You may or may not be aware that some of these things are 
limitations of

the underlying disc format,


Sorry no, it isn't.

Even assuming you meant the more reasonable "file system", no, it 
isn't.

 Actually I should have mentioned the filing system as well as the disc
format (which does matter).  I may not be using correct Windows 
terminology,

since I'm referring to both the bytes on hardware and the software stack
that terminates in the OS API.
 Still, colour me surprised.  I had assumed that NTFS had some (large)
limit on filenames, and 256 sounded plausible.


For NTFS it's 32K or 64K wide characters, I don't recall which. But 
what's important is that that's also the API level limit. You can find 
most of the details in Microsoft's documentation of CreateFile (but 
it's off-topic here).


Actually it [the limit]'s not


You're disputing a plain fact.

For which you've been given a technical reference, as well as concrete example.

I'm sorry, but it's idiotic to dispute plain facts.



, since it's a perfect example of the "not reading quite
carefully enough" others have pointed out before.  You make this statement
as an absolute, iron-clad assertion.  Checking the MS website, we find it
actually says:

"Maximum Path Length Limitation

In the Windows API (with some exceptions discussed in the following 
paragraphs), the maximum length for a path is MAX_PATH, which is defined 
as 260 characters."


The exceptions are unicode versions of some of the functions, which do
give you ~32K characters.  However, the docs are pretty specific about
what is and isn't the API limit.


I'm sorry but you're misunderstanding the documentation.

In your own words, you're "not reading quite carefully enough".

By the way, your technique of vague ad hominem attack here is detestable.

But anyway, if you read the documentation of CreateFile as I directed you to, or 
simply read on where you was, then you get a more technically correct picture.


Or, by applying logic you can /deduce/ that since >260 character paths can and 
do exist, 260 characters is not "the limit".


The MS documentation is unfortunately not all that clear. In many cases (the 
most infamous one is perhaps the claim that a program's entry point is WinMain) 
it's just plain incorrect, being written by technical writers. But it's simple 
enough to write a few programs to check it out.




 Since this applies to the command
line just as much as to GUIs,


No, it doesn't. And you've been given a concrete example of how.

You can't just go on *inventing* facts.

Facts are facts, your fantasies & wishes are your fantasies & wishes.



I'll repeat my claim that blaming Explorer
for something that causes just as much grief on a command line is a
tad unfair.


I'm sorry, but there's a complete lack of logic in that, as well as 
misdirection.

First, regarding the misdirection, it is untrue that I have "blamed" Windows 
Explorer for this. The blame, if any is to be affixed anywhere, belongs 
elsewhere than with a computer program.


Second, regarding the logic, that a program exhibits low quality in some respect 
is not OK just because there's another program that also exhibits low quality.




More importantly, I accuse you of making very definitive statments
that turn out to be insufficiently researched.


That would be OK and what I want. :-) But you haven't. You're making general 
vague statements about quality, but haven't addressed any concrete thing in the 
text. And what you have responded to here in this thread, it's all been 
incorrect. In this latest article you have even started disputing simple 
technical facts and started making fallacious deductions, shown above.




 That's not an
encouraging state of affairs in someone planning to write a beginners'
textbook.  Having originally learned C

Re: Feedback wanted on programming introduction (Python in Windows)

2009-11-01 Thread Rhodri James
On Sun, 01 Nov 2009 21:20:20 -, Alf P. Steinbach   
wrote:



* Rhodri James:


This is a weird attribution style, by the way.  I don't think it helps.

On Fri, 30 Oct 2009 03:26:45 -, Alf P. Steinbach   
wrote:



* Rhodri James:
On Thu, 29 Oct 2009 16:53:05 -, Alf P. Steinbach   
wrote:
with the best knowledge of the program's environment, is unable to  
handle (such as delete) files or folders with paths greater than  
some 260 characters, is unable to handle filenames that differ only  
in case and are in the same directory, and is unable to e.g. delete  
a folder called "con"  --  although such files & folders can very  
easily be created.
 You may or may not be aware that some of these things are  
limitations of

the underlying disc format,


Sorry no, it isn't.

Even assuming you meant the more reasonable "file system", no, it  
isn't.

 Actually I should have mentioned the filing system as well as the disc
format (which does matter).  I may not be using correct Windows  
terminology,

since I'm referring to both the bytes on hardware and the software stack
that terminates in the OS API.
 Still, colour me surprised.  I had assumed that NTFS had some (large)
limit on filenames, and 256 sounded plausible.


For NTFS it's 32K or 64K wide characters, I don't recall which. But  
what's important is that that's also the API level limit. You can find  
most of the details in Microsoft's documentation of CreateFile (but it's  
off-topic here).


Actually it's not, since it's a perfect example of the "not reading quite
carefully enough" others have pointed out before.  You make this statement
as an absolute, iron-clad assertion.  Checking the MS website, we find it
actually says:

"Maximum Path Length Limitation

In the Windows API (with some exceptions discussed in the following  
paragraphs), the maximum length for a path is MAX_PATH, which is defined  
as 260 characters."


The exceptions are unicode versions of some of the functions, which do
give you ~32K characters.  However, the docs are pretty specific about
what is and isn't the API limit.  Since this applies to the command
line just as much as to GUIs, I'll repeat my claim that blaming Explorer
for something that causes just as much grief on a command line is a
tad unfair.

More importantly, I accuse you of making very definitive statments
that turn out to be insufficiently researched.  That's not an
encouraging state of affairs in someone planning to write a beginners'
textbook.  Having originally learned C from one of Herbert Schildt's
books, I reckon I've earned the right to be highly allergic to this!

--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Doesn't MS-Windows likes Python ? (or: why more than 20 sec delay when running a program from Python)

2009-11-01 Thread Stef Mientki

hello,

I've an AutoIt program that set some switches in the LAN settings.

When I launch the AutoIt executable, the settings are changed immediately.

When I launch the AutoIt executable from python (which is the intention),
it hangs for about 20 seconds, before any action appears on the screen.

Analyzing the script, shows that it hangs on the next 2 lines:

  Run ( "control.exe ncpa.cpl" )
  WinWait( "Network Connections")

Transfering the Run command to Python, it hangs on the next subprocess call
 subprocess.call ( [ r"control.exe",  "ncpa.cpl" ])

Does anyone have a clue, why starting a process takes 20 seconds longer 
when ran from Python ?


And even more important, is there a work around ?

thanks,
Stef Mientki
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why 'import module' will not import module.py but the directory module?

2009-11-01 Thread Colin W.

Robert Kern wrote:

On 2009-10-31 19:16 PM, Peng Yu wrote:
On Sat, Oct 31, 2009 at 7:02 PM, Robert Kern  
wrote:

On 2009-10-31 18:51 PM, Peng Yu wrote:


If I have both the directory 'module' and the file 'module.py' in a
directory in $PYTHONPATH, python will import 'module' rather than
'module.py'. I'm wondering what is the design rationale of setting
higher priorities to directories. Is there a way to reverse the
priority?


You mean that you have a package "module/"? With an __init__.py? Plain
directories that aren't packages shouldn't be imported by Python.


Yes. I mean a pakcage 'module/' with an __init__.py.


No, you can't reverse the priority between packages and modules. I'm not
sure why that would help you. The package would then be inaccessible 
if you

did. If it's inaccessible, then why have it at all?


Why the package 'module' has to be inaccessible? I can 'import
module.part1' to access the component of the package.


No, it wouldn't. It's a moot point because Python picks the package 
first, but if it did pick modules before packages, then 
sys.modules['module'] would point to the module from module.py and not 
module/__init__.py . "import module.part1" first executes "import 
module", then looks in there to determine who to resolve "module.part1". 
Since sys.modules['module'] is a regular module and not the package, it 
wouldn't find module/part1.py .


Doesn't it make sense to avoid the use of names like module or package, 
even though they are permitted.


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


Re: Tkinter callback arguments

2009-11-01 Thread Alf P. Steinbach

* MRAB:

Lord Eldritch wrote:

Hi

Maybe this is maybe something it has been answered somewhere but I 
haven't been able to make it work. I wanna pass one variable to a 
callback function and I've read the proper way is:


Button(.., command=lambda: function(x))

So with

def function(a): print a

I get the value of x. Ok. My problem now is that I generate the 
widgets in a loop and I use the variable to 'label' the widget:


for x in range(0,3):  Button(.., command=lambda: function(x))

so pressing each button should give me 0,1,2.

But with the lambda, I always get the last index, because it gets 
actualized at each loop cycle. Is there any way to get that?



A lambda expression is just an unnamed function. At the point the
function is /called/ 'x' is bound to 3, so that's why 'function' is
always called with 3.

A function's default arguments are evaluated when the function is
/defined/, so you can save the current value of 'x' creating the
function (the lambda expression, in this case) with a default argument:

for x in range(0,3):
Button(.., command=lambda arg=x: function(arg))

The following will also work, although you might find the "x=x" a bit
surprising/confusing if you're not used to how Python works:

for x in range(0,3):
Button(.., command=lambda x=x: function(x))


An alternative reusable alternative is to create a button-with-id class.

This is my very first Python class so I'm guessing that there are all sorts of 
issues, in particular naming conventions.


And the idea of creating a reusable solution for such a small issue may be 
un-pythonic?


But just as an example, in Python 3.x,



import tkinter
# I guess for Python 2.x do "import Tkinter as tkinter" but haven't tested.


class IdButton( tkinter.Button ):
def __init__( self, owner_widget, id = None, command = None, **args ):
tkinter.Button.__init__(
self, owner_widget, args, command = self.__on_tk_command
)
self.__id = id
self.__specified_command = command

def __on_tk_command( self ):
if self.__specified_command != None:
self.__specified_command( self )
else:
self.on_clicked()

def on_clicked( self ):
pass
def id( self ):
return self.__id
def id_string( self ):
return str( self.id() );


def on_button_click( aButton ):
print( "Button " + aButton.id_string() + " clicked!" )

window = tkinter.Tk()

n_buttons = 3
for x in range( 1, n_buttons + 1 ):
IdButton(
window, id = x, text = "Button " + str( x ), command = on_button_click
).pack()

window.mainloop()



Cheers,

- Alf

PS: Now I see that I've used camelCase once. Oh well...
--
http://mail.python.org/mailman/listinfo/python-list


Function states [was Re: How to import only one module in a package when the package __init__.py has already imports the modules?]

2009-11-01 Thread Steven D'Aprano
On Sun, 01 Nov 2009 08:07:37 -0600, Peng Yu wrote:

> It is
> reasonable to assume the log of the number of states of a function or a
> class is proportional to it length. Hence, when a function or a
> class is long, you will never be able to test all its states.



def f(n):
return n + 5


def g(n):
x = n + 1
x += 1
x += 1
x += 1
return x + 1


Function g() has five times the length (in lines) as f(). Does it require 
five times the testing? Obviously not. In fact, there's no easy way to 
test the internal state of the function from outside, because x is local 
to g(). You can't test the value of x from outside, because x is not 
exposed to the outside.

The complexity of testing functions is roughly proportional to the number 
of paths through the function, not the number of lines. Both f() and g() 
have a single path through the function and therefore require the same 
amount of testing.

The simplest estimate of the number of paths in a function is the number 
of if...else statements. Each pair *doubles* the number of paths:

def func():
if cond1:  A
else:  B
if cond2:  C
else:  D
if cond3:  E
else:  F

There are 2**3 paths that need testing:

ACE ACF ADE ADF BCE BCF BDE BDF


Or consider this example:

def func(x, cond):
for f in [A, B, C, D, E, F]:
if cond(x): x = f(x)


This function has two lines only, but clearly there could be as many as 
128 paths that need testing. Ideally your test data should visit each one 
of these paths.



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


Re: How to import only one module in a package when the package __init__.py has already imports the modules?

2009-11-01 Thread Steven D'Aprano
On Sun, 01 Nov 2009 13:46:42 -0600, Robert Kern wrote:

> Peng Yu wrote:
>> On Sat, Oct 31, 2009 at 11:40 PM, Steven D'Aprano
>>  wrote:
> 
>>> Oh wait, I get it... you want to do a global search-and-replace over
>>> the entire file. *face-palm*
>> 
>> Yes. You get it.
> 
> In any capable programmer's editor, it should not be hard to do a local
> search-and-replace over just the one function.

Given the OP's stated claim that all his functions are less than a screen 
in size, Notepad could do it, with just the tiniest amount of manual 
effort.



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


Re: list comprehension problem

2009-11-01 Thread Steven D'Aprano
On Sun, 01 Nov 2009 21:32:15 +0100, Mick Krippendorf wrote:

> When we want find out if two sets s1 and s2 are the same we only need to
> look at their extensions, so given:
> 
> (i s1)(Ay)(y e s1  <->  y is a fire-breathing animal) (i s2)(Ay)(y e s2 
> <->  y is a real number equal to sqrt(-1))
> 
> we only need to find out if:
> 
> (Ax)(x is a fire-breathing animal <-> x is a real number equal to
> sqrt(-1)).
> 
> And since there are neither such things, it follows that s1 = s2.

That assumes that all({}) is defined as true. That is a common definition 
(Python uses it), it is what classical logic uses, and it often leads to 
the "obvious" behaviour you want, but there is no a priori reason to 
accept that all({}) is true, and indeed it leads to some difficulties:

All invisible men are alive.
All invisible men are dead.

are both true. Consequently, not all logic systems accept vacuous truths.

http://en.wikipedia.org/wiki/Vacuous_truth



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


Re: import bug

2009-11-01 Thread Steven D'Aprano
On Sun, 01 Nov 2009 17:34:19 -0300, Gabriel Genellina wrote:

> En Sun, 01 Nov 2009 02:54:15 -0300, Steven D'Aprano
>  escribió:
>> On Sun, 01 Nov 2009 01:38:16 -0300, Gabriel Genellina wrote:
> 
 Incorrect. Simplicity of implementation and API is a virtue, in and
 of itself. The existing module machinery is quite simple to
 understand, use and maintain.
>>>
>>> Uhm... module objects might be quite simple to understand, but module
>>> handling is everything but simple! (simplicity of implem...? quite
>>> simple to WHAT? ROTFLOL!!!  )
>>
>> I stand corrected :)
>> Nevertheless, the API is simple: the first time you "import name",
>> Python searches a single namespace (the path) for a module called name.
>> There are other variants of import, but the basics remain:
>>
>> search the path for the module called name, and do something with the
>> first one you find.
> 
> Sure, beautiful, a plain and simple search over a list of directories.
> That's how it worked in Python 1.4, I think... Now you have lots of
> "hooks" and even "meta-hooks": sys.meta_path, sys.path_hooks,
> sys.path_importer_cache. And sys.path, of course, which may contain
> other things apart of directory names (zip files, eggs, and even
> instances of custom "loader" objects...). 

You'll notice I deliberately didn't refer to directories. I just said 
"the path". If the path contains things other than directories, they are 
searched too.


> PEP 302 explains this but I'm
> not sure the description is still current. PEP369, if approved, would
> add even more hooks.
> Add packages to the picture, including relative imports and __path__[]
> processing, and it becomes increasingly harder to explain. Bret Cannon
> has rewritten the import system in pure Python (importlib) for 3.1; this
> should help to understand it, I hope. The whole system works, yes, but
> looks to me more like a collection of patches over patches than a
> coherent system. Perhaps this is due to the way it evolved.

You've convinced me that the implementation of the import infrastructure 
isn't as clean as I imagined. I'm sure it's a gnarly hack on top of 
gnarly hacks, and that maintaining it requires heroic measures worthy of 
a medal *grin*. 


 Dealing with name clashes doesn't come for free. If you think it
 does, I encourage you to write a patch implementing the behaviour you
 would prefer.
>>>
>>> I'd say it is really a bug, and has existed for a long time.
>>
>> Since import is advertised to return the first module with the given
>> name it finds, I don't see it as a bug even if it doesn't do what the
>> programmer intended it to do. [...] Shadowing a standard library module
>> is no different.
> 
> But that's what namespaces are for; if the standard library had its own
> namespace, such collisions would not occur. 


Sure. But that's not a bug in the import system. If it's a bug, it's a 
bug in the layout of the standard library.


>> You could do it in a backwards compatible way, by adding the std
>> package directory into the path.
> 
> Unfortunately you can't, at least not without some special treatment of
> the std package. One of the undocumented rules of the import system is
> that you must not have more than one way to refer to the same module (in
> this case, std.re and re). 

*slaps head*

How obvious in hindsight.



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


Re: About one class/function per module

2009-11-01 Thread Robert Kern

Peng Yu wrote:


So far, I haven't find one. It seems impossible in python, but I want
to double check if there is one solution.


We have already told you more than twice that the answer is "No." Please don't 
triple check.


--
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: Sqlite3. Substitution of names in query.

2009-11-01 Thread Carsten Haese
Lawrence D'Oliveiro wrote:
> Says someone who hasn't realized where the real inefficiencies are. Remember 
> what Tony Hoare told us: "premature optimization is the root of all evil". 
> These are databases we're talking about. Real-world databases are large, and 
> reside on disk, which is several orders of magnitude slower than RAM. And 
> RAM is where string parameter substitutions take place. So a few hundred 
> extra RAM accesses isn't going to make any significant difference to the 
> speed of database queries.

You're just not getting it. The cost is not in performing the parameter
substitutions themselves. The cost is in parsing what's essentially the
same query one million times over when it could have been parsed only
once. You might find an increase of seven orders of magnitude
insignificant, but I don't.

> Probably why I don't use Informix. What use is a binary data type if you 
> can't insert and retrieve binary data values?

You CAN insert and retrieve binary data values. You just have to use the
right tool for the job, and that is parameter binding.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: About one class/function per module

2009-11-01 Thread Diez B. Roggisch

Peng Yu schrieb:

I recently asked how to support one class/function per module under
the title 'How to import only one module in a package when the package
__init__.py has already imports the modules?' I summarize my key
points below. In particular, I have to two questions:
1. What disadvantages there are to enforce one class/function per file?
2. How to better support one class/function per file in python?


Are you aware that it's much easier to just let go about your 
preconceptions about how things should work, and instead adapt for 
*Pythocode* to the way *Python* works? The energy you've invested in 
coming up with contrived reasons for why e.g. one file per function is a 
good idea is better spent actually programming Python - and ejoying it.


Diez


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


About one class/function per module

2009-11-01 Thread Peng Yu
I recently asked how to support one class/function per module under
the title 'How to import only one module in a package when the package
__init__.py has already imports the modules?' I summarize my key
points below. In particular, I have to two questions:
1. What disadvantages there are to enforce one class/function per file?
2. How to better support one class/function per file in python?

--
I prefer organized my code one class/function per file (i.e per module
in python). I know the majority of programmers don't use this
approach. Therefore, I'm wondering what its disadvantage is.

The advantages of one-function/class-per-file that I am aware of are
the following items (maybe incomplete).
  1. It is easy to see what functions and classes there are just by
browsing the source directory, without the need of opening the file by
an editor.
  2. Testing code for a function/class can be organized along with the
module for the function/class, which also makes it easier to keep
track of the testing code for any function/class.
  3. It is easy to move a function/class from one package to another
by just moving files around.
  4. It is easy change variable names, etc., for a function/class by
replacement in a file without worrying accidentally change variable
names in other functions.
I have used the above approach on a C++ project. And I use vim + ctags
to navigate from a reference of a class/funciton to its definition. So
far it works fine.

Some people mentioned an good IDE can do 1 and 4. But I'm not aware of
an IDE that can allow me to change file name freely. I tried Visual
Studio long time ago, I have to delete a file, change the file name
and add the file back in order to change the file.


Now let us consider how well python can support one function/class per
file style. I encounter the following problems. Suppose that the
parent directory of 'test' is in $PYTHONPATH and __init__.py is empty,

test/
|-- __init__.py
|-- A.py
`-- B.py

where A.py has only class A and B.py has only class B.

The end user of the test package has to either

  import test.A
  a=test.A.A()

or

  from test.A import A
  a=A()

Both of the two cases are not satisfactory. In the first case, a end
user has to type A twice in test.A.A(), which is a burden to the end
user. In the second case, 'from test.A import A' screws up the
namespace, which might cause potential conflicts with classes of the
same name but from different packages.

I was also suggested to put the following line in __init__.py.

  from A import A
  from B import B

Then the end user can use the following code.

  import test
  test.A()

But the disadvantage is that I can not import individule file test.A
and test.B any more. Suppose that A is modified but not done yet, then
I modify B. Since the modification of A is not finished yet, the test
code of B won't run because the test code import test.A.

I'm looking for if there is a solution, so that a end user can use the
following code

  import test.A
  test.A()

So far, I haven't find one. It seems impossible in python, but I want
to double check if there is one solution.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: import bug

2009-11-01 Thread MRAB

Gabriel Genellina wrote:
[snip]

One way to avoid name clashes would be to put the entire standard
library under a package; a program that wants the standard re
module would write "import std.re" instead of "import re", or
something similar. Every time the std package is suggested, the
main argument against it is backwards compatibility.


You could do it in a backwards compatible way, by adding the std
package directory into the path.


Unfortunately you can't, at least not without some special treatment
of the std package. One of the undocumented rules of the import
system is that you must not have more than one way to refer to the
same module (in this case, std.re and re). Suppose someone imports
std.re; an entry in sys.modules with that name is created. Later
someone imports re; as there is no entry in sys.modules with such
name, the re module is imported again, resulting in two module
instances, darkness, weeping and the gnashing of teeth :) (I'm sure
you know the problem: it's the same as when someone imports the main
script as a module, and gets a different module instance because the
"original" is called __main__ instead).


Couldn't the entry in sys.modules be where the module was found, so that
if 're' was found in 'std' then the entry is 'std.re' even if the import
said just 're'?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Sqlite3. Substitution of names in query.

2009-11-01 Thread Lawrence D'Oliveiro
In message , Carsten 
Haese wrote:

> Lawrence D'Oliveiro wrote:
>
>> In message ,
>> Carsten Haese wrote:
>
>>> On what grounds are you asserting that it's not necessary to mix the
>>> two? Please elaborate your point.
>> 
>> On the grounds that Python has more general and powerful string
>> parameter- substitution mechanisms than anything built into any database
>> API.
> 
> That statement is fundamentally flawed. You are assuming that the
> preferred way of getting a value into a query is by substituting a
> literal into the query string. That is, in general, not true, because
> that would be horribly inefficient.

Says someone who hasn't realized where the real inefficiencies are. Remember 
what Tony Hoare told us: "premature optimization is the root of all evil". 
These are databases we're talking about. Real-world databases are large, and 
reside on disk, which is several orders of magnitude slower than RAM. And 
RAM is where string parameter substitutions take place. So a few hundred 
extra RAM accesses isn't going to make any significant difference to the 
speed of database queries.

> Finally, you're assuming that every value that can be supplied to a
> query actually HAS a literal form. That is not true. For example, in
> Informix databases, there are no literals for BYTE-type values.

Probably why I don't use Informix. What use is a binary data type if you 
can't insert and retrieve binary data values?

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


Re: __str__ difficulty with lists

2009-11-01 Thread Diez B. Roggisch

Jabba Laci schrieb:

Hi,

I have a list that contains custom objects. When printing the list,
I'd like to have a readable result, i.e. I'd like to see the output of
the __str__ functions. See an example below. When I call "print li", I
would like to get "[3, 5]". How to do that?


Use __repr__ instead - lists call that on their contained objects.


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


Re: Feedback desired on reworked ch 1 progr. intro (now Python 3.x, Windows)

2009-11-01 Thread Alf P. Steinbach

* Rhodri James:

Before we start, can I just say that I find Google Docs loathsome?

On Sat, 31 Oct 2009 07:40:36 -, Alf P. Steinbach  
wrote:


I hope this new version of ch 1 is, well, better, addresses some of 
the concerns raised? 


Section 1.1 needs serious work.


Could you please expand on that?

It is a hint.

Byt it doesn't leave me with much to go on regarding what you mean.



 You have a very assertive writing style
and a lot of things that you definitively state are at best debatable.
If I'd picked that up in a shop and browsed that opening, I'd put the
book down and walk away; essentially you're calling your accuracy into
question before you've even said anything about programming.


Could you please expand on this also? Sort of, more concrete?


Cheers & thanks,

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


Re: Feedback wanted on programming introduction (Python in Windows)

2009-11-01 Thread Alf P. Steinbach

* Rhodri James:
On Fri, 30 Oct 2009 03:26:45 -, Alf P. Steinbach  
wrote:



* Rhodri James:
On Thu, 29 Oct 2009 16:53:05 -, Alf P. Steinbach  
wrote:
with the best knowledge of the program's environment, is unable to 
handle (such as delete) files or folders with paths greater than 
some 260 characters, is unable to handle filenames that differ only 
in case and are in the same directory, and is unable to e.g. delete 
a folder called "con"  --  although such files & folders can very 
easily be created.
 You may or may not be aware that some of these things are 
limitations of

the underlying disc format,


Sorry no, it isn't.

Even assuming you meant the more reasonable "file system", no, it isn't.


Actually I should have mentioned the filing system as well as the disc
format (which does matter).  I may not be using correct Windows 
terminology,

since I'm referring to both the bytes on hardware and the software stack
that terminates in the OS API.

Still, colour me surprised.  I had assumed that NTFS had some (large)
limit on filenames, and 256 sounded plausible.


For NTFS it's 32K or 64K wide characters, I don't recall which. But what's 
important is that that's also the API level limit. You can find most of the 
details in Microsoft's documentation of CreateFile (but it's off-topic here).


Given that the API level makes it possible for long paths/names to exist, a 
program should be prepared to handle them, although it may reasonably refuse to 
create them. Windows Explorer fails to handle them. Not only to create them.


A filesystem may impose a lower limit, but a program should ideally not be 
limited to or just work with a given filesystem (note: Windows supports multiple 
different filesystems, but accessed via the same general API).




 More to the point, I
was under the impression that path manipulation logic in the filing
system had limited sized buffers, which were the cause of this fault,
and that Exploder's only sin was not programming around the bug.  In
fact, the more I think about it, the more sure I am that I've had to
play silly buggers on the command line myself to get around this.

Depending on the file system a program may be unable to create such 
things as I mentioned. And depending on the program design it may be 
reasonable to refuse to create them.


But a program should have no trouble deleting the files etc. once 
they're there.


Your faith is touching, but fundamentally misplaced.


By the facts, if I believed that most programs have no problem it would be a 
misplaced belief, yes (assuming that's what you mean above). But my argument and 
concrete example was the opposite. It expanded on my statement that


  "Unfortunately even most professional programs do not handle the requirements
  of their environs very well"

So in what you quoted above I used "should" in the sense of the ideal to strive 
for, and illustrated the harsh reality that it currently isn't that way, by the 
concrete Windows Explorer example.


This is worth keeping in mind: in a Usenet discussion, context often disappears. 
Looking up-thread is then one way to find out what it's all about. :-)



That's why the Windows API handles them just fine, while Windows 
Explorer does not. You may consider, since you're unfamiliar with the 
API, that mostly it's no problem doing these things in the command 
interpreter, which has no special support (rather, the reason it's 
easy is because it doesn't properly check command arguments). And from 
that you can deduce that the API support is there.


Having stuffed this up many, many years ago, my recollection is that
it needed a certain deviousness to get around.


Yes.



C:\> md rhodri & cd rhodri

C:\rhodri> md \\?\c:\rhodri\con

C:\rhodri> dir
 Volume in drive C is maindisk
 Volume Serial Number is C469-4FA2

 Directory of C:\rhodri

01.11.2009  22:16  .
01.11.2009  22:16  ..
01.11.2009  22:16  con
   0 File(s)  0 bytes
   3 Dir(s)  18 405 834 752 bytes free

C:\rhodri> cd con
The system cannot find the path specified.

C:\rhodri> cd \\?\c:\rhodri\con
'\\?\c:\rhodri\con'
CMD does not support UNC paths as current directories.

C:\rhodri> rd \\?\c:\rhodri\con

C:\rhodri> _



To keep it short the above example is of something that no program really is 
expected to handle. It's just an example of the mechanisms involved. Also, it's 
nice with concrete examples, to show that one is not just blowing wind. :-)




 In the case of the long
path names, my deduction from comparing the behaviours of the command
line and Explorer was that the API limited the path name length, and
Explorer didn't use relative paths to get around it.  I find it hard
to call that a bug, when it's only really exposing a limitation of the
underlying FS.


No, it's not exposing a limitation of the underlying FS.

It's exposing a limitation in the way that the program deals with paths.

Apparently Windows Explorer 

__str__ difficulty with lists

2009-11-01 Thread Jabba Laci
Hi,

I have a list that contains custom objects. When printing the list,
I'd like to have a readable result, i.e. I'd like to see the output of
the __str__ functions. See an example below. When I call "print li", I
would like to get "[3, 5]". How to do that?

Thanks,

Laszlo

==

class MyNumber:
def __init__(self, n):
self.n = n

def __str__(self):
return str(self.n)

if __name__ == "__main__":
li = []
a = MyNumber(3)
li.append(a)
li.append(MyNumber(5))
print li   # [<__main__.MyNumber instance at 0xb77a456c>,
<__main__.MyNumber instance at 0xb77a46ec>]
print a   # 3
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stdin in embedded python

2009-11-01 Thread Gabriel Genellina
En Sun, 01 Nov 2009 13:34:44 -0300, KillSwitch   
escribió:

On Nov 1, 5:34 am, Dave Angel  wrote:

KillSwitch wrote:



> I have a C++ program, with a GUI, into which I have embedded python. I
> have made several python functions in C++, one of which I use to
> override the normal stdout and stderr so that they print to a text box
> of my GUI. One thing I cannot think of how to do is to redefine stdin
> so that it pauses the program, waits for a user to type input into the
> box, hit enter, and takes input from another text element and sends it
> to python like it was the console.

I suspect you don't really want to redirect stdin, but instead implement
raw_input(). [...]Try changing __builtins__.raw_input  to reference  
your new

function.


But what would the function do? How would it pause python and wait for
it to have text to send?


Whatever you want. You don't have to "pause python", Python itself won't  
resume until your function doesn't return. (You should release the GIL if  
your C++ function doesn't call back to Python code, to allow other threads  
to continue, but that's another story).
This is a raw_input replacement written in Tkinter; it shows a dialog box  
instead of reading from stdin:


py> from Tkinter import *
py> from tkSimpleDialog import askstring
py> def my_raw_input(prompt):
...   return askstring("Python", prompt)
...
py> root = Tk()
py> import __builtin__
py> __builtin__.raw_input = my_raw_input
py>
py> raw_input("What's your name?")
'Gabriel'

--
Gabriel Genellina<>-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feedback desired on reworked ch 1 progr. intro (now Python 3.x, Windows)

2009-11-01 Thread Rhodri James

Before we start, can I just say that I find Google Docs loathsome?

On Sat, 31 Oct 2009 07:40:36 -, Alf P. Steinbach   
wrote:


I hope this new version of ch 1 is, well, better, addresses some of the  
concerns raised? 


Section 1.1 needs serious work.  You have a very assertive writing style
and a lot of things that you definitively state are at best debatable.
If I'd picked that up in a shop and browsed that opening, I'd put the
book down and walk away; essentially you're calling your accuracy into
question before you've even said anything about programming.

--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: Feedback wanted on programming introduction (Python in Windows)

2009-11-01 Thread Rhodri James
On Fri, 30 Oct 2009 03:26:45 -, Alf P. Steinbach   
wrote:



* Rhodri James:
On Thu, 29 Oct 2009 16:53:05 -, Alf P. Steinbach   
wrote:
with the best knowledge of the program's environment, is unable to  
handle (such as delete) files or folders with paths greater than some  
260 characters, is unable to handle filenames that differ only in case  
and are in the same directory, and is unable to e.g. delete a folder  
called "con"  --  although such files & folders can very easily be  
created.
 You may or may not be aware that some of these things are limitations  
of

the underlying disc format,


Sorry no, it isn't.

Even assuming you meant the more reasonable "file system", no, it isn't.


Actually I should have mentioned the filing system as well as the disc
format (which does matter).  I may not be using correct Windows  
terminology,

since I'm referring to both the bytes on hardware and the software stack
that terminates in the OS API.

Still, colour me surprised.  I had assumed that NTFS had some (large)
limit on filenames, and 256 sounded plausible.  More to the point, I
was under the impression that path manipulation logic in the filing
system had limited sized buffers, which were the cause of this fault,
and that Exploder's only sin was not programming around the bug.  In
fact, the more I think about it, the more sure I am that I've had to
play silly buggers on the command line myself to get around this.

Depending on the file system a program may be unable to create such  
things as I mentioned. And depending on the program design it may be  
reasonable to refuse to create them.


But a program should have no trouble deleting the files etc. once  
they're there.


Your faith is touching, but fundamentally misplaced.

That's why the Windows API handles them just fine, while Windows  
Explorer does not. You may consider, since you're unfamiliar with the  
API, that mostly it's no problem doing these things in the command  
interpreter, which has no special support (rather, the reason it's easy  
is because it doesn't properly check command arguments). And from that  
you can deduce that the API support is there.


Having stuffed this up many, many years ago, my recollection is that
it needed a certain deviousness to get around.  In the case of the long
path names, my deduction from comparing the behaviours of the command
line and Explorer was that the API limited the path name length, and
Explorer didn't use relative paths to get around it.  I find it hard
to call that a bug, when it's only really exposing a limitation of the
underlying FS.

For example, for general tool usage in Windows the student needs to  
know about levels of environment variable specifications and file  
associations, which in turn requires knowledge of processes and the  
Windows registry database and various commands.

 Mercifully this is rubbish.  For most purposes with most tools even
Windows users don't need to know much if anything about environment
variables and the registry.  Needing to know anything about the
registry is usually a sign that Windows has stuffed you up royally.


I deduce that you mainly use IDEs and don't know about the things you're  
commenting on here (more than you did above). Sorry, but there it is.


You deduce incorrectly.  I'd unbend enough to admit that setting
environment variables is frequently very useful to inveterate command-
line users like myself, and that Windows makes that a lot harder than
necessary, but your original statement still reads like scaremongering.

Why am I defending Windows again?

--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: list comprehension problem

2009-11-01 Thread Mick Krippendorf
Steven D'Aprano wrote:
> There are an infinite number of empty sets that differ according to their 
> construction:
> 
> The set of all American Presidents called Boris Nogoodnik.
> The set of all human languages with exactly one noun and one verb.
> The set of all fire-breathing mammals.
> The set of all real numbers equal to sqrt(-1).
> The set of all even prime numbers other than 2.
> The set of all integers between 0 and 1 exclusive.
> The set of all integers between 1 and 2 exclusive.
> The set of all positive integers between 2/5 and 4/5.
> The set of all multiples of five between 26 and 29.
> The set of all non-zero circles in Euclidean geometry where the radius 
> equals the circumference.
> ...

Logically, they're all the same, by extensionality. There is of course a
difference between the reference of an expression and it's meaning, but
logical truth only depends on reference.

In mathematical logic 'the thing, that ...' can be expressed with the
iota operator (i...), defined like this:

((ia)phi e b) := (Ec)((c e b) & (Aa)((a = b) <-> phi)).

with phi being a formula, E and A the existential and universal
quantors, resp., e the membership relation, & the conjunction operator
and <-> the bi-conditional operator.

When we want find out if two sets s1 and s2 are the same we only need to
look at their extensions, so given:

(i s1)(Ay)(y e s1  <->  y is a fire-breathing animal)
(i s2)(Ay)(y e s2  <->  y is a real number equal to sqrt(-1))

we only need to find out if:

(Ax)(x is a fire-breathing animal <-> x is a real number equal to
sqrt(-1)).

And since there are neither such things, it follows that s1 = s2.

BTW, '=' is usually defined as:

a = b  :=  (AabP)(Pa <-> Pb)

AKA the Leibniz-Principle, but this definition is 2nd order logic. If we
have sets at our disposal when we're axiomatisizing mathematics, we can
also define it 1st-orderly:

a = b  :=  (Aabc)((a e c) <-> (b e c))

Regargs,
Mick.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: import bug

2009-11-01 Thread Gabriel Genellina

En Sun, 01 Nov 2009 02:54:15 -0300, Steven D'Aprano
 escribió:

On Sun, 01 Nov 2009 01:38:16 -0300, Gabriel Genellina wrote:



Incorrect. Simplicity of implementation and API is a virtue, in and of
itself. The existing module machinery is quite simple to understand,
use and maintain.


Uhm... module objects might be quite simple to understand, but module
handling is everything but simple! (simplicity of implem...? quite
simple to WHAT? ROTFLOL!!!  )


I stand corrected :)
Nevertheless, the API is simple: the first time you "import name", Python
searches a single namespace (the path) for a module called name. There
are other variants of import, but the basics remain:

search the path for the module called name, and do something with the
first one you find.


Sure, beautiful, a plain and simple search over a list of directories.  
That's how it worked in Python 1.4, I think...
Now you have lots of "hooks" and even "meta-hooks": sys.meta_path,  
sys.path_hooks, sys.path_importer_cache. And sys.path, of course, which
may contain other things apart of directory names (zip files, eggs, and  
even instances of custom "loader" objects...). PEP 302 explains this but  
I'm not sure the description is still current. PEP369, if approved, would  
add even more hooks.
Add packages to the picture, including relative imports and __path__[]  
processing, and it becomes increasingly harder to explain.
Bret Cannon has rewritten the import system in pure Python (importlib) for  
3.1; this should help to understand it, I hope.
The whole system works, yes, but looks to me more like a collection of  
patches over patches than a coherent system. Perhaps this is due to the  
way it evolved.



Dealing with name clashes doesn't come for free. If you think it does,
I encourage you to write a patch implementing the behaviour you would
prefer.


I'd say it is really a bug, and has existed for a long time.


Since import is advertised to return the first module with the given name
it finds, I don't see it as a bug even if it doesn't do what the
programmer intended it to do. [...] Shadowing a standard library module  
is no different.


But that's what namespaces are for; if the standard library had its own  
namespace, such collisions would not occur. I can think of C++, Java, C#,  
all of them have some way of qualifying names. Python too - packages. But  
nobody came with a method to apply packages to the standard library in a  
backwards compatible way. Perhaps those name collisions are not considered  
serious. Perhaps every user module should live in packages and only the  
standard library has the privilege of using the global module namespace.
Both C++ and XML got namespaces late in their life so in principle this  
should be possible.



One way to
avoid name clashes would be to put the entire standard library under a
package; a program that wants the standard re module would write "import
std.re" instead of "import re", or something similar. Every time the std
package is suggested, the main argument against it is backwards
compatibility.


You could do it in a backwards compatible way, by adding the std package
directory into the path.


Unfortunately you can't, at least not without some special treatment of  
the std package. One of the undocumented rules of the import system is  
that you must not have more than one way to refer to the same module (in  
this case, std.re and re). Suppose someone imports std.re; an entry in  
sys.modules with that name is created. Later someone imports re; as there  
is no entry in sys.modules with such name, the re module is imported  
again, resulting in two module instances, darkness, weeping and the  
gnashing of teeth :)
(I'm sure you know the problem: it's the same as when someone imports the  
main script as a module, and gets a different module instance because the  
"original" is called __main__ instead).


--
Gabriel Genellina

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


Tkinter callback arguments

2009-11-01 Thread Lord Eldritch
Hi

Maybe this is maybe something it has been answered somewhere but I haven't 
been able to make it work. I wanna pass one variable to a callback function 
and I've read the proper way is:

Button(.., command=lambda: function(x))

So with

def function(a): print a

I get the value of x. Ok. My problem now is that I generate the widgets in a 
loop and I use the variable to 'label' the widget:

for x in range(0,3):  Button(.., command=lambda: function(x))

so pressing each button should give me 0,1,2.

But with the lambda, I always get the last index, because it gets actualized 
at each loop cycle. Is there any way to get that?

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


Re: Tkinter callback arguments

2009-11-01 Thread MRAB

Lord Eldritch wrote:

Hi

Maybe this is maybe something it has been answered somewhere but I haven't 
been able to make it work. I wanna pass one variable to a callback function 
and I've read the proper way is:


Button(.., command=lambda: function(x))

So with

def function(a): print a

I get the value of x. Ok. My problem now is that I generate the widgets in a 
loop and I use the variable to 'label' the widget:


for x in range(0,3):  Button(.., command=lambda: function(x))

so pressing each button should give me 0,1,2.

But with the lambda, I always get the last index, because it gets actualized 
at each loop cycle. Is there any way to get that?



A lambda expression is just an unnamed function. At the point the
function is /called/ 'x' is bound to 3, so that's why 'function' is
always called with 3.

A function's default arguments are evaluated when the function is
/defined/, so you can save the current value of 'x' creating the
function (the lambda expression, in this case) with a default argument:

for x in range(0,3):
Button(.., command=lambda arg=x: function(arg))

The following will also work, although you might find the "x=x" a bit
surprising/confusing if you're not used to how Python works:

for x in range(0,3):
Button(.., command=lambda x=x: function(x))
--
http://mail.python.org/mailman/listinfo/python-list


Tkinter callback arguments

2009-11-01 Thread Lord Eldritch
Hi

Maybe this is maybe something it has been answered somewhere but I haven't 
been able to make it work. I wanna pass one variable to a callback function 
and I've read the proper way is:

Button(.., command=lambda: function(x))

So with

def function(a): print a

I get the value of x. Ok. My problem now is that I generate the widgets in a 
loop and I use the variable to 'label' the widget:

for x in range(0,3):  Button(.., command=lambda: function(x))

so pressing each button should give me 0,1,2.

But with the lambda, I always get the last index, because it gets actualized 
at each loop cycle. Is there any way to get that?

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


Re: How to import only one module in a package when the package __init__.py has already imports the modules?

2009-11-01 Thread Robert Kern

Peng Yu wrote:

On Sat, Oct 31, 2009 at 11:43 PM, Steven D'Aprano
 wrote:

On Sat, 31 Oct 2009 22:54:47 -0500, Peng Yu wrote:


So python would not be able to accommodate my preference one
class/function per file?

Of course it does! You can do that RIGHT NOW -- just put one class per
file.


I.e., I have to use something like 'from spam
import spam' or 'spam.spam()',

How else do you expect to use the class if you don't import it?



or accept that the filename is not the
same as the class/function name.

So let me see...

You don't want to write "import spam; spam.spam()"
You don't want to write "from spam import spam; spam()"
You don't want to write "from Spam import spam; spam()"
You don't want to write "from spam import Spam; Spam()"

What exactly do you want?


When I define class spam in file spam.py, I want to call it by

import spam
spam()

If spam.py is in dir/, then I want to call it by

import dir.spam

dir.spam()


That's just not how Python imports work.

--
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: How to import only one module in a package when the package __init__.py has already imports the modules?

2009-11-01 Thread Robert Kern

Peng Yu wrote:

On Sat, Oct 31, 2009 at 11:40 PM, Steven D'Aprano
 wrote:



Oh wait, I get it... you want to do a global search-and-replace over the
entire file. *face-palm*


Yes. You get it.


In any capable programmer's editor, it should not be hard to do a local 
search-and-replace over just the one function.


--
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


ANN: blist 1.0.2

2009-11-01 Thread Daniel Stutzbach
blist 1.0.2 is now available:

http://pypi.python.org/pypi/blist/

What is blist?
--

The blist is a type that looks, acts, and quacks like a Python list, but has
better asymptotic performance when inserting or deleting elements (O(log
n)). For small lists, blists and the built-in list have very similar
performance.  The blist also features copy-on-write behavior, so copying or
taking large slices from a list is inexpensive.

What's new?
---

blist version 1.0.2 includes two important bug fixes:

- Fixed a crash in the .index method, which was not properly sanitizing the
optional arguments.
- Fixed a possible crash when modifying the blist during iteration

Other changes include:

- Changed int to Py_ssize_t in several places for better 64-bit hygiene
- Removed some over-zealous assertion checks that were causing crashes in
oddball (but legal!) cases in debug builds
- Ported tests to run under Python 2.6 and Python 3.1 (but no longer Python
2.5)
- Got rid of warnings on non-ix86 platforms

--
Daniel Stutzbach, Ph.D.
President, Stutzbach Enterprises, LLC 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I run a python program from within emacs?

2009-11-01 Thread rustom
On Nov 1, 7:20 pm, Robinson  wrote:
> I have also just started with both Aquamacs and Python so I ask for  
> your patience as well.
> When I evaluate the buffer (C-c C-C) I don't see any response or  
> output from my python program. Should another buffer open  
> automatically? Should a terminal window open?
> thanks for your patience.
> Rugbeia Floreat Ubique
>
> > On Mar 20, 3:09 pm, jmDesktop  wrote:
> > > Hi, I'm trying to learn Python.  I using Aquamac an emac
> > > implementation with mac os x.  I have a program.  If I go to the
> > > command prompt and type pythong myprog.py, it works.  Can the  
> > program
> > > be run from within the editor or is that not how development is  
> > done?

There are two python modes -- python.el and python-mode.el
Default with emacs is python.el, what comes from/with python is python-
mode.el (needs a download and a couple of lines of setup see
http://www.emacswiki.org/emacs/PythonMode). I recommend python-mode.

The key-bindings are different --C-c ! to start interpreter followed
by C-c C-c to exec a file.


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


Re: Can I run a python program from within emacs?

2009-11-01 Thread Robinson

Jason,
Thanks, but I have already tried your suggestions (which seem like  
logical cause/effect actions) and nothing.  There must be a python  
preference or something I haven't set correctly.


There is no Aquamacs list, but I'll check further.

Thanks again for the quick reply.


On Nov 1, 2009, at 9:15 AM, Jason Sewall wrote:

On Sun, Nov 1, 2009 at 9:20 AM, Robinson  
 wrote:
I have also just started with both Aquamacs and Python so I ask for  
your

patience as well.
When I evaluate the buffer (C-c C-C) I don't see any response or  
output from

my python program. Should another buffer open automatically? Should a
terminal window open?


I don't know much about Aquamacs or the version of Emacs the Aquamacs
you are using is based on, but the C-c C-c command runs
py-execute-buffer. Try M-x py-execute-buffer  and see what
happens. It should pop up a *Python Output* buffer, unless you're
actually running the python interpreter in Emacs, in which case the
code is run in that buffer.

If you're still having trouble, probably an Emacs or Aquamacs list is
a better place to look.

Jason


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


Re: stdin in embedded python

2009-11-01 Thread KillSwitch
On Nov 1, 5:34 am, Dave Angel  wrote:
> KillSwitch wrote:
> > I have a C++ program, with a GUI, into which I have embedded python. I
> > have made several python functions in C++, one of which I use to
> > override the normal stdout and stderr so that they print to a text box
> > of my GUI. One thing I cannot think of how to do is to redefine stdin
> > so that it pauses the program, waits for a user to type input into the
> > box, hit enter, and takes input from another text element and sends it
> > to python like it was the console.
>
> > I wonder if anyone could help me in trying to do such a thing. To
> > simplify, the new stdin should wait for the C++ function to give it a
> > value, like it waits for the console.
>
> I suspect you don't really want to redirect stdin, but instead implement
> raw_input().  If you have control over the script, just change it from
> raw_input() to cpp_raw_input().  But if  you need to be able to run
> arbitrary scripts, ...
>
> (untried) - Try changing __builtins__.raw_input  to reference your new
> function.
>
> DaveA

But what would the function do? How would it pause python and wait for
it to have text to send?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is Islam?-1

2009-11-01 Thread omer azazi
from python to exe


py2exe turns Python programs into packages that can be run on other
Windows computers without needing to install Python on those
computers. Python is needed on the computer where py2exe itself is run
because py2exe is a Python program and it includes parts of Python in
the package that is built.

see here

http://www.py2exe.org/index.cgi/Tutorial

http://www.py2exe.org/

http://www.scribd.com/doc/19792648/-python-to-exe


also
eclipse editor>>>
http://www.eclipse.org/downloads/


thank u again







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


Re: Can I run a python program from within emacs?

2009-11-01 Thread Jason Sewall
On Sun, Nov 1, 2009 at 9:20 AM, Robinson  wrote:
> I have also just started with both Aquamacs and Python so I ask for your
> patience as well.
> When I evaluate the buffer (C-c C-C) I don't see any response or output from
> my python program. Should another buffer open automatically? Should a
> terminal window open?

I don't know much about Aquamacs or the version of Emacs the Aquamacs
you are using is based on, but the C-c C-c command runs
py-execute-buffer. Try M-x py-execute-buffer  and see what
happens. It should pop up a *Python Output* buffer, unless you're
actually running the python interpreter in Emacs, in which case the
code is run in that buffer.

If you're still having trouble, probably an Emacs or Aquamacs list is
a better place to look.

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


Re: Pyfora, a place for python

2009-11-01 Thread Martijn Arts
I think it's a really good idea :) My accountname is "TotempaaltJ"

On Sun, Nov 1, 2009 at 8:48 AM, Paul Rubin wrote:

> Saketh  writes:
> > I am proud to announce the release of Pyfora (http://pyfora.org), an
> > online community of Python enthusiasts to supplement comp.lang.python
> > and #python.
>
> And the reason to want to further fragment Python discussion is
> exactly what?
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to import only one module in a package when the package __init__.py has already imports the modules?

2009-11-01 Thread Peng Yu
On Sat, Oct 31, 2009 at 11:40 PM, Steven D'Aprano
 wrote:
> On Sat, 31 Oct 2009 22:48:10 -0500, Peng Yu wrote:
>
>>> Variables in a function are already private.  How can the names in one
>>> function be affected by other functions in the same module?
>>
>> You misunderstood me.
>>
>> If there are multiple functions or classes in a file, when I change
>> variables in a function/class, I have to make sure that they are not in
>> other functions or classes.
>
> No you don't.
>
> def f(x):
>    return x+1
>
> def g(x):
>    return x-1
>
>
> If I choose to refactor f() and change "x" to "y", why do I care about
> the internal variable inside g()?

What I mean was, for example, I only want to change 'x' in f() to 'y',
but not 'x' in g() to 'y', because the meaning of 'x' in f() and 'x'
in g() may represent different things. If both f() and g() are in the
same file, I have to make sure that I only replace 'x' in f() but not
in g(). However, if I only have f() in a file, I can simply replace
all x in the file without worrying replacing 'x' in g(). Is this
clear?

> Oh wait, I get it... you want to do a global search-and-replace over the
> entire file. *face-palm*

Yes. You get it.

> If your functions are less than one-screen full, why do you need a global
> replacement? Global replacement risks changing words in docstrings,
> comments etc that it shouldn't.

My variables in general are not as short as a single letter, like 'x',
and is descriptive. In general, they will not appear in docstrings,
unless the ones in docstrings mean the same thing, in which case it is
OK to replace the variable and the one in docstrings.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for help getting tkinter to work.

2009-11-01 Thread Francesco Bochicchio
On Nov 1, 4:06 am, Shue Boks  wrote:
> I tried to compile Python and Tcl/Tk on Linux using the following
> files:
>
> Python-3.1.1.tar.gz
> tcl8.5.7-src.tar.gz
>
> Cannot get tkinter to work after compiling & installing Tcl/Tk.  I get
> the following error after compiling Python:
>
> "Python build finished, but the necessary bits to build these modules
> were not found:
> _tkinter
> To find the necessary bits, look in setup.py in detect_modules() for
> the module's name."
>
> Are the above files the correct versions to get tkinter to work?
>
> Thanks.

The version should be ok. I just compiled python3.1 against tcl/tk
8.5, only I used
the tcl/tk development packages coming with my distribution (Ubuntu).
I used
./configure --with-tk, so if you did not, try that first.

Did you run 'make install' during tcl/tk installation _before_ doing ./
configure in python source
directory?

If so, look where the library files ( e.g. libtk8.5.so ) and include
files (e.g tk.h ) have been placed
and check against the places where the function 'detect_tkinter' in
'setup.py' looks for them.

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


Can I run a python program from within emacs?

2009-11-01 Thread Robinson
I have also just started with both Aquamacs and Python so I ask for  
your patience as well.
When I evaluate the buffer (C-c C-C) I don't see any response or  
output from my python program. Should another buffer open  
automatically? Should a terminal window open?

thanks for your patience.
Rugbeia Floreat Ubique


On Mar 20, 3:09 pm, jmDesktop  wrote:
> Hi, I'm trying to learn Python.  I using Aquamac an emac
> implementation with mac os x.  I have a program.  If I go to the
> command prompt and type pythong myprog.py, it works.  Can the  
program
> be run from within the editor or is that not how development is  
done?

> I ask because I was using Visual Studio with C# and, if you're
> familiar, you just hit run and it works.  On Python do I use the
> editor for editing only and then run the program from the command
> line?  Thank you.

Aquamacs, just like any variant of GNU Emacs, will show a Python
menu.  There's a "Start Interpreter" function, and one to evaluate the
buffer (C-c C-c).  It's pretty straightforward (a euphemism for
obvious).

If the Python menu doesn't show, then something is going wrong. M-x
python-mode RET would switch it on.


--
http://aquamacs.org -- Aquamacs: Emacs on Mac OS X
http://aquamacs.org/donate -- Could we help you? Return the favor and
support the Aquamacs Project!








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


Re: How to import only one module in a package when the package __init__.py has already imports the modules?

2009-11-01 Thread Peng Yu
On Sat, Oct 31, 2009 at 11:43 PM, Steven D'Aprano
 wrote:
> On Sat, 31 Oct 2009 22:54:47 -0500, Peng Yu wrote:
>
>> So python would not be able to accommodate my preference one
>> class/function per file?
>
> Of course it does! You can do that RIGHT NOW -- just put one class per
> file.
>
>> I.e., I have to use something like 'from spam
>> import spam' or 'spam.spam()',
>
> How else do you expect to use the class if you don't import it?
>
>
>> or accept that the filename is not the
>> same as the class/function name.
>
> So let me see...
>
> You don't want to write "import spam; spam.spam()"
> You don't want to write "from spam import spam; spam()"
> You don't want to write "from Spam import spam; spam()"
> You don't want to write "from spam import Spam; Spam()"
>
> What exactly do you want?

When I define class spam in file spam.py, I want to call it by

import spam
spam()

If spam.py is in dir/, then I want to call it by

import dir.spam

dir.spam()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to import only one module in a package when the package __init__.py has already imports the modules?

2009-11-01 Thread Peng Yu
On Sat, Oct 31, 2009 at 11:34 PM, Steven D'Aprano
 wrote:
> On Sat, 31 Oct 2009 22:29:12 -0500, Peng Yu wrote:
>
 In my question, module A and B exist just for the sake of
 implementation. Even if I have module A and B, I don't want the user
 feel the existence of module A and B. I want them feel exact like
 class A and B are defined in module 'test' instead of feeling two
 modules A and B are in package 'test'.
>>>
>>>
>>> Inside test/__init__.py:
>>>
>>> from A import A  # class A from file A.py
>>> from B import B  # class B from file B.py
>>
>> I can not use the above approach as I mentioned its problem in my
>> previous message.
>
> Either I have not seen it, or I have not understood it, but I don't
> understand why you can not use this approach.

The problem is when you test a package you want to 'import test.A'
rather than 'import test'. Having such __init__.py does not allow you
to import only 'test.A'. This cause artificial dependence.

>>> or better still:
>>>
>>> from a import A  # class A from file a.py
>>> from b import B  # class B from file b.py
>>
>> This artificially introduces the constraint that the file name can not
>> be the same as the class/function name. There is no constraint like this
>> if I can C++.
>
> It is not a constraint, it is a convention. You are free to ignore it if
> you like.

I'm ignoring this convention now. But I have to call a function like
glob.glob, which I also feel inconvenient.

> Some people don't like writing "glob.glob" (for example). Some people
> would like to see Python ban modules with the same name as objects inside
> them, to avoid this error:
>
 import datetime
> ... much later
 from datetime import datetime
 datetime.datetime()
> Traceback (most recent call last):
>  File "", line 1, in 
> AttributeError: type object 'datetime.datetime' has no attribute
> 'datetime'
>
>
> You seem to be inconsistent -- you say you want to name the file the same
> as the function in it, so you know which file to look for a function, but
> then you complain about writing:
>
> test.A.A
>
> so when we suggest naming A.py a.py, so you can write:
>
> test.a.A
>
> you complain about that too. Frankly, I think you are just complaining
> because Python isn't C++.

I'm not complaining. I just wish there is a walkaround. In C++, I
still have to write some script to make sure the directory hierarchy
is consistent with the namespace, because C++ doesn't impose the
constraint that the directory hierarchy is the same as the namespace.
But it seems that is no such walkaround in python for my case, because
python binds namespace to directory hierarchy.

 I know that module names should be in lower cases, in general.
 However, it is OK to have the module name capitalized in this case
 since the end users don't see them.
>>>
>>> Of course they do.
>>
>> This sentence is confusing. Can you spell out what you mean?
>
> If you supply a package
>
> test/
> +--  __init__.py
> +--  A.py
> +--  B.py
>
>
> there is nothing stopping your users from doing this:
>
> import test.A as A
> import test.B as SomethingElse

First, this is a redudancy---'A' appears twice. Second, you can not do
something like the following, because name A from the two name space
is conflict.

import test.A as A
import test2.A as A


> [...]
>> I have defined 'long' in one of my previous message. I consider a file
>> long, when it does not fit in one or two screen. Basically, I want to
>> get a whole picture of the file after glancing of the file.
>
> You must only write incredibly trivial programs then.
>
> There is more to understanding a program than understanding one single
> function. Any serious function will call other functions. To get the
> whole picture, you have to understand them too. Your requirement simply
> shifts the burden from "open one file, and read ten functions" to "open
> ten files, and read ten functions".

I insist on having screen long functions or classes, because they have
less number of states compare with long ones. This allows me to test
all the states of them to make sure they are bug free. It is
reasonable to assume the log of the number of states of a function or
a class is proportional to it length. Hence, when a function or a
class is long, you will never be able to test all its states.

I don't have to put all related functions in a single file. With vim
and ctags, you should be able to jump to the definition of any
function or class from the place where it is used. So putting single
class/function in a file does not give me any extra 'burden' than if I
put them in the same file.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stdin in embedded python

2009-11-01 Thread Dave Angel

KillSwitch wrote:

I have a C++ program, with a GUI, into which I have embedded python. I
have made several python functions in C++, one of which I use to
override the normal stdout and stderr so that they print to a text box
of my GUI. One thing I cannot think of how to do is to redefine stdin
so that it pauses the program, waits for a user to type input into the
box, hit enter, and takes input from another text element and sends it
to python like it was the console.

I wonder if anyone could help me in trying to do such a thing. To
simplify, the new stdin should wait for the C++ function to give it a
value, like it waits for the console.

  
I suspect you don't really want to redirect stdin, but instead implement 
raw_input().  If you have control over the script, just change it from 
raw_input() to cpp_raw_input().  But if  you need to be able to run 
arbitrary scripts, ...


(untried) - Try changing __builtins__.raw_input  to reference your new 
function.


DaveA

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


Re: problem with read() write()

2009-11-01 Thread Steven D'Aprano
On Sun, 01 Nov 2009 10:44:45 +0100, Alf P. Steinbach wrote:

> Could you post (copy and paste) the code, and description of results?

Using Python 2.6 under Linux (Fedora 7):

>>> f = open('garbage', 'r')  # prove the file doesn't exist
Traceback (most recent call last):
  File "", line 1, in 
IOError: [Errno 2] No such file or directory: 'garbage'
>>> f = open('garbage', 'wb+')
>>> f.read(4)
''
>>> f.write('hello world\n')
>>> f.seek(0)
>>> f.read(100)
'hello world\n'


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


Re: problem with read() write()

2009-11-01 Thread Matt Nordhoff
Gertjan Klein wrote:
> Alf P. Steinbach wrote:
> 
>> So with 'w+' the only way to get garbage is if 'read' reads beyond the end 
>> of 
>> file, or 'open' doesn't conform to the documentation.
> 
> It does read beyond the end of file. This is perhaps the way the
> underlying C library works, but it looks like an "unexpected feature"
> (read: bug) to me.
> 
> I reproduced (with Python 2.5.2 on WinXP) the code the OP wrote after
> creating an empty (0-byte) test file; after the write() the read()
> returns random garbage. I can't imagine why anyone would want that
> behaviour. The file grew to be 4099 bytes after f.close(). I wrote
> 'hello' to it, so the length of garbage added was 4094 bytes, which I
> find a strange number also.
> 
> I would have expected the read to return nothing. Can anyone explain or
> even defend this behaviour?
> 
> Gertjan.

I wonder, does it still happen if you open the file in binary mode?
(Stick a "b" in the file mode.) It could be some Windows text mode
craziness.
-- 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with read() write()

2009-11-01 Thread Gertjan Klein
Alf P. Steinbach wrote:

>* Gertjan Klein:
>> I reproduced (with Python 2.5.2 on WinXP) the code the OP wrote after
>> creating an empty (0-byte) test file; after the write() the read()
>> returns random garbage. I can't imagine why anyone would want that
>> behaviour. The file grew to be 4099 bytes after f.close(). I wrote
>> 'hello' to it, so the length of garbage added was 4094 bytes, which I
>> find a strange number also.
>
>Could you post (copy and paste) the code, and description of results?

The code is exactly the OP's code, with an f.close() after f.read(). The
results are described above.

>"Shall not" means UB. This applies to C "FILE*" handling.

Yes. But Python is not C. I would have expected that Python shields me
from such bizarre results. The fact that, apparently, the Python file
object is a thin wrapper over a C library function is an explanation of
the behaviour, but not a justification.

>And for a language used by so many newbies (this is positive!) I agree that it 
>should ideally get rid of that UB (assuming that's what the problem is), or, 
>if 
>it doesn't already, mention that in the Python documentation.

I'm not sure I can defend this statement, but I think Python should not
have undefined behaviour at all.

Gertjan.

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


Re: python os.path.exists failure

2009-11-01 Thread Roel Schroeven
koranthala schreef:
> Hi all,
>My code is as follows:
> 
> path = r'C:/"Program Files"/testfolder/2.3/test.txt'
> if os.path.lexists(path):
> print 'Path Exists'
> else:
> print 'No file found in path - %s' %path
> print Popen(path, stdout=PIPE, shell=True).stdout.read()
> 
> The output comes as
> No file found in path - C:/"Program Files"/testfolder/2.3/test.txt
> but the test.txt file is opened.
> 
> The issue, I guess, is that the double quotes inside is failing the
> check. But without the double quotes, Popen fails.
> One solution, I can think is to check without double quotes, and then
> using some code, put the double quotes back inside, but it looks quite
> kludgy.

You can put the double quotes around the whole path instead of just
around "Program Files" in the call to Popen().

The issue here is actually that os.path.exists() (and all other Python
functions) use the path exactly like you pass it; but with your call to
Popen(), the path is passed as an argument to the shell, and it needs to
be quoted for the shell to interpret that correctly.

So here's what I would do: first specify the path literally without
quotes, and quote it only when needed:

path = r'C:/Program Files/testfolder/2.3/test.txt'
if os.path.lexists(path):
print 'Path Exists'
else:
print 'No file found in path - %s' %path
print Popen('"%s"' % path, stdout=PIPE, shell=True).stdout.read()

Some other notes:
- Since you use forward slashes, there's no need to use a raw string
literal.
- You can just as well use os.path.exists() instead of
os.path.lexists(). The difference has to do with symbolic links, which
Windows doesn't have.
- I'm not sure what you expect the line with Popen to do. On my system,
it opens the specified text file in notepad and returns an empty string.
If that's what you want to do, it's easier with os.startfile().

-- 
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
  -- Isaac Asimov

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


Re: problem with read() write()

2009-11-01 Thread Alf P. Steinbach

* Gertjan Klein:

Alf P. Steinbach wrote:

So with 'w+' the only way to get garbage is if 'read' reads beyond the end of 
file, or 'open' doesn't conform to the documentation.


It does read beyond the end of file. This is perhaps the way the
underlying C library works, but it looks like an "unexpected feature"
(read: bug) to me.

I reproduced (with Python 2.5.2 on WinXP) the code the OP wrote after
creating an empty (0-byte) test file; after the write() the read()
returns random garbage. I can't imagine why anyone would want that
behaviour. The file grew to be 4099 bytes after f.close(). I wrote
'hello' to it, so the length of garbage added was 4094 bytes, which I
find a strange number also.


Could you post (copy and paste) the code, and description of results?



I would have expected the read to return nothing. Can anyone explain or
even defend this behaviour?


I'm just a Python newbie, but in C and C++ such things are usually down to 
"undefined behavior", that is, the program doing something that is implicitly or 
explicitly defined as undefined behavior by the language standard.


With UB the effect may then be something or nothing or anything or just what you 
expected; appearance of the infamous nasal demons is one possibility...


Quoting n869, which is the January 18th 1999 draft of the C99 standard:

  §7.19.5.3/6
  When a file is opened with update mode (’+’ as the second or third
  character in the above list of mode argument values), both input and
  output may be performed on the associated stream. However, output shall
  not be directly followed by input without an intervening call to the
  fflush function or to a file positioning function (fseek, fsetpos, or
  rewind), and input shall not be directly followed by output without an
  intervening call to a file positioning function, unless the input
  operation encounters end-of-file. Opening( or creating) a text file with
  update mode may instead open (or create) a binary stream in some
  implementations.

"Shall not" means UB. This applies to C "FILE*" handling.

AFAICS nothing except efficiency prevents the Python wrapper, if "FILE*" is what 
it uses, from automatically inserting an appropriate fflush or fseek.


And for a language used by so many newbies (this is positive!) I agree that it 
should ideally get rid of that UB (assuming that's what the problem is), or, if 
it doesn't already, mention that in the Python documentation.



Cheers,

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


Re: problem with read() write()

2009-11-01 Thread Gertjan Klein
Alf P. Steinbach wrote:

>So with 'w+' the only way to get garbage is if 'read' reads beyond the end of 
>file, or 'open' doesn't conform to the documentation.

It does read beyond the end of file. This is perhaps the way the
underlying C library works, but it looks like an "unexpected feature"
(read: bug) to me.

I reproduced (with Python 2.5.2 on WinXP) the code the OP wrote after
creating an empty (0-byte) test file; after the write() the read()
returns random garbage. I can't imagine why anyone would want that
behaviour. The file grew to be 4099 bytes after f.close(). I wrote
'hello' to it, so the length of garbage added was 4094 bytes, which I
find a strange number also.

I would have expected the read to return nothing. Can anyone explain or
even defend this behaviour?

Gertjan.

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


Re: Sqlite3. Substitution of names in query.

2009-11-01 Thread Carsten Haese
Lawrence D'Oliveiro wrote:
>> On what grounds are you asserting that it's not necessary to mix the
>> two? Please elaborate your point.
> 
> On the grounds that Python has more general and powerful string parameter-
> substitution mechanisms than anything built into any database API.

That statement is fundamentally flawed. You are assuming that the
preferred way of getting a value into a query is by substituting a
literal into the query string. That is, in general, not true, because
that would be horribly inefficient. This is also why I despise the term
"parameter substitution", since it implies incorrectly that passing
parameters to a query is merely a string formatting exercise. The
correct term is "parameter binding."

Most databases actually provide an API for supplying parameters
separately from the query string. This is more efficient, because it
eliminates the need to render the parameter value into a literal form on
the client side and to parse the literal form on the server side. Also,
it allows the engine to perform the same query multiple times with
different values without having to re-parse the query.

Finally, you're assuming that every value that can be supplied to a
query actually HAS a literal form. That is not true. For example, in
Informix databases, there are no literals for BYTE-type values. (You'd
probably call them blobs.) So, if vomiting literals into the query
string were your only way of conveying values to the database, you'd
never be able to populate a BYTE column on an Informix database. The
only way to pass a BYTE value to an Informix database is by parameter
binding.

Since parameter binding is in general much more than string
substitution, it is indeed necessary to mix the two.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Pyfora, a place for python

2009-11-01 Thread Paul Rubin
Saketh  writes:
> I am proud to announce the release of Pyfora (http://pyfora.org), an
> online community of Python enthusiasts to supplement comp.lang.python
> and #python.

And the reason to want to further fragment Python discussion is
exactly what?
-- 
http://mail.python.org/mailman/listinfo/python-list


stdin in embedded python

2009-11-01 Thread KillSwitch
I have a C++ program, with a GUI, into which I have embedded python. I
have made several python functions in C++, one of which I use to
override the normal stdout and stderr so that they print to a text box
of my GUI. One thing I cannot think of how to do is to redefine stdin
so that it pauses the program, waits for a user to type input into the
box, hit enter, and takes input from another text element and sends it
to python like it was the console.

I wonder if anyone could help me in trying to do such a thing. To
simplify, the new stdin should wait for the C++ function to give it a
value, like it waits for the console.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __eq__() inconvenience when subclassing set

2009-11-01 Thread Gabriel Genellina
En Fri, 30 Oct 2009 17:55:27 -0300, Jess Austin   
escribió:



On Oct 29, 10:41 pm, "Gabriel Genellina" 
wrote:
We know the last test fails because the == logic fails to recognize  
mySet (on the right side) as a "more specialized" object than frozenset  
(on the left side), because set and frozenset don't have a common base  
type (although they share a lot of implementation)


I think the only way would require modifying tp_richcompare of  
set/frozenset objects, so it is aware of subclasses on the right side.  
Currently, frozenset() == mySet() effectively ignores the fact that  
mySet is a subclass of set.


I don't think even that would work.  By the time set_richcompare() is
called (incidentally, it's used for both set and frozenset), it's too
late.  That function is not responsible for calling the subclass's
method.  It does call PyAnySet_Check(), but only to short-circuit
equality and inequality for non-set objects.  I believe that something
higher-level in the interpreter decides to call the right-side type's
method because it's a subclass of the left-side type, but I'm not
familiar enough with the code to know where that happens.  It may be
best not to sully such generalized code with a special case for
this.

I may do some experiments with bytes, str, and unicode, since that
seems to be an analogous case.  There is a basestring type, but at
this point I don't know that it really helps with anything.


Looks like in 3.1 this can be done with bytes+str and viceversa, even if  
bytes and str don't have a common ancestor (other than object; basestring  
doesn't exist in 3.x):


p3> Base = bytes
p3> Other = str
p3>
p3> class Derived(Base):
...   def __eq__(self, other):
... print('Derived.__eq__')
... return True
...
p3> Derived()==Base()
Derived.__eq__
True
p3> Base()==Derived()
Derived.__eq__
True
p3> Derived()==Other()
Derived.__eq__
True
p3> Other()==Derived()
Derived.__eq__# !!!
True
p3> Base.mro()
[, ]
p3> Other.mro()
[, ]

The same example with set+frozenset (the one you're actually interested  
in) doesn't work, unfortunately.
After further analysis, this works for bytes and str because both types  
refuse to guess and compare to each other; they return NotImplemented when  
the right-side operand is not of the same type. And this gives that other  
operand the chance of being called.


set and frozenset, on the other hand, are promiscuous: their  
tp_richcompare slot happily accepts any set of any kind, derived or not,  
and compares their contents. I think it should be a bit more strict: if  
the right hand side is not of the same type, and its tp_richcompare slot  
is not the default one, it should return NotImplemented. This way the  
other type has a chance to be called.


--
Gabriel Genellina

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