Re: Markdown to reStructuredText

2011-02-10 Thread Michele Simionato
Looks cool, I will have a look at it, thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Easy function, please help.

2011-02-10 Thread Benjamin Kaplan
On Thu, Feb 10, 2011 at 12:03 AM, Jason Swails  wrote:
>
>
> On Wed, Feb 9, 2011 at 5:34 PM, MRAB  wrote:
>>
>> On 09/02/2011 21:42, Jason Swails wrote:
>>>
>>> You've gotten several good explanations, mainly saying that 0 -> False
>>> and not 0 -> True, which is why the while loop exits.  You've also
>>> gotten advice about how to make your method more robust (i.e. force
>>> integer division).
>>>
>>> However, as surprising as this may be I'm actually with RR on this one
>>> (for a little) -- for code readability's sake, you should make your
>>> conditional more readable (i.e. don't depend on the fact that the
>>> iterations will take your test value down to 0 which conveniently in
>>> this case evaluates to False).  This could encourage you in later cases
>>> to think that if this result eventually converged to a different number,
>>> say the multiplicative identity instead, that the same approach will
>>> work (when instead it'll dump you into an infinite loop).
>>>
>>> You've also gotten the suggestion of typecasting to a string and then
>>> looking at the number of characters in the string.  This works fine for
>>> integers and positive numbers, but not so well for negatives and floats,
>>> since both the decimal and negative sign will be counted.  You could
>>> typecast to a string then strip out '-' and '.' and then count the
>>> characters.  i.e.
>>>
>>> def num_digits(n):
>>>    return len(str(n).replace('-','').replace('.',''))
>>>
>> Or:
>>
>> def num_digits(n):
>>    return len(str(abs(n)).replace('.',''))
>>
>>> Or typecast to an int if you want to neglect decimals before converting
>>> to a string, etc.
>>>
>> [snip]
>> Python doesn't have typecasting. :-)
>
> Because these basic types are not mutable?   Most of my work has to
> be in Fortran, so I'm a relative newcomer to Python.  When I don't need
> Fortran-y performance it's much nicer (obviously to anyone that's used them
> both)!  Still don't know much deeper than Python's cosmetic surface at this
> point. 
>

Not exactly. It's because everything in Python is an object. What
you're doing isn't type casting. It's just calling an object
constructor- no different than any other class in the language.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reassign or discard Popen().stdout from a server process

2011-02-10 Thread John O'Hagan
On Wed, 9 Feb 2011, Nobody wrote:
> On Fri, 04 Feb 2011 15:48:55 +, John O'Hagan wrote:
> > But I'm still a little curious as to why even unsuccessfully attempting
> > to reassign stdout seems to stop the pipe buffer from filling up.
> 
> It doesn't. If the server continues to run, then it's ignoring/handling
> both SIGPIPE and the EPIPE error. Either that, or another process has the
> read end of the pipe open (so no SIGPIPE/EPIPE), and the server is using
> non-blocking I/O or select() so that it doesn't block writing its
> diagnostic messages.

The server fails with stdout=PIPE if I don't keep reading it, but doesn't fail 
if I do stdout=anything (I've tried files, strings, integers, and None) soon 
after starting the process, without any other changes. How is that consistent 
with either of the above conditions? I'm sure you're right, I just don't 
understand.

Regards,

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


Re: Algorithm for generating pitch-class sets in prime form

2011-02-10 Thread John O'Hagan
On Sat, 5 Feb 2011, Charles Turner wrote:
> Hi-
> 
> Do you knowof Christopher Ariza's AthenaCL?
> 
> 
> 
> HTH, Charles

Wow. That looks like a much more complete and elaborate version of what I'm 
doing, although from what I can tell I don't think it's real-time. I'll 
certainly be having a good poke around in the code. Thanks. 

Mind you, rather than using an algorithm like the one one I was looking for in 
the OP, AthenaCL uses a dictionary to hold the 12-based prime forms. I want to 
use arbitrary base-numbers ("temperaments" if applied to pitch), so I'd like 
to be able to generate the prime forms on the fly. 

Regards, 

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


Re: PDB how to define a global inspection function?

2011-02-10 Thread Charles Fox (Sheffield)



On Feb 8, 11:37 am, Peter Otten <__pete...@web.de> wrote:
> CharlesFox(Sheffield) wrote:
> > Hi guys, I'm new to this group and have a question about debugging.
> > I'm stepping through my code (using emacs pdbtrack and python-mode.el)
> > and would like to isnpect objects as I go.  So I've defined a little
> > object print function,
>
> > def p(obj):
> >     print obj
> >     print obj.__class__
> >     d=dir(obj)
> >     for a in d:
> >         print a, "=", getattr(obj, a)
>
> > however it only works if the function is imported by whatever module I
> > am currently debugging.  I'd like it to be available globally so I can
> > stop and inspect anything as I step through various modules (including
> > external libraries).  Is there a way to put it in the global scope for
> > pdb to use?   Also is there a way to automatically import it whenever
> > pdb starts up (like a matlab startup file)?     (I'm not using ipython
> > as it's not happy with pdbtrack in emacs, so am launching from emacs M-
> > x pdb command).
>
> For debugging purposes it's OK to put your function into the __builtin__
> namespace:
>
>
>
> >>> def p(): print 42
> ...
> >>> import __builtin__
> >>> __builtin__.p = p
>
> Try it out:
>
> >>> with open("tmp.py", "w") as f:
>
> ...     f.write("p()\n")
> ...>>> import tmp
>
> 42


Thanks very much for your help, Peter, that's exactly what I was
after :-)
Charles
-- 
http://mail.python.org/mailman/listinfo/python-list


Yappi error "context not found"

2011-02-10 Thread Brian
I'm posting here because I can't find a Yappi specific mailing list.

I've been using the rather brilliant Yappi from http://code.google.com/p/yappi/
It works well for small programs with a few threads. However, when
trying to run it over large programs with several hundred threads I've
been getting the error "context not found".

The most basic example I can come up with which illustrates the
problem is below. Changing the number of threads started from 25 down
to, say, 10, works fine. Any more than ~25 and the error keeps
appearing. This is using Python 2.6.5 and Ubuntu Linux 10.04. I don't
have another box to try this out on at the moment.

I've tested a similar script using thread.start_new_thread() and that
doesn't seem to have the problem. So is there some issue with Yappi
and inheriting from threading.Thread?

import yappi
import time
import threading

class MyThread(threading.Thread):
def run(self):
time.sleep(1)

yappi.start()

for i in range(0,25):
c = MyThread()
c.start()
time.sleep(1)

yappi.print_stats()
yappi.stop()


Running the above gives:
[*] [yappi-err] context not found.
[*] [yappi-err] context not found.
[*] [yappi-err] context not found.
[*] [yappi-err] context not found.
...

Any help appreciated.
-- 
http://mail.python.org/mailman/listinfo/python-list


Shared memory python between two separate shell-launched processes

2011-02-10 Thread Charles Fox (Sheffield)
Hi guys,
I'm working on debugging a large python simulation which begins by
preloading a huge cache of data.  I want to step through code on many
runs to do the debugging.   Problem is that it takes 20 seconds to
load the cache at each launch.  (Cache is a dict in a 200Mb cPickle
binary file).

So speed up the compile-test cycle I'm thinking about running a
completely separate process (not a fork, but a processed launched form
a different terminal) that can load the cache once then dunk it in an
area of shareed memory.Each time I debug the main program, it can
start up quickly and read from the shared memory instead of loading
the cache itself.

But when I look at posix_ipc and POSH it looks like you have to fork
the second process from the first one, rather than access the shared
memory though a key ID as in standard C unix shared memory.  Am I
missing something?   Are there any other ways to do this?

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


Re: Easy function, please help.

2011-02-10 Thread Jason Swails
On Thu, Feb 10, 2011 at 3:31 AM, Benjamin Kaplan
wrote:

>
> > On Wed, Feb 9, 2011 at 5:34 PM, MRAB  wrote:
>
> >>> Or typecast to an int if you want to neglect decimals before converting
> >>> to a string, etc.
> >>>
> >> [snip]
> >> Python doesn't have typecasting. :-)
> >
> > Because these basic types are not mutable?   Most of my work has
> to
> > be in Fortran, so I'm a relative newcomer to Python.  When I don't need
> > Fortran-y performance it's much nicer (obviously to anyone that's used
> them
> > both)!  Still don't know much deeper than Python's cosmetic surface at
> this
> > point. 
> >
>
> Not exactly. It's because everything in Python is an object. What
> you're doing isn't type casting. It's just calling an object
> constructor- no different than any other class in the language.
>

Ah, makes sense, thanks.  Most of what I see/work in is C and Fortran -- not
much OOP there :)

--Jason

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



-- 
Jason M. Swails
Quantum Theory Project,
University of Florida
Ph.D. Graduate Student
352-392-4032
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Shared memory python between two separate shell-launched processes

2011-02-10 Thread Jean-Paul Calderone
On Feb 10, 9:30 am, "Charles Fox (Sheffield)" 
wrote:
> Hi guys,
> I'm working on debugging a large python simulation which begins by
> preloading a huge cache of data.  I want to step through code on many
> runs to do the debugging.   Problem is that it takes 20 seconds to
> load the cache at each launch.  (Cache is a dict in a 200Mb cPickle
> binary file).
>
> So speed up the compile-test cycle I'm thinking about running a
> completely separate process (not a fork, but a processed launched form
> a different terminal)

Why _not_ fork?  Load up your data, then go into a loop forking and
loading/
running the rest of your code in the child.  This should be really
easy to
implement compared to doing something with shared memory, and solves
the
problem you're trying to solve of long startup time just as well.  It
also
protects you from possible bugs where the data gets corrupted by the
code
that operates on it, since there's only one copy shared amongst all
your
tests.  Is there some other benefit that the shared memory approach
gives
you?

Of course, adding unit tests that exercise your code on a smaller data
set
might also be a way to speed up development.

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


Re: Problem with giant font sizes in tkinter

2011-02-10 Thread Cousin Stanley
Steven D'Aprano wrote:

> I have a tkinter application under Python 2.6 which is shows text 
> in a giant font, about twenty(?) times larger than expected.
>
> The fonts are set using:
>
> titlefont = '-Adobe-Helvetica-Bold-R-Normal-*-180-*'
> buttonfont = '-Adobe-Helvetica-Bold-R-Normal-*-140-*'
> labelfont = '-Adobe-Helvetica-Bold-R-Normal-*-140-*'
> 

  Although I've been a linux user for several years,
  that type of font spec hurts my head  :-)

  Will the more simplistic type of tuple spec 
  not work in your tkinter application ?

  canv.create_text(
 81 , 27 ,
 text = ' NTSC Standard ' ,
 fill = 'white' ,
 font = ( 'Helvetica' , 12 , 'bold' ) )


-- 
Stanley C. Kitching
Human Being
Phoenix, Arizona

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


Re: email.encoders.encode_base64 creates one line only

2011-02-10 Thread spam



This is with python 3.1.2 (r312:79147). I have not tried with 2.7.

When I create an attachment with email.mime.image.MIMEImage, by default it
uses email.encoders.encode_base64 for the encoder, but that results in a
single line base64 string, instead of the recommended multiple 76-chars lines.

This works with most MTA and MUA, but some of them choke on it.



In case somebody runs into the same issue:
http://bugs.python.org/issue9298

And I added a work around if you need a solution before this bug is fixed at:
http://bugs.python.org/issue11156#msg128213

--
Yves.  http://www.SollerS.ca/
   http://blog.zioup.org/
--
http://mail.python.org/mailman/listinfo/python-list


Re: OO Python

2011-02-10 Thread Dan Stromberg
On Wed, Feb 9, 2011 at 1:50 PM, Paul Symonds  wrote:
> Are there any good resources to learn OO Python from?

Yes, plenty, but it's important for us to know so we can advise you:
Do you know any other OO languages yet?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Easy function, please help.

2011-02-10 Thread Ethan Furman

Jason Swails wrote:

On Wed, Feb 9, 2011 at 8:16 PM, Ethan Furman wrote:
while n:  is plenty readable.  n is either something or nothing, and
something evaluates to True, nothing to False.

Sure it's readable.  But then you have to make sure that the loop will 
eventually take n down to 0.  


Sure, but the same holds true with 'while n != 0' -- you have to make 
sure the loop will eventually take n down to 0.


You can always *assume* that the 
programmer knew what they were doing (not an assumption I'm typically 
willing to make on code that's not my own).


Hopefully not something you have to deal with unless you're debugging...

How is "while n != 0:" any worse?  (or abs(n) < tolerance).  It has 
exactly the same effect without adding any code while at the same time 
directly communicates the intended conditional.  IMO it makes reading 
the code easier to read barring effective documentation (my experience 
with people documenting their code is that they don't; at least in my 
field).  "while n != 0" makes my life easier.


In that instance (a bunch of mathematical functions), I can easily see 
using that construct.


The fact that the proposed loop finished with *nothing* was 
coincidental.  What if he had been doing some type of prime 
factorization or something where each iteration reduced the number until 
eventually all you were left with was the multiplicative identity?  
You'd say (correctly) that obviously the same approach won't work, but 
in some lines of thought it's a logical extension to use the same 
construct (especially to those that don't fully understand why the 
original loop exits in the first place).  Expanding the conditional a 
little can only help IMO.


Thank you for making my argument for me -- you have to understand the 
tool you are using to make the best use of it.



def num_digits(n):
  return len(str(n).replace('-','').replace('.',''))

Or typecast to an int if you want to neglect decimals before
converting to a string, etc.

Or use recursion!

 >>> def num_digits(n):
...if n == 0:
...   return 0
...else:
...   return num_digits(n//10) + 1
...
 >>> num_digits(1)
1
 >>> num_digits(0)
0


0 is still one digit.  ;)


Well that is something; yet only nothing evaluates to False.  We seem to 
be at an impasse :).


I fail to see how a faulty algorithm puts us at an impasse.  To tweak 
your code:


--> def num_digits(n, _first_pass=True):
--> if n == 0:
--> return int(_first_pass)
--> else:
--> return num_digits(n//10, _first_pass=False) + 1

correctly handles the special case of zero.  To use my style, it would 
look like:


--> def num_digits(n, _first_pass=True):
--> if n:
--> return num_digits(n//10, _first_pass=False) + 1
--> else:
--> return int(_first_pass)

And, of course, this only works for non-negative integers.  (I'll leave 
the discussion of whether zero is non-negative to others.  ;)  As I said 
earlier, I can see using the 'if n == 0' construct in certain 
situations, and if the non-zero branch were lengthy I would stick with 
the first version here.


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


Re: Problem with giant font sizes in tkinter

2011-02-10 Thread rantingrick
On Feb 10, 12:59 am, Steven D'Aprano  wrote:
> I have a tkinter application under Python 2.6 which is shows text in a
> giant font, about twenty(?) times larger than expected.
>
> The fonts are set using:
>
> titlefont = '-Adobe-Helvetica-Bold-R-Normal-*-180-*'
> buttonfont = '-Adobe-Helvetica-Bold-R-Normal-*-140-*'
> labelfont = '-Adobe-Helvetica-Bold-R-Normal-*-140-*'
>
> On one PC (Fedora), the text is displayed fine. Running xlsfonts gives me
> this:
>
> $ xlsfonts -fn '-Adobe-Helvetica-Bold-R-Normal-*-140-*'
> -adobe-helvetica-bold-r-normal--14-140-75-75-p-82-iso10646-1
> -adobe-helvetica-bold-r-normal--14-140-75-75-p-82-iso8859-1
> -adobe-helvetica-bold-r-normal--20-140-100-100-p-105-iso10646-1
> -adobe-helvetica-bold-r-normal--20-140-100-100-p-105-iso8859-1
>
> On a second PC (Ubuntu), the text is displayed in HUGE letters and I get
> this from xlsfonts:
>
> $ xlsfonts -fn '-Adobe-Helvetica-Bold-R-Normal-*-140-*'
> -adobe-helvetica-bold-r-normal--14-140-75-75-p-82-iso10646-1
> -adobe-helvetica-bold-r-normal--14-140-75-75-p-82-iso10646-1
> -adobe-helvetica-bold-r-normal--14-140-75-75-p-82-iso8859-1
> -adobe-helvetica-bold-r-normal--14-140-75-75-p-82-iso8859-1
> -adobe-helvetica-bold-r-normal--20-140-100-100-p-105-iso10646-1
> -adobe-helvetica-bold-r-normal--20-140-100-100-p-105-iso10646-1
> -adobe-helvetica-bold-r-normal--20-140-100-100-p-105-iso8859-1
> -adobe-helvetica-bold-r-normal--20-140-100-100-p-105-iso8859-1
>
> I don't know how to diagnose or fix the problem. What should I do to fix
> this problem?


First let me stop laughing... hold on... yea just a minute... a little
longer please... gawd i am enjoying this... ok i am ready... *pffftt*
ha ha ha ha ha ha ha!

I thought you hated Tkinter Steven? That is what you told this fine
group many times anyway. Also on many occasions you have said that you
have no use for GUI's, period. This is very interesting that know you
cannot even draw text to preferred size.

Oh, and about your problem. READ THE FREAKING MANUAL!


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


Re: Easy function, please help.

2011-02-10 Thread Terry Reedy

On 2/10/2011 11:52 AM, Ethan Furman wrote:

Jason Swails wrote:




How is "while n != 0:" any worse?


1. It is redundant, just like 'if bool_value is not False:'.
Python programmers should understand the null value idiom.

2. It does 2 comparisons, 1 unneeded, instead of 1. For CPython,
it adds 2 unnecessary bytecode instructions and takes longer.

>>> from dis import dis
>>> def f(n):
while n: pass


>>> dis(f)
  2   0 SETUP_LOOP  10 (to 13)
>>3 LOAD_FAST0 (n)
  6 POP_JUMP_IF_FALSE   12
  9 JUMP_ABSOLUTE3
>>   12 POP_BLOCK
>>   13 LOAD_CONST   0 (None)
 16 RETURN_VALUE
>>> def f(n):
while n != 0: pass


>>> dis(f)
  2   0 SETUP_LOOP  16 (to 19)
>>3 LOAD_FAST0 (n)
  6 LOAD_CONST   1 (0)
  9 COMPARE_OP   3 (!=)
 12 POP_JUMP_IF_FALSE   18
 15 JUMP_ABSOLUTE3
>>   18 POP_BLOCK
>>   19 LOAD_CONST   0 (None)
 22 RETURN_VALUE



It has exactly the same effect without adding any code


Untrue, see above.



--
Terry Jan Reedy

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


Re: Problem with giant font sizes in tkinter

2011-02-10 Thread uahmed
Hi ,

I am new one but ur talked make me laugh too :D , although here is relevant
link for you

" if Tk cannot come up with an exact match, it tries to find a similar font.
If that fails, Tk falls back to a platform-specific default font. Tk's idea
of what is "similar enough" probably doesn't correspond to your own view, so
you shouldn't rely too much on this feature."

http://www.pythonware.com/library/tkinter/introduction/x444-fonts.htm

Hope it helps you

On Thu, Feb 10, 2011 at 9:55 PM,  wrote:

> Send Python-list mailing list submissions to
>python-list@python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
>http://mail.python.org/mailman/listinfo/python-list
> or, via email, send a message with subject or body 'help' to
>python-list-requ...@python.org
>
> You can reach the person managing the list at
>python-list-ow...@python.org
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Python-list digest..."
>
> Today's Topics:
>
>   1. Yappi error "context not found" (Brian)
>   2. Re: Markdown to reStructuredText (Michele Simionato)
>   3. Shared memory python between two separate shell-launched
>  processes (Charles Fox (Sheffield))
>   4. Re: Easy function, please help. (Jason Swails)
>   5. Re: Shared memory python between two separate shell-launched
>  processes (Jean-Paul Calderone)
>   6. Re: Problem with giant font sizes in tkinter (Cousin Stanley)
>   7. Re: email.encoders.encode_base64 creates one line only
>  (s...@uce.gov)
>   8. Re: OO Python (Dan Stromberg)
>   9. Re: Easy function, please help. (Ethan Furman)
>  10. Re: Problem with giant font sizes in tkinter (rantingrick)
>
>
> -- Forwarded message --
> From: Brian 
> To: python-list@python.org
> Date: Thu, 10 Feb 2011 05:38:43 -0800 (PST)
> Subject: Yappi error "context not found"
> I'm posting here because I can't find a Yappi specific mailing list.
>
> I've been using the rather brilliant Yappi from
> http://code.google.com/p/yappi/
> It works well for small programs with a few threads. However, when
> trying to run it over large programs with several hundred threads I've
> been getting the error "context not found".
>
> The most basic example I can come up with which illustrates the
> problem is below. Changing the number of threads started from 25 down
> to, say, 10, works fine. Any more than ~25 and the error keeps
> appearing. This is using Python 2.6.5 and Ubuntu Linux 10.04. I don't
> have another box to try this out on at the moment.
>
> I've tested a similar script using thread.start_new_thread() and that
> doesn't seem to have the problem. So is there some issue with Yappi
> and inheriting from threading.Thread?
>
> import yappi
> import time
> import threading
>
> class MyThread(threading.Thread):
>def run(self):
>time.sleep(1)
>
> yappi.start()
>
> for i in range(0,25):
>c = MyThread()
>c.start()
> time.sleep(1)
>
> yappi.print_stats()
> yappi.stop()
>
>
> Running the above gives:
> [*] [yappi-err] context not found.
> [*] [yappi-err] context not found.
> [*] [yappi-err] context not found.
> [*] [yappi-err] context not found.
> ...
>
> Any help appreciated.
>
>
>
> -- Forwarded message --
> From: Michele Simionato 
> To: comp.lang.pyt...@googlegroups.com
> Date: Thu, 10 Feb 2011 00:03:19 -0800 (PST)
> Subject: Re: Markdown to reStructuredText
> Looks cool, I will have a look at it, thanks!
>
>
>
> -- Forwarded message --
> From: "Charles Fox (Sheffield)" 
> To: python-list@python.org
> Date: Thu, 10 Feb 2011 06:30:18 -0800 (PST)
> Subject: Shared memory python between two separate shell-launched processes
> Hi guys,
> I'm working on debugging a large python simulation which begins by
> preloading a huge cache of data.  I want to step through code on many
> runs to do the debugging.   Problem is that it takes 20 seconds to
> load the cache at each launch.  (Cache is a dict in a 200Mb cPickle
> binary file).
>
> So speed up the compile-test cycle I'm thinking about running a
> completely separate process (not a fork, but a processed launched form
> a different terminal) that can load the cache once then dunk it in an
> area of shareed memory.Each time I debug the main program, it can
> start up quickly and read from the shared memory instead of loading
> the cache itself.
>
> But when I look at posix_ipc and POSH it looks like you have to fork
> the second process from the first one, rather than access the shared
> memory though a key ID as in standard C unix shared memory.  Am I
> missing something?   Are there any other ways to do this?
>
> thanks,
> Charles
>
>
>
> -- Forwarded message --
> From: Jason Swails 
> To: Benjamin Kaplan 
> Date: Thu, 10 Feb 2011 09:50:18 -0500
> Subject: Re: Easy function, please help.
>
>
> On Thu, Feb 10, 2011 at 3:31 AM, Benjamin Kaplan  > wrote:
>
>>
>> > On Wed, Feb 9

Re: Shared memory python between two separate shell-launched processes

2011-02-10 Thread Charles Fox (Sheffield)
On Feb 10, 3:43 pm, Jean-Paul Calderone 
wrote:
> On Feb 10, 9:30 am, "Charles Fox (Sheffield)" 
> wrote:
>
> > Hi guys,
> > I'm working on debugging a large python simulation which begins by
> > preloading a huge cache of data.  I want to step through code on many
> > runs to do the debugging.   Problem is that it takes 20 seconds to
> > load the cache at each launch.  (Cache is a dict in a 200Mb cPickle
> > binary file).
>
> > So speed up the compile-test cycle I'm thinking about running a
> > completely separate process (not a fork, but a processed launched form
> > a different terminal)
>
> Why _not_ fork?  Load up your data, then go into a loop forking and
> loading/
> running the rest of your code in the child.  This should be really
> easy to
> implement compared to doing something with shared memory, and solves
> the
> problem you're trying to solve of long startup time just as well.  It
> also
> protects you from possible bugs where the data gets corrupted by the
> code
> that operates on it, since there's only one copy shared amongst all
> your
> tests.  Is there some other benefit that the shared memory approach
> gives
> you?
>
> Of course, adding unit tests that exercise your code on a smaller data
> set
> might also be a way to speed up development.
>
> Jean-Paul



Thanks Jean-Paul, I'll have a think about this.  I'm not sure if it
will get me exactly what I want though, as I would need to keep
unloading my development module and reloading it, all within the
forked process, and I don't see how my debugger (and emacs pdb
tracking) will keep up with that to let me step though the code.
(this debugging is more about integration issues than single
functions, I have a bunch of unit tests for the little bits but
something is unhappy when I put them all together...)

(I also had a reply by email, suggesting I use /dev/shm to store the
data instead of the hard disc; this speeds things up a little but not
much as the data still has to be transferred in bulk into my
process.   Unless I'm missing something and my process can just access
the data in that shm without having to load its own copy?)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OO Python

2011-02-10 Thread Paul Symonds

I have coded in VB using modules and functions but never coded a complete 
project in OO.  I understand the theory of OO, it's more the syntax and Python 
nuances that I need to be up to speed on.


On 10 Feb 2011, at 16:36, Dan Stromberg  wrote:

> On Wed, Feb 9, 2011 at 1:50 PM, Paul Symonds  wrote:
>> Are there any good resources to learn OO Python from?
> 
> Yes, plenty, but it's important for us to know so we can advise you:
> Do you know any other OO languages yet?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Shared memory python between two separate shell-launched processes

2011-02-10 Thread Jean-Paul Calderone
On Feb 10, 12:21 pm, "Charles Fox (Sheffield)" 
wrote:
> On Feb 10, 3:43 pm, Jean-Paul Calderone 
> wrote:
>
>
>
>
>
>
>
>
>
> > On Feb 10, 9:30 am, "Charles Fox (Sheffield)" 
> > wrote:
>
> > > Hi guys,
> > > I'm working on debugging a large python simulation which begins by
> > > preloading a huge cache of data.  I want to step through code on many
> > > runs to do the debugging.   Problem is that it takes 20 seconds to
> > > load the cache at each launch.  (Cache is a dict in a 200Mb cPickle
> > > binary file).
>
> > > So speed up the compile-test cycle I'm thinking about running a
> > > completely separate process (not a fork, but a processed launched form
> > > a different terminal)
>
> > Why _not_ fork?  Load up your data, then go into a loop forking and
> > loading/
> > running the rest of your code in the child.  This should be really
> > easy to
> > implement compared to doing something with shared memory, and solves
> > the
> > problem you're trying to solve of long startup time just as well.  It
> > also
> > protects you from possible bugs where the data gets corrupted by the
> > code
> > that operates on it, since there's only one copy shared amongst all
> > your
> > tests.  Is there some other benefit that the shared memory approach
> > gives
> > you?
>
> > Of course, adding unit tests that exercise your code on a smaller data
> > set
> > might also be a way to speed up development.
>
> > Jean-Paul
>
> Thanks Jean-Paul, I'll have a think about this.  I'm not sure if it
> will get me exactly what I want though, as I would need to keep
> unloading my development module and reloading it, all within the
> forked process, and I don't see how my debugger (and emacs pdb
> tracking) will keep up with that to let me step though the code.

Not really.  Don't load your code at all in the parent.  Then there's
nothing to unload in each child process, just some code to load for
the very first time ever (as far as that process is concerned).

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


Re: Problem with giant font sizes in tkinter

2011-02-10 Thread Jason Swails
On Thu, Feb 10, 2011 at 11:52 AM, rantingrick  wrote:

>
> Oh, and about your problem. READ THE FREAKING MANUAL!
>
>
Google Translation: i have no clue

-- 
Jason M. Swails
Quantum Theory Project,
University of Florida
Ph.D. Graduate Student
352-392-4032
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Easy function, please help.

2011-02-10 Thread rantingrick
On Feb 10, 11:01 am, Terry Reedy  wrote:
> On 2/10/2011 11:52 AM, Ethan Furman wrote:
>
> > Jason Swails wrote:
> >> How is "while n != 0:" any worse?
>
> 1. It is redundant, just like 'if bool_value is not False:'.
> Python programmers should understand the null value idiom.
>
> 2. It does 2 comparisons, 1 unneeded, instead of 1. For CPython,
> it adds 2 unnecessary bytecode instructions and takes longer.
>
>  >>> from dis import dis
>  >>> def f(n):
>         while n: pass
>
>  >>> dis(f)
>    2           0 SETUP_LOOP              10 (to 13)
>          >>    3 LOAD_FAST                0 (n)
>                6 POP_JUMP_IF_FALSE       12
>                9 JUMP_ABSOLUTE            3
>          >>   12 POP_BLOCK
>          >>   13 LOAD_CONST               0 (None)
>               16 RETURN_VALUE
>  >>> def f(n):
>         while n != 0: pass
>
>  >>> dis(f)
>    2           0 SETUP_LOOP              16 (to 19)
>          >>    3 LOAD_FAST                0 (n)
>                6 LOAD_CONST               1 (0)
>                9 COMPARE_OP               3 (!=)
>               12 POP_JUMP_IF_FALSE       18
>               15 JUMP_ABSOLUTE            3
>          >>   18 POP_BLOCK
>          >>   19 LOAD_CONST               0 (None)
>               22 RETURN_VALUE
>
> >> It has exactly the same effect without adding any code
>
> Untrue, see above.

Overblown. See below!

Terry i apologize for saying this but you offer a *really* weak
argument here. The load constant should only happen once. The
COMPARE_OP could be called "an extra step" but such a little problem
can easily be optimized away on the CPython side of things. It is
obvious that POP_JUMP_IF_FALSE is optimized for boolean comparisons.
And even if you throw out my fine solution...

1. When has 2 bytecode instructions EVER out weighed a solid
readability feature's incorporation into Python?

2. How many zillions of iterations would it take to notice even a
*microscopic* speed reduction?

Remember, Python IS "first and foremost" the language of readability.
Why do you think indention is enforced? Why do think the number of
built-in methods is kept small? Why do think magic methods are wrapped
in leading and trailing double underscores? Why do you think the
keyword set is simplistic and small? Why? Why? Why? i could go on all
day...  Terry, *we* are the shining jewel of coherency in a dark sea
polluted with multiplicity which is violently agitated by syntactical
asininity.
-- 
http://mail.python.org/mailman/listinfo/python-list


Ipython Ctypes conflict

2011-02-10 Thread Wanderer
When I try to use program that uses ctypes to load a dll in Ipython. I
get

Traceback (most recent call last):
File "... \console.py" line 671, in hook_wrapper_23
res = ensire_str(readline_hook(prompt))
File "...\rlmain.py", lin 342, in readline
return self.mode.readline(prompt)
File "...\emac.py", line 116, in readline
self._print_prompt()
File "...\rlmain.py, line 298, in _print_prompt
n = c.write_scrolling(self.prompt, self.prompt_color)
File "...\console.py", line 289, in write_scrolling
w, h = self.size()
TypeError: 'NoneType' object is not iterable
Readline internal error

Some hacking in console.py shows it is caused by

def size(self, width=None, height=None):
u'''Set/get window size.'''
info = CONSOLE_SCREEN_BUFFER_INFO()
status = self.GetConsoleScreenBufferInfo(self.hout,
byref(info))
if not status:
return None
if width is not None and height is not None:
wmin = info.srWindow.Right - info.srWindow.Left + 1
hmin = info.srWindow.Bottom - info.srWindow.Top + 1
#print wmin, hmin
width = max(width, wmin)
height = max(height, hmin)
#print width, height
self.SetConsoleScreenBufferSize(self.hout,
self.fixcoord(width,
height))
else:
return (info.dwSize.X, info.dwSize.Y)

After loading the dll, GetConsoleScreenBufferInfo always returns zero,
so size returns None and everybody is unhappy.

I don't get the problem in Idle or WinPython.

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


Re: Easy function, please help.

2011-02-10 Thread Jason Swails
On Thu, Feb 10, 2011 at 12:01 PM, Terry Reedy  wrote:

> On 2/10/2011 11:52 AM, Ethan Furman wrote:
>
>  Jason Swails wrote:
>>
>
>
>  How is "while n != 0:" any worse?
>>>
>>
> 1. It is redundant, just like 'if bool_value is not False:'.
> Python programmers should understand the null value idiom.
>
> 2. It does 2 comparisons, 1 unneeded, instead of 1. For CPython,
> it adds 2 unnecessary bytecode instructions and takes longer.
>

I see what you mean, and I think we're coming from different perspectives.
First I must say that the calculations I implement/use are VERY
computationally demanding and code optimization is of utmost importance, so
this point does not fall on deaf ears.  I agree that code optimization can
be very important.  However, the only things worth *optimizing*, really, is
the RDS.  Optimizing parts of the program that consume ~5% of the total
operation time to run ~20% faster is only ~ 0.1% increase in total
performance -- a sacrifice I'm more than willing to make for code
readability (as a general philosophy).

These programs are also very large, collaborative efforts that necessarily
have many people working on it, modifying it, etc.  It's this reason why I
say that sometimes code readability trumps performance.


>  It has exactly the same effect without adding any code
>>>
>>
> Untrue, see above.
>

What I meant was that the function result is unchanged without adding more
LOC; not that it was the same on the instruction level.

I think this is just a difference of perspective: mine is almost strictly
utilitarian, in that I just use languages/code/computers to solve my
problems.


All the best,
Jason


>
>
> --
> Terry Jan Reedy
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Jason M. Swails
Quantum Theory Project,
University of Florida
Ph.D. Graduate Student
352-392-4032
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: toy list processing problem: collect similar terms

2011-02-10 Thread WJ
Pascal J. Bourguignon wrote:

> Xah Lee  writes:
> 
> 
> > here's a interesting toy list processing problem.
> > 
> > I have a list of lists, where each sublist is labelled by
> > a number. I need to collect together the contents of all sublists
> > sharing
> > the same label. So if I have the list
> > 
> > ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4
> > q r) (5 s t))
> > 
> > where the first element of each sublist is the label, I need to
> > produce:
> > 
> > output:
> > ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
> > 
> > a Mathematica solution is here:
> > http://xahlee.org/UnixResource_dir/writ/notations_mma.html
> > 
> > R5RS Scheme lisp solution:
> > http://xahlee.org/UnixResource_dir/writ/Sourav_Mukherjee_sourav.work
> > _gmail.scm by Sourav Mukherjee
> > 
> > also, a Common Lisp solution can be found here:
> > http://groups.google.com/group/comp.lang.lisp/browse_frm/thread/5d1d
> > ed8824bc750b?
> 
> It's too complex. Just write:
> 
> (let ((list '((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) 
>   (2 o p) (4 q r) (5 s t
> 
>   (mapcar (lambda (class) (reduce (function append) class :key
> (function rest)))
> (com.informatimago.common-lisp.list:equivalence-classes list :key
> (function first)))
> 
>)
> 
> --> ((S T) (Q R M N) (G H) (O P K L E F) (I J C D) (A B))

Clojure:

(def groups '((0 a b)(1 c d)(2 e f)(3 g h)(1 i j)(2 k l)(4 m n)
(2 o p)(4 q r) (5 s t)))

Using group-by:

(map (fn[[k v]](flatten (map rest v))) (group-by first groups))

Using reduce:

(map #(flatten(rest %)) (reduce (fn[h [k & v]]
  (merge-with concat h {k v})) {} groups)) 

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


Re: Ipython Ctypes conflict

2011-02-10 Thread Robert Kern

On 2/10/11 1:57 PM, Wanderer wrote:

When I try to use program that uses ctypes to load a dll in Ipython.


The IPython mailing list is over here:

  http://mail.scipy.org/mailman/listinfo/ipython-dev

You can also report bugs here:

  https://github.com/ipython/ipython/issues

--
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: Programmatic Parsing of ps

2011-02-10 Thread bsergean
If you're on Linux you should

* Have a look at the /proc/ filesystem, there's probably what you want
there.

Here's a small script that print all the pid/cmd from the process ran
with your user.

#!/usr/local/bin/python

import os
import re
import stat
from os.path import join

for pid in (pid for pid in os.listdir('/proc') if re.match('\d',
pid)):
cmdline_fn = join('/proc', pid, 'cmdline')
cmdline = open(cmdline_fn).read()
uid = os.stat(cmdline_fn)[stat.ST_UID]

if os.getuid() == uid:
print pid, cmdline


For a more cross-platform solution there's a module that does that (I
forgot it's name but with some googling you might find it)




On Feb 9, 1:34 pm, Dan Stromberg  wrote:
> On Wed, Feb 9, 2011 at 11:15 AM, Emile van Sebille  wrote:
>
> > On 2/9/2011 10:58 AM octopusgrabbus said...
>
> >> I have Python 2.6.6. I would like to get this output
>
> >> ps -ef | grep 'fglgo csm'
>
> >> into a list. What is the best way to do that? I've been reading the
> >> documentation, and am lost.
>
> >> Thank you.
> >> cmn
>
> > commands.getoutput
>
> > Emile
>
> Also, consider using "ps -eo pid,comm" (or similar) instead of ps -ef
> - it should be easier to parse that way.

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


Re: Programmatic Parsing of ps

2011-02-10 Thread James Mills
On Thu, Feb 10, 2011 at 4:58 AM, octopusgrabbus
 wrote:
> I have Python 2.6.6. I would like to get this output
>
> ps -ef | grep 'fglgo csm'
>
> into a list. What is the best way to do that? I've been reading the
> documentation, and am lost.

Have you checked out psutil (1) to see if it
meets your needs ?

cheers
James

1. http://pypi.python.org/pypi/psutil/0.2.0

-- 
-- James Mills
--
-- "Problems are solved by method"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Programmatic Parsing of ps

2011-02-10 Thread Dan Stromberg
FWIW, Linux' /proc is very different from pretty much all other *ix's.
 I like Linux' design better, but it might be good to put the Linux
/proc assumption in one place, in case you need to port to another *ix
someday.

On Thu, Feb 10, 2011 at 4:26 PM, bsergean  wrote:
> If you're on Linux you should
>
> * Have a look at the /proc/ filesystem, there's probably what you want
> there.
>
> Here's a small script that print all the pid/cmd from the process ran
> with your user.
>
> #!/usr/local/bin/python
>
> import os
> import re
> import stat
> from os.path import join
>
> for pid in (pid for pid in os.listdir('/proc') if re.match('\d',
> pid)):
>    cmdline_fn = join('/proc', pid, 'cmdline')
>    cmdline = open(cmdline_fn).read()
>    uid = os.stat(cmdline_fn)[stat.ST_UID]
>
>    if os.getuid() == uid:
>        print pid, cmdline
>
>
> For a more cross-platform solution there's a module that does that (I
> forgot it's name but with some googling you might find it)
>
>
>
>
> On Feb 9, 1:34 pm, Dan Stromberg  wrote:
>> On Wed, Feb 9, 2011 at 11:15 AM, Emile van Sebille  wrote:
>>
>> > On 2/9/2011 10:58 AM octopusgrabbus said...
>>
>> >> I have Python 2.6.6. I would like to get this output
>>
>> >> ps -ef | grep 'fglgo csm'
>>
>> >> into a list. What is the best way to do that? I've been reading the
>> >> documentation, and am lost.
>>
>> >> Thank you.
>> >> cmn
>>
>> > commands.getoutput
>>
>> > Emile
>>
>> Also, consider using "ps -eo pid,comm" (or similar) instead of ps -ef
>> - it should be easier to parse that way.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with giant font sizes in tkinter

2011-02-10 Thread Steven D'Aprano
On Thu, 10 Feb 2011 15:48:47 +, Cousin Stanley wrote:

> Steven D'Aprano wrote:
> 
>> I have a tkinter application under Python 2.6 which is shows text in a
>> giant font, about twenty(?) times larger than expected.
>>
>> The fonts are set using:
>>
>> titlefont = '-Adobe-Helvetica-Bold-R-Normal-*-180-*' 
>> buttonfont = '-Adobe-Helvetica-Bold-R-Normal-*-140-*' 
>> labelfont = '-Adobe-Helvetica-Bold-R-Normal-*-140-*' 
>> 
> 
>   Although I've been a linux user for several years, that type of font
>   spec hurts my head  :-)
> 
>   Will the more simplistic type of tuple spec not work in your tkinter
>   application ?

I don't know, but I'll give it a try.

Nevertheless, I'd like to learn how to diagnose these sorts of font 
issues. Can anyone suggest where I should start?



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


Re: Easy function, please help.

2011-02-10 Thread Steven D'Aprano
On Thu, 10 Feb 2011 12:01:57 -0500, Terry Reedy wrote:

> On 2/10/2011 11:52 AM, Ethan Furman wrote:
>> Jason Swails wrote:
> 
> 
>>> How is "while n != 0:" any worse?
> 
> 1. It is redundant, just like 'if bool_value is not False:'. Python
> programmers should understand the null value idiom.

I find that if statement too implicit for my tastes. I prefer to be 
explicit about the values returned by comparisons, rather than just 
assume that the reader understands Python's comparisons. Unfortunately, I 
never know when to stop.

if bool_value is not False is True is True is True is True is ... 


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


Re: Problem with giant font sizes in tkinter

2011-02-10 Thread Paul Rubin
Steven D'Aprano  writes:
>>> labelfont = '-Adobe-Helvetica-Bold-R-Normal-*-140-*' 
>>> 
> Nevertheless, I'd like to learn how to diagnose these sorts of font 
> issues. Can anyone suggest where I should start?

Is the -140- a font size in points (1 point = 1/72 inch) or something
like that?  Try a smaller number.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OO Python

2011-02-10 Thread Rhodri James

[Re-ordered to get rid of the top-posting]

On Thu, 10 Feb 2011 17:11:16 -, Paul Symonds  
 wrote:

On 10 Feb 2011, at 16:36, Dan Stromberg  wrote:

On Wed, Feb 9, 2011 at 1:50 PM, Paul Symonds   
wrote:

Are there any good resources to learn OO Python from?


Yes, plenty, but it's important for us to know so we can advise you:
Do you know any other OO languages yet?


I have coded in VB using modules and functions but never coded a  
complete project in OO.  I understand the theory of OO, it's more the  
syntax and Python nuances that I need to be up to speed on.


On the whole, I'd forget about VB and start with the tutorial at
www.python.org.

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


Re: Problem with giant font sizes in tkinter

2011-02-10 Thread Steven D'Aprano
On Thu, 10 Feb 2011 18:35:09 -0800, Paul Rubin wrote:

> Steven D'Aprano  writes:
 labelfont = '-Adobe-Helvetica-Bold-R-Normal-*-140-*' 
>> Nevertheless, I'd like to learn how to diagnose these sorts of font
>> issues. Can anyone suggest where I should start?
> 
> Is the -140- a font size in points (1 point = 1/72 inch) or something
> like that?  Try a smaller number.

Thanks, but I already know how to make random changes to code until it 
works :) 

I want to understand what I'm doing and why. Why does the same piece of 
code work perfectly fine on one PC, and blow up to the size of a house on 
another? This surprises me, particularly since the not-working PC has the 
same fonts as the working one (plus extras).



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


Re: Problem with giant font sizes in tkinter

2011-02-10 Thread rantingrick
On Feb 10, 8:08 pm, Steven D'Aprano  wrote:
> On Thu, 10 Feb 2011 15:48:47 +, Cousin Stanley wrote:

> >   Will the more simplistic type of tuple spec not work in your tkinter
> >   application ?
>
> I don't know, but I'll give it a try.
>
> Nevertheless, I'd like to learn how to diagnose these sorts of font
> issues. Can anyone suggest where I should start?


I am *seriously* worried about comrade D'Aprano! Either his little
sister is using his account or he has completely lost his marbles!
Either way i am worried! SERIOUSLY!

Steven, are you seriously telling this group that with all your
knowledge of Python, CPython, C and many other languages you cannot
solve a simple "attack of the Tkinter giant font" bug? You cannot read
a tutorial or a manual to find the answer? You cannot use Google?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Easy function, please help.

2011-02-10 Thread alex23
rantingrick  wrote:
> 1. When has 2 bytecode instructions EVER out weighed a solid
> readability feature's incorporation into Python?

The original point was whether or not the code is identical, which
Terry showed it was not.

> The load constant should only happen once. The
> COMPARE_OP could be called "an extra step" but such a little problem
> can easily be optimized away on the CPython side of things.

Looking forward to seeing your patch.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with giant font sizes in tkinter

2011-02-10 Thread Westley Martínez
On Fri, 2011-02-11 at 03:13 +, Steven D'Aprano wrote:

> On Thu, 10 Feb 2011 18:35:09 -0800, Paul Rubin wrote:
> 
> > Steven D'Aprano  writes:
>  labelfont = '-Adobe-Helvetica-Bold-R-Normal-*-140-*' 
> >> Nevertheless, I'd like to learn how to diagnose these sorts of font
> >> issues. Can anyone suggest where I should start?
> > 
> > Is the -140- a font size in points (1 point = 1/72 inch) or something
> > like that?  Try a smaller number.
> 
> Thanks, but I already know how to make random changes to code until it 
> works :) 
> 
> I want to understand what I'm doing and why. Why does the same piece of 
> code work perfectly fine on one PC, and blow up to the size of a house on 
> another? This surprises me, particularly since the not-working PC has the 
> same fonts as the working one (plus extras).
> 
> 
> 
> -- 
> Steven

It could be DPI.
Anyways why would you want to set particular fonts anyways? Odd are
there's gonna be someone who doesn't have the font installed. Whenever
I've done tkinter programming, which isn't much, I've just stuck with
the default font.
-- 
http://mail.python.org/mailman/listinfo/python-list


How does IDLE do it?

2011-02-10 Thread Richard D. Moores
I recently wrote some code that prints information about the 'jukugo'
used in Japanese newspaper articles. A jukugo is a Japanese word
written with at least 2 kanji. An example of a 2-kanji jukugo is 危機
(kiki -- crisis). I found that I could not use my usual IDE to render
the Japanese correctly in either the code or the output. But IDLE
(version 3.1.2; Windows Vista) does a beautiful job! See screen shots

and
.
(The whole script plus output is at
.)

I'd like to know how the IDLE developers did this. How can IDLE not
have a problem with Japanese using Courier New, Calibri, even Fences
or Windings! (For Wingdings, see
.)

Thanks,

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


Re: returning all matching groups with re.search()

2011-02-10 Thread Roland Mueller

Hello,

On 02/07/2011 06:26 PM, Mauro Caceres wrote:

>>> import re
>>> help(re.findall)
Help on function findall in module re:

findall(pattern, string, flags=0)
Return a list of all non-overlapping matches in the string.
If one or more groups are present in the pattern, return a
list of groups; this will be a list of tuples if the pattern
has more than one group.
Empty matches are included in the result.

>>> re.findall('e','fredbarneybettywilma')
['e', 'e', 'e']


depending on what is intended the non-overlapping behaviour of findall() 
may cause some problem:


>>> re.findall('.[aeiou].','fredbarneybettywilma')
['red', 'bar', 'ney', 'bet', 'wil']

>>> re.findall('.[aeiouy].','fredbarneybettywilma')
['red', 'bar', 'ney', 'bet', 'tyw']

BR,
Roland


--
Mauro Cáceres


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


Re: Easy function, please help.

2011-02-10 Thread Westley Martínez
On Tue, 2011-02-08 at 21:52 -0800, Nanderson wrote:

> def num_digits(n):
> count = 0
> while n:
> count = count + 1
> n = n / 10
> return count
> 
> This is a function that basically says how many digits are in a
> number. For example,
> >>>print num_digits(44)
> 2
> >>>print num_digits(7654)
> 4
> 
> This function counts the number of decimal digits in a positive
> integer expressed in decimal format. I get this function ALMOST
> completely. The only thing I don't understand is why it eventually
> exits the loop, and goes off to the second branch. "while n" is
> confusing me. What I am thinking is that if someone puts "while n" the
> loop would be infinite. I get what is happening in the function, and I
> understand why this would work, but for some reason it's confusing me
> as to how it is exiting the loop after a certain number of times. Help
> is appreciated, thanks.

I've become a little annoyed by this thread. Here's a good function that
does what you want:
def num_digits(n):
"""Return number of digits in an iteger."""
count = 1
while n:
n = n // 10
count += 1
return count
-- 
http://mail.python.org/mailman/listinfo/python-list


Parameterized functions of no arguments?

2011-02-10 Thread Rotwang

Hi all

Sorry if this is a dumb question, I would guess it's answered in an FAQ 
somewhere but I haven't been able to find anything that helps. I'm 
trying to use Tkinter to create a menu whose entries and corresponding 
commands depend on some list x. I want the menu options to be labelled 
by the elements of x, and upon selecting an option k I want my program 
to execute a function f(k). So I tried writing something that 
schematically looked like this:


def f(k):
[do something that depends on k]

menu = Tkinter.Menu(master, tearoff = 0)
for k in x:
menu.add_command(label = str(k), command = lambda: f(k))

The trouble is, whenever I open the menu and click on any entry k, 
instead of evaluating f(k) it always evaluates f(x[-1]). I've also tried 
this:


menu = Tkinter.Menu(master, tearoff = 0)
for k in x:
def f():
[do something that depends on k]
menu.add_command(label = str(k), command = f)

and it gives me the same problem. Can anybody suggest a way around this?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parameterized functions of no arguments?

2011-02-10 Thread Rotwang

On 11/02/2011 04:54, Rotwang wrote:

Hi all

Sorry if this is a dumb question, I would guess it's answered in an FAQ
somewhere but I haven't been able to find anything that helps. I'm
trying to use Tkinter to create a menu whose entries and corresponding
commands depend on some list x. I want the menu options to be labelled
by the elements of x, and upon selecting an option k I want my program
to execute a function f(k). So I tried writing something that
schematically looked like this:

def f(k):
[do something that depends on k]

menu = Tkinter.Menu(master, tearoff = 0)
for k in x:
menu.add_command(label = str(k), command = lambda: f(k))

The trouble is, whenever I open the menu and click on any entry k,
instead of evaluating f(k) it always evaluates f(x[-1]). I've also tried
this:

menu = Tkinter.Menu(master, tearoff = 0)
for k in x:
def f():
[do something that depends on k]
menu.add_command(label = str(k), command = f)



Mmmmnngh, that obviously wasn't going to work. Here's something that 
does work:


menu = Tkinter.Menu(master, tearoff = 0)
for k in x:
def f(j = k):
[do something that depends on j]
menu.add_command(label = str(k), command = f)

Still, I'd like to know if there's a more elegant method for creating a 
set of functions indexed by an arbitrary list.

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


Re: Parameterized functions of no arguments?

2011-02-10 Thread Ben Finney
Rotwang  writes:

> Here's something that does work:
>
> menu = Tkinter.Menu(master, tearoff = 0)
> for k in x:
> def f(j = k):
> [do something that depends on j]
> menu.add_command(label = str(k), command = f)
>
> Still, I'd like to know if there's a more elegant method for creating
> a set of functions indexed by an arbitrary list.

That already seems quite elegant to me. What part is inelegant to your
eye?

-- 
 \ “I'm not a bad guy! I work hard, and I love my kids. So why |
  `\  should I spend half my Sunday hearing about how I'm going to |
_o__)Hell?” —Homer Simpson |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parameterized functions of no arguments?

2011-02-10 Thread Chris Rebert
On Thu, Feb 10, 2011 at 8:54 PM, Rotwang  wrote:
> Hi all
>
> Sorry if this is a dumb question, I would guess it's answered in an FAQ
> somewhere but I haven't been able to find anything that helps. I'm trying to
> use Tkinter to create a menu whose entries and corresponding commands depend
> on some list x. I want the menu options to be labelled by the elements of x,
> and upon selecting an option k I want my program to execute a function f(k).
> So I tried writing something that schematically looked like this:
>
>    def f(k):
>        [do something that depends on k]
>
>    menu = Tkinter.Menu(master, tearoff = 0)
>    for k in x:
>        menu.add_command(label = str(k), command = lambda: f(k))
>
> The trouble is, whenever I open the menu and click on any entry k, instead
> of evaluating f(k) it always evaluates f(x[-1]). I've also tried this:
>
>    menu = Tkinter.Menu(master, tearoff = 0)
>    for k in x:
>        def f():
>            [do something that depends on k]
>        menu.add_command(label = str(k), command = f)
>
> and it gives me the same problem. Can anybody suggest a way around this?

It's a well-known problem due to the intricacies of Python's scoping rules.
One workaround is:

for k in x:
def f(k=k):
[rest same as before]

Basically, the problem is that f() does close over the variable k, but
not the particular value of k at the time it was defined; f() looks up
the value of k anew each time it's called. But by the time you get
around to actually calling f(), the loop has terminated and thus k
retains its last value of x[-1]. Default argument values, however, are
evaluated only once and at definition-time, thus achieving the
intended behavior.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parameterized functions of no arguments?

2011-02-10 Thread Carl Banks
Rotwang wrote:
> On 11/02/2011 04:54, Rotwang wrote:
> Mmmmnngh, that obviously wasn't going to work. Here's something that 
> does work:
>
>  menu = Tkinter.Menu(master, tearoff = 0)
>  for k in x:
>  def f(j = k):
>  [do something that depends on j]
>  menu.add_command(label = str(k), command = f)
>
> Still, I'd like to know if there's a more elegant method for creating a 
> set of functions indexed by an arbitrary list.

If you don't want to use keyword arguments you can define a helper
function to help create your closure:

def create_menu_command(j):
def f():
do_something_that_depends_on(j)
return f

for k in x:
menu.add_command(label=str(k),command=create_menu_command(k))


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


Re: Parameterized functions of no arguments?

2011-02-10 Thread Paul Rubin
Rotwang  writes:
> menu = Tkinter.Menu(master, tearoff = 0)
> for k in x:
> def f(j = k):
> [do something that depends on j]
> menu.add_command(label = str(k), command = f)
>
> Still, I'd like to know if there's a more elegant method for creating
> a set of functions indexed by an arbitrary list.

That is a standard python idiom.  These days maybe I'd use partial
evaluation:

   from functools import partial

   def f(k):  whatever...

   for k in x:
  menu.add_command(label=str(k), command=partial(f, k))

the "pure" approach would be something like

   def f(k):  whatever...

   for k in x:
 menu.add_command(label=str(k),
  command=(lambda x: lambda: f(x))(k))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parameterized functions of no arguments?

2011-02-10 Thread Rotwang

On 11/02/2011 05:42, Ben Finney wrote:

Rotwang  writes:


Here's something that does work:

 menu = Tkinter.Menu(master, tearoff = 0)
 for k in x:
 def f(j = k):
 [do something that depends on j]
 menu.add_command(label = str(k), command = f)

Still, I'd like to know if there's a more elegant method for creating
a set of functions indexed by an arbitrary list.


That already seems quite elegant to me.


Thanks.



What part is inelegant to your eye?


I guess the fact that it exploits the way Python evaluates default 
function arguments to achieve something other than what they were 
intended for. Still, I see that Chris suggested the same solution 
(thanks, Chris) so it clearly isn't something that's frowned upon.

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


Re: Parameterized functions of no arguments?

2011-02-10 Thread Rotwang

On 11/02/2011 05:59, Carl Banks wrote:

Rotwang wrote:

On 11/02/2011 04:54, Rotwang wrote:
Mmmmnngh, that obviously wasn't going to work. Here's something that
does work:

  menu = Tkinter.Menu(master, tearoff = 0)
  for k in x:
  def f(j = k):
  [do something that depends on j]
  menu.add_command(label = str(k), command = f)

Still, I'd like to know if there's a more elegant method for creating a
set of functions indexed by an arbitrary list.


If you don't want to use keyword arguments you can define a helper
function to help create your closure:

def create_menu_command(j):
 def f():
 do_something_that_depends_on(j)
 return f

for k in x:
 menu.add_command(label=str(k),command=create_menu_command(k))


Nice, thanks.

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


Re: Parameterized functions of no arguments?

2011-02-10 Thread Rotwang

On 11/02/2011 06:19, Paul Rubin wrote:

Rotwang  writes:

 menu = Tkinter.Menu(master, tearoff = 0)
 for k in x:
 def f(j = k):
 [do something that depends on j]
 menu.add_command(label = str(k), command = f)

Still, I'd like to know if there's a more elegant method for creating
a set of functions indexed by an arbitrary list.


That is a standard python idiom.  These days maybe I'd use partial
evaluation:

from functools import partial

def f(k):  whatever...

for k in x:
   menu.add_command(label=str(k), command=partial(f, k))


functools is new to me, I will look into it. Thanks.



the "pure" approach would be something like

def f(k):  whatever...

for k in x:
  menu.add_command(label=str(k),
   command=(lambda x: lambda: f(x))(k))


I don't understand why this works. What is the difference between

(lambda x: lambda: f(x))(k)

and

lambda: f(k)

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


Re: Problem with giant font sizes in tkinter

2011-02-10 Thread Chris Jones
On Thu, Feb 10, 2011 at 09:08:01PM EST, Steven D'Aprano wrote:
> On Thu, 10 Feb 2011 15:48:47 +, Cousin Stanley wrote:
> 
> > Steven D'Aprano wrote:
> > 
> >> I have a tkinter application under Python 2.6 which is shows text in a
> >> giant font, about twenty(?) times larger than expected.
> >>
> >> The fonts are set using:
> >>
> >> titlefont = '-Adobe-Helvetica-Bold-R-Normal-*-180-*' 
> >> buttonfont = '-Adobe-Helvetica-Bold-R-Normal-*-140-*' 
> >> labelfont = '-Adobe-Helvetica-Bold-R-Normal-*-140-*' 
> >> 
> > 
> >   Although I've been a linux user for several years, that type of font
> >   spec hurts my head  :-)
> > 
> >   Will the more simplistic type of tuple spec not work in your tkinter
> >   application ?
> 
> I don't know, but I'll give it a try.
> 
> Nevertheless, I'd like to learn how to diagnose these sorts of font 
> issues. Can anyone suggest where I should start?

First of all, you need to know precisely what the above font name coding
means.

Chapter 6 of O'Reilly's ‘The X Window System's User Guide’, provides
a brief but fairly thorough introduction. 

In relation to your problem, see in particular the discussion of the use
of wild cards and such aspects as pixel size and vertical/horizontal
resolution. 

You can download a scanned pdf of this book free of charge here:

  http://www.archive.org/details/xwindowsytemosf03querarch

Have fun,

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


Re: Parameterized functions of no arguments?

2011-02-10 Thread Arnaud Delobelle
Rotwang  writes:

> On 11/02/2011 06:19, Paul Rubin wrote:
>> Rotwang  writes:
>>>  menu = Tkinter.Menu(master, tearoff = 0)
>>>  for k in x:
>>>  def f(j = k):
>>>  [do something that depends on j]
>>>  menu.add_command(label = str(k), command = f)
>>>
>>> Still, I'd like to know if there's a more elegant method for creating
>>> a set of functions indexed by an arbitrary list.
>>
>> That is a standard python idiom.  These days maybe I'd use partial
>> evaluation:
>>
>> from functools import partial
>>
>> def f(k):  whatever...
>>
>> for k in x:
>>menu.add_command(label=str(k), command=partial(f, k))
>
> functools is new to me, I will look into it. Thanks.
>
>
>> the "pure" approach would be something like
>>
>> def f(k):  whatever...
>>
>> for k in x:
>>   menu.add_command(label=str(k),
>>command=(lambda x: lambda: f(x))(k))
>
> I don't understand why this works. What is the difference between
>
> (lambda x: lambda: f(x))(k)
>

The value of k is bound to the local variable x; If k is changed later,
it doesn't affect the value of x above

Note that you can also write it:

lambda k=k: f(k)

> and
>
> lambda: f(k)
>
> ?

K not being local, If k is changed later, it does affect the above.

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