Re: initialization in argument definitions

2008-11-22 Thread Marc 'BlackJack' Rintsch
On Sun, 23 Nov 2008 13:13:11 +1300, greg wrote:

> George Sakkis wrote:
> 
>> Don't worry, it's not obvious to *anyone* new to Python (and many not-
>> so-new for that matter).
> 
> That's by no means certain, because we only hear from the people who
> guessed the wrong way. We have no way of knowing how many people guessed
> the right way.

Or how many worked through the tutorial, stumbled across the warning 
about that behavior and got that question answered before they have even 
known there's something to guess.

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


Re: build minimal python 2.6 on linux

2008-11-22 Thread Paul Rubin
r <[EMAIL PROTECTED]> writes:
> The files weigh in at 51MB and some change.
> Since transfer from USB on the laptop is painfully slow, and the cdrom
> is toast, i need to slim down the 2.6 source as much as possible, so
> it doesn't take 2 days to copy,

Even with USB 1.0, 51 mb should only take a minute or so to copy.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Feedback

2008-11-22 Thread Banibrata Dutta
2008/11/21 Ali art <[EMAIL PROTECTED]>

>  I am using Windows XP professional version 2002 Service pack 3. AMD
> Athlon(TM)XP 2400+ 2.00GHz 992MB RAM.
> I have download Windows x86 MSI Instaler (3.0rc2) Python 3.0rc2 Release:
> 06-Nov-2008.
>
> I want to use source code file from Python Command line but I could not.
>
> Firstly i opened IDLE and clicked on File → New Window and pasted
>  #!/usr/bin/python
> #Filename: helloworld.py
>
> print('Hello World')
> and saved  "helloworld.py" without quotes.Then i invoced pyton command
> line.
> Python 3.0rc2 (r30rc2:67141, Nov  7 2008, 11:43:46) [MSC v.1500 32 bit
> (Intel)]
> on win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> python helloworld.py
> and pressed enter
> But it did not work gives the error
>  Python 3.0rc2 (r30rc2:67141, Nov  7 2008, 11:43:46) [MSC v.1500 32 bit
> (Intel)]
> on win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> python helloworld.py
>   File "", line 1
> python helloworld.py
> ^
> SyntaxError: invalid syntax
> >>>
> Did i meke any misteke? I tried
> Control Panel -> System -> Advanced -> Environment Variables.
> System Variables -> C:\Python30
> but it still gives same error.
>

Since others have already pointed out what went wrong, here's a suggestion
from another newbie (self), to get you quickly up to speed with Python --

http://diveintopython.org/toc/index.html
and especially section 1.8. There are several great books out there, but I
found Dive-into-Python very easy to follow, allowing me to make very fast
progress, and getting me up to (a certain encouraging) speed, soon enough.
Happy hacking.

-- 
regards,
Banibrata
http://www.linkedin.com/in/bdutta
http://octapod.wordpress.com
--
http://mail.python.org/mailman/listinfo/python-list


build minimal python 2.6 on linux

2008-11-22 Thread r
I would like to install minimal version if python 2.6 on a linux laptop
(and no there is not one already installed...i checked)
i have no way to access the net with the laptop.
So basicly i down loaded the 2.6 source and unpacked it on my other
PC.
The files weigh in at 51MB and some change.
Since transfer from USB on the laptop is painfully slow, and the cdrom
is toast, i need to slim down the 2.6 source as much as possible, so
it doesn't take 2 days to copy, and besides i don't need all this crap
anyway.

I know right away i can lose:
-Demo
-Doc
-Mac
-IDLE
-PC...???
-PCbuild...???

What else can i dump to slim down to just python-Tkinter only
note: i DO want to keep all the built-in modules.

And i know this may be asking alot but:
where do i put the files before i run "./configure"
does it matter what directory there in??
any help here would be great since i am new to linux
and have never built a python installation.
Gracias amigos!



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


Re: initialization in argument definitions

2008-11-22 Thread Aaron Brady
On Nov 21, 3:25 pm, Brentt <[EMAIL PROTECTED]> wrote:
> Hi, I know this is a terribly simple question, but the docs seem to be
> designed for people who probably find a the answer to this question
> terribly obvious. But its not at all obvious to me.
>
> I can't figure out why when I define a function, a variable
> (specifically a list) that I define and initialize in the argument
> definitions, will not initialize itself every time its called.
snip
> Why is this? Thanks, hope its not a stupid quesiton.

That is not what the equals sign means in a 'def' statement in Python.

No, not a stupid question.
--
http://mail.python.org/mailman/listinfo/python-list


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

2008-11-22 Thread Aaron Brady
On Nov 22, 8:40 am, Joe Strout <[EMAIL PROTECTED]> wrote:
> On Nov 22, 2008, at 4:08 AM, Aaron Brady wrote:
>
> > Furthermore, to apply c-b-v to Python, you have to
> > introduce the concept of pointers, which is ostensibly non-native for
> > human programmers.
>
> Not necessarily "pointers" per se -- any type of object references  
> will do, and yes, Python has those in spades.

Humans don't.  That's my point.

> >  You'd have a pretty hard time making the case that c-b-v is 'round  
> > peg, round hole' for Python.
>
> I didn't find it all that hard:  >  Just describe it and give it a name.
>
> OK: "Python variables contain object references, which are copied from  
> the actual parameter expression to the formal parameter.  This  
> evaluation strategy is named 'call-by-value,' though some authors use  
> the term 'call-by-sharing' to indicate the specific case of call-by-
> value where the values passed are object references."

Better: Objects are passed to functions without copying, and
assignment assigns a new identity to the variable, without changing
the old object.  Round peg, round hole.

The only purpose it serves to keep bringing up reference this and
reference that, is so you can 'square peg, round hole' the term 'call-
by-value'.

> (I should add that last bit to my web page -- I'll try to do that this  
> weekend.)

What you should do, is add mine to the 'short answer' section, and
yours to the 'long answer' section.  Diversify your portfolio.

> P.S. I've pretty well tired of this thread, but I can't let Greg stand  
> up for truth and clarity all by himself...

Truth and clarity are not tired of this thread.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3 __cmp__ semantic change?

2008-11-22 Thread Steven D'Aprano
On Sat, 22 Nov 2008 09:10:04 +, Arnaud Delobelle wrote:

> That's not surprising.  You're measuring the wrong things.  If you read
> what I wrote, you'll see that I'm talking about Fraction.__gt__ being
> slower (as it is defined in terms of Fraction.__eq__ and
> Fraction.__lt__) using when my 'totally_ordered' decorator.
> 
> I haven't done any tests but as Fraction.__gt__ calls *both*
> Fraction.__eq__ and Fraction.__lt__ it is obvious that it is going to be
> roughly twice as slow.


What's obvious to you and what's obvious to the Python VM are not 
necessarily the same thing. I believe you are worrying about the wrong 
thing. (BTW, I think your earlier decorator had a bug, in that it failed 
to define __ne__ but then called "self != other".) My tests suggest that 
relying on __cmp__ is nearly three times *slower* than your decorated 
class, and around four times slower than defining all the rich 
comparisons directly:

$ python comparisons.py
Testing FractionCmp... 37.4376080036
Testing FractionRichCmpDirect... 9.83379387856
Testing FractionRichCmpIndirect... 16.152534008
Testing FractionDecoratored... 13.2626030445

Test code follows. If I've made an error, please let me know.


[comparisons.py]
from __future__ import division

def totally_ordered(cls):
# Define total ordering in terms of __eq__ and __lt__ only.
if not hasattr(cls, '__ne__'):
def ne(self, other):
return not self == other
cls.__ne__ = ne
if not hasattr(cls, '__gt__'):
def gt(self, other):
return not (self < other or self == other)
cls.__gt__ = gt
if not hasattr(cls, '__ge__'):
def ge(self, other):
return not (self < other)
cls.__ge__ = ge
if not hasattr(cls, '__le__'):
def le(self, other):
return (self < other or self == other)
cls.__le__ = le
return cls


class AbstractFraction:
def __init__(self, num, den=1):
if self.__class__ is AbstractFraction:
raise TypeError("abstract base class, do not instantiate")
assert den > 0, "denomintator must be > 0"
self.num = num
self.den = den
def __float__(self):
return self.num/self.den

class FractionCmp(AbstractFraction):
def __cmp__(self, other):
return cmp(self.num*other.den, self.den*other.num)

class FractionRichCmpDirect(AbstractFraction):
def __eq__(self, other):
return (self.num*other.den) == (self.den*other.num)
def __ne__(self, other):
return (self.num*other.den) != (self.den*other.num)
def __lt__(self, other):
return (self.num*other.den) < (self.den*other.num)
def __le__(self, other):
return (self.num*other.den) <= (self.den*other.num)
def __gt__(self, other):
return (self.num*other.den) > (self.den*other.num)
def __ge__(self, other):
return (self.num*other.den) >= (self.den*other.num)

class FractionRichCmpIndirect(AbstractFraction):
def __cmp__(self, other):
return cmp(self.num*other.den, self.den*other.num)
def __eq__(self, other):
return self.__cmp__(other) == 0
def __ne__(self, other):
return self.__cmp__(other) != 0
def __lt__(self, other):
return self.__cmp__(other) < 0
def __le__(self, other):
return self.__cmp__(other) <= 0
def __gt__(self, other):
return self.__cmp__(other) > 0
def __ge__(self, other):
return self.__cmp__(other) >= 0


class FractionDecoratored(AbstractFraction):
def __eq__(self, other):
return self.num*other.den == self.den*other.num
def __lt__(self, other):
return self.num*other.den < self.den*other.num

FractionDecoratored = totally_ordered(FractionDecoratored)

def test_suite(small, big):
assert small < big
assert small <= big
assert not (small > big)
assert not (small >= big)
assert small != big
assert not (small == big)

from timeit import Timer

test = 'test_suite(p, q)'
setup = '''from __main__ import %s as frac
from __main__ import test_suite
p = frac(1, 2)
q = frac(4, 5)
assert float(p) < float(q)'''

for cls in [FractionCmp, FractionRichCmpDirect, FractionRichCmpIndirect, 
FractionDecoratored]:
t = Timer(test, setup % cls.__name__)
print "Testing %s..." % cls.__name__, 
best = min(t.repeat())
print best
[end comparisons.py]



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


Re: initialization in argument definitions

2008-11-22 Thread greg

George Sakkis wrote:


Don't worry, it's not obvious to *anyone* new to Python (and many not-
so-new for that matter).


That's by no means certain, because we only hear from the
people who guessed the wrong way. We have no way of knowing
how many people guessed the right way.

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


Re: Re: how to get all repeated group with regular expression

2008-11-22 Thread Jeremiah Dodds
On Fri, Nov 21, 2008 at 9:12 PM, scsoce <[EMAIL PROTECTED]> wrote:

> MRAB wrote:
>
>> Steve Holden
>> wrote:
>>
>>> Please keep this on the list.
>>>
>>> scsoce wrote:
>>>
 Steve Holden wrote:

> scsoce wrote:
>
>
>> say, when I try to search and match every char  from variable length
>> string, such as string '123456',  i tried re.findall( r'(\d)*, '12346'
>> )
>>
>>
> I think you will find you missed a quote out there. Always better to
> copy and paste ...
>
>
>
>> , but only get '6' and Python doc indeed say: "If a group is contained
>> in a part of the pattern that matched multiple times, the last match
>> is
>> returned."
>>
>>
> So use
>
>r'(\d*)'
>
> instead and then the group includes all the digits you match.
>
>
>
>> cause the regx engine cannot remember all the past history then ?  is
>> it
>> nature to all regx engine or only to Python ?
>>
>>
> Different regex engines have different capabilities, so I can't speak
> to
> them all. If you wanted *all* the matches of *all* groups, how would
> you
> have them returned? As a list? That would make the case where there was
> only one match  much tricker to handle. And what would you do with
>
>  r'((\w)*\d)*)'
>
> Also, what about named groups? I can see enough potential
> implementation
> issues that I can perfectly understand why Python works the way it
> does,
> so I'd be interested to know why it doesn't makes sense to you, and
> what
> you would prefer it to do.
>
> regards
>  Steve
>
>
 maybe my expression was not clear. I  want to capture every matched part
 in a repeated pattern, not only the last,  say, for string '123456',  I
 want to back reference any one char, not only the '6'. and i know the
 example is very simple, so we can got the whole string using regx and
 get every char using other python statements, but if the pattern in
 group is complex?
 and I test in VIM, it can do the 'back reference':
 ==you text in vim:
 123456
 == pattern:
 :%s/\(\d\)*/$2
 text will turn to be:
 2

  'Fraid the Python re implementers just decided not to do it that way.
>>>
>>>  Nor Perl.
>>
>> Probably what you want is re.findall(r"(\d)", "123456"), which returns a
>> list of what it captured.
>>
>>
>> 
>>
> Yes, you are right, but this way findall() capture only the 'top' group.
> What I really need to do is to capture nested and repated patterns, say,
>  tag in html contains many ,contains many ,   the
>  data in   is i need, so I write the regx like this:
>   regx ='''
>   (
>  (\s*   (\s*\n|\n)*
>   \s*\n
>  |\n)*
>  )
>  \s*
>   '''
> Steve Holden wrote:
>
>> I can see enough potential implementation
>> issues that I can perfectly understand why Python works the way it does,
>> so I'd be interested to know why it doesn't makes sense to you, and what
>> you would prefer it to do.
>>
>>
>
> As Steve said, if re really cannot do this kind of work , so I have to
> split the one line regx down, and  capture  first, and then loop to
> catpure , and then , and so on ... . I donnot like this way compared
> with the above one clean regx line.
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

If you're parsing structured markup like HTML, why not use something meant
for that? I personally find BeautifulSoup (
http://www.crummy.com/software/BeautifulSoup/) to be very good at this. For
instance, here's a code snippet I recently used to pull out specific data
from a table in a site:

soup = BeautifulSoup(some_page)
opts = [fonttag.string.strip()
   for row in soup('tr', attrs={'class':'targetClass'})
   for cell in row('td')
   for fonttag in cell('font')
   if cell('font')]
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to dynamically instantiate an object inheriting from several classes?

2008-11-22 Thread George Sakkis
On Nov 22, 9:32 am, Joe Strout <[EMAIL PROTECTED]> wrote:
> On Nov 21, 2008, at 7:02 PM, Steven D'Aprano wrote:
>
> >> I have a function that takes a reference to a class,
>
> > Hmmm... how do you do that from Python code? The simplest way I can  
> > think
> > of is to extract the name of the class, and then pass the name as a
> > reference to the class, and hope it hasn't been renamed in the  
> > meantime...
>
> Please quit trying to confuse the kids at home.  Classes in Python are  
> first-class objects, and any time you refer to a class or any other  
> object in Python, what you have is a reference to it.

..which makes the phrase "a reference to an X" a more verbose,
redundant version of "an X" since it applies to *every* Python object.
You have made your point in the 300+ posts thread, so please quit the
terminology trolling in every new thread.

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


Re: Feedback

2008-11-22 Thread Benjamin Kaplan
Idle is not a command line shell, it is the python interactive interpreter.
If you want to run your program in a command line, open a real command line
(cmd.exe) and cd to whatever directory you put helloworld.py in. Then type
"python helloworld.py".

2008/11/21 Ali art <[EMAIL PROTECTED]>

>  I am using Windows XP professional version 2002 Service pack 3. AMD
> Athlon(TM)XP 2400+ 2.00GHz 992MB RAM.
> I have download Windows x86 MSI Instaler (3.0rc2) Python 3.0rc2 Release:
> 06-Nov-2008.
>
> I want to use source code file from Python Command line but I could not.
>
> Firstly i opened IDLE and clicked on File → New Window and pasted
>  #!/usr/bin/python
> #Filename: helloworld.py
>
> print('Hello World')
> and saved  "helloworld.py" without quotes.Then i invoced pyton command
> line.
> Python 3.0rc2 (r30rc2:67141, Nov  7 2008, 11:43:46) [MSC v.1500 32 bit
> (Intel)]
> on win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> python helloworld.py
> and pressed enter
> But it did not work gives the error
>  Python 3.0rc2 (r30rc2:67141, Nov  7 2008, 11:43:46) [MSC v.1500 32 bit
> (Intel)]
> on win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> python helloworld.py
>   File "", line 1
> python helloworld.py
> ^
> SyntaxError: invalid syntax
> >>>
> Did i meke any misteke? I tried
> Control Panel -> System -> Advanced -> Environment Variables.
> System Variables -> C:\Python30
> but it still gives same error.
>
> --
> Discover the new Windows Vista Learn 
> more!
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Feedback

2008-11-22 Thread MRAB

Ali art wrote:
I am using Windows XP professional version 2002 Service pack 3. AMD 
Athlon(TM)XP 2400+ 2.00GHz 992MB RAM.
I have download Windows x86 MSI Instaler (3.0rc2) Python 3.0rc2 Release: 
06-Nov-2008.


I want to use source code file from Python Command line but I could not.
 
Firstly i opened IDLE and clicked on File → New Window and pasted 
 #!/usr/bin/python

#Filename: helloworld.py
 
print('Hello World')

and saved  "helloworld.py" without quotes.Then i invoced pyton command line.
Python 3.0rc2 (r30rc2:67141, Nov  7 2008, 11:43:46) [MSC v.1500 32 bit 
(Intel)]

on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> python helloworld.py
and pressed enter
But it did not work gives the error


That would work only in a Command Prompt window.

 Python 3.0rc2 (r30rc2:67141, Nov  7 2008, 11:43:46) [MSC v.1500 32 bit 
(Intel)]

on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> python helloworld.py
  File "", line 1
python helloworld.py
^
SyntaxError: invalid syntax
 >>>
Did i meke any misteke? I tried
Control Panel -> System -> Advanced -> Environment Variables.
System Variables -> C:\Python30
but it still gives same error.


You can open it in IDLE and run it with Run → Run Module or press F5.

Alternatively you can double-click on the file in Windows Explorer, 
although the window would close as soon as the program had finished.

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


CHASE CREDIT CARDS

2008-11-22 Thread LUDLAM
Compare and choose the best Chase credit card for your needs
http://chasecreditcardsnews.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python / Debian package dependencies

2008-11-22 Thread Paul Boddie
On 21 Nov, 23:09, Steven Samuel Cole <[EMAIL PROTECTED]>
wrote:
>
> 1. I must use a 'higher-level' tool than dpkg to install the package
> which automatically resolves and installs dependency packages. There has
>   got to be a way to use apt-get for .deb files which do not reside
> (yet) in a repository.

I more or less skipped the part about installation, but had the
dependencies been included correctly in the package description and
had they not been available, dpkg would have complained. You can use
apt-get with local repositories, although the magic required for
initialising them isn't too obvious. That said, if it's like the
package building scene, I'm sure various tools exist for initialising
repositories; I use a very short shell script to run the programs that
update the repository records.

> 2. stdeb does not seem to 'transform' dependencies specified in setup.py
> into dependencies in its output files. There seems to be a mailing list
> for stedb athttp://mail.python.org/mailman/listinfo/distutils-sig. I'll
> try there.

Good luck! One of the issues with such transformations is that they
cannot generally be done trivially, but perhaps some kind of mapping
between "upstream" source packages and Debian packages would alleviate
such difficulties.

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


And now for something completely different ...

2008-11-22 Thread Christian Heimes
To whom it might concern. Monty Python has opened an official Monty 
Python channel on Youtube. http://www.youtube.com/user/MontyPython


High quality Monty Python movies - powered by Python :)

Have fun!
Christian

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


Feedback

2008-11-22 Thread Ali art

I am using Windows XP professional version 2002 Service pack 3. AMD 
Athlon(TM)XP 2400+ 2.00GHz 992MB RAM.I have download Windows x86 MSI Instaler 
(3.0rc2) Python 3.0rc2 Release: 06-Nov-2008. 
I want to use source code file from Python Command line but I could not.
 
Firstly i opened IDLE and clicked on File → New Window and pasted  
#!/usr/bin/python #Filename: helloworld.py print('Hello World')
and saved  "helloworld.py" without quotes.Then i invoced pyton command line.
Python 3.0rc2 (r30rc2:67141, Nov  7 2008, 11:43:46) [MSC v.1500 32 bit 
(Intel)]on win32Type "help", "copyright", "credits" or "license" for more 
information.>>> python helloworld.py 
and pressed enterBut it did not work gives the error
 Python 3.0rc2 (r30rc2:67141, Nov  7 2008, 11:43:46) [MSC v.1500 32 bit 
(Intel)]on win32Type "help", "copyright", "credits" or "license" for more 
information.>>> python helloworld.py  File "", line 1python 
helloworld.py^SyntaxError: invalid syntax>>>
Did i meke any misteke? I tried Control Panel -> System -> Advanced -> 
Environment Variables. System Variables -> C:\Python30
but it still gives same error.
_
Discover the new Windows Vista
http://search.msn.com/results.aspx?q=windows+vista&mkt=en-US&form=QBRE--
http://mail.python.org/mailman/listinfo/python-list


Re: how to dynamically instantiate an object inheriting from several classes?

2008-11-22 Thread Steven D'Aprano
On Sat, 22 Nov 2008 07:32:07 -0700, Joe Strout wrote:

> On Nov 21, 2008, at 7:02 PM, Steven D'Aprano wrote:
> 
>>> I have a function that takes a reference to a class,
>>
>> Hmmm... how do you do that from Python code? The simplest way I can
>> think
>> of is to extract the name of the class, and then pass the name as a
>> reference to the class, and hope it hasn't been renamed in the
>> meantime...
> 
> Please quit trying to confuse the kids at home. Classes in Python are
> first-class objects, and any time you refer to a class or any other
> object in Python, what you have is a reference to it.


No, at the level of Python code, what you have is the object itself.

What any specific implementation of the Python virtual machine almost 
certainly will have are references, or pointers, or some other 
implementation-specific form of indirection that eventually leads to the 
object. But at the level of Python code, they are invisible. There are no 
references at the level of Python code.

The burden of proof lies on you to prove that "reference to a class" has 
any meaning at the level of Python code. First you need to define what a 
reference is, in terms of *Python* entities (not implementation details), 
how it differs from the object itself, and how you can tell "a reference 
to a class" apart from the class itself, *at the level of Python code*.

I don't think you can do it, not without conflating implementation-level 
details with Python-level details. In Python code, you have objects, and 
that is all. Talking about "a reference to a class" instead of "a class" 
is simply obscurantism.



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


Re: Custom Formatting The Output Of subprocess.Popen

2008-11-22 Thread thedsadude
> regards
>  Steve
> --
> Steve Holden        +1 571 484 6266   +1 800 494 3119
> Holden Web LLC              http://www.holdenweb.com/


  Thanks all for your help! Bye, TD
--
http://mail.python.org/mailman/listinfo/python-list


Re: Module not included when running "setup.py sdist"

2008-11-22 Thread Martin v. Löwis
> I did not see "wyzard.py" anywhere in there, so I copied wyzard.py to
> "~/Code/distrib/wyzard" (so that it was living next to the setup
> script), deleted the tarball created by the first try, and ran
> "setup.py sdist" again. It still hadn't copied to the tarball. I tried
> again several times, but nothing happened. Can anyone explain what I
> have to do to get Distutils to include the module?

You need to delete the MANIFEST, or rerun with --force-manifest.
Otherwise, the manifest will only get regenerated when setup.py changes.

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


Re: how to dynamically instantiate an object inheriting from several classes?

2008-11-22 Thread Arnaud Delobelle
Joe Strout <[EMAIL PROTECTED]> writes:

> On Nov 21, 2008, at 7:02 PM, Steven D'Aprano wrote:
>
>>> I have a function that takes a reference to a class,
>>
>> Hmmm... how do you do that from Python code? The simplest way I can
>> think
>> of is to extract the name of the class, and then pass the name as a
>> reference to the class, and hope it hasn't been renamed in the
>> meantime...
>
> Please quit trying to confuse the kids at home.  Classes in Python are
> first-class objects, and any time you refer to a class or any other
> object in Python, what you have is a reference to it.
>
>

Why don't you put this link in your sig?  It'll save you time.  If I
were you though I would wait a bit until I have had more experience with
Python (In case you change your mind).

In the meantime why not adopt the terminology commonly used on this list
and by Python users at large?  Nobody else would talk about 'a function
that takes a reference to a class'.  It's just plain confusing.

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


Re: Python 3 __cmp__ semantic change?

2008-11-22 Thread Colin J. Williams

Johannes Bauer wrote:

Steve Holden schrieb:


If it's not present then it would be worth reporting it as a 3.0 bug -
there's still time to get it in, as the release isn't due until early
December.


Seems it was removed on purpose - I'm sure there was a good reason for
that, but may I ask why? Instead of the sleek __cmp__ function I had
earlier, I now have code like:


def __lt__(self, other):
return self.__cmp__(other) < 0

def __le__(self, other):
return self.__cmp__(other) < 0

def __gt__(self, other):
return self.__cmp__(other) > 0

def __ge__(self, other):
return self.__cmp__(other) >= 0

Does anyone know the reason why __cmp__ was discarded?

Kind regards,
Johannes



Johannes,

Isn't the problem with your original 
post that x and y are either of 
different types or, is of the same type 
that the values of that type are not 
strictly comparable?  It seems that the 
old approach was to make a recursive 
comparison.


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


Re: RELEASED Python 3.0rc3

2008-11-22 Thread Mensanator
On Nov 22, 9:32�am, [EMAIL PROTECTED] (Aahz) wrote:
> In article <[EMAIL PROTECTED]>,
>
> Mensanator �<[EMAIL PROTECTED]> wrote:
>
> >So, if the IDLE from ActiveState comes up and says 2.6 (indicating
> >final release), shouldn't the copywrite message also say 2.6
> >instead of 2.6rc1 as shown here?
>
> That would be an "oops"; please file a bug report,

Done.

> we're going to be
> releasing 2.6.1 about the same time as 3.0.
> --
> Aahz ([EMAIL PROTECTED]) � � � � � <*> � � � �http://www.pythoncraft.com/
>
> "It is easier to optimize correct code than to correct optimized code."
> --Bill Harlan

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


Re: Need help converting text to csv format

2008-11-22 Thread Chuck Connors
Firstly, I would like to thank those that offered help.  I was able to
get my data into the database and also have connectivity with the
mysql and can pull the data in/out at will.  Hooray and thanks again.

Secondly,  perhaps I overstated my abilities.  I have written a couple
of websites from scratch that pull data in/out of databases and have
formatted their outputs for user consumption.  I am by no means a php
expert and have never had occasion to use regular expressions for the
type of data I've been manipulating.  My sarcastic reply was only in
response to the 'go google it' answer I received to what I thought was
a fair question.  It's usually easiest to google something if you know
what you are looking for.  At no point did I expect anyone to spend a
great deal of time working out my specific problem but I am most
grateful for those who did provide more than what could have been
expected.

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


Re: Need help converting text to csv format

2008-11-22 Thread Thorsten Kampe
* Chuck Connors (Fri, 21 Nov 2008 08:10:09 -0800 (PST))
> Wow!  What a change in direction from the previous post.  Thank you
> both for the help and the explanations.  This will work great!

No, it will not. For manipulating CSV data in Python you use the 
(*tada*) CSV module ("import csv"). The Python doc tells you how to use 
it. Even being a PHP programmer doesn't excuse asking stupid questions.

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


Re: RELEASED Python 3.0rc3

2008-11-22 Thread Steve Holden
Mensanator wrote:
> On Nov 21, 9:06 am, Barry Warsaw <[EMAIL PROTECTED]> wrote:
>> -BEGIN PGP SIGNED MESSAGE-
>> Hash: SHA1
>>
>> On behalf of the Python development team and the Python community, I  
>> am happy to announce the third and last planned release candidate for  
>> Python 3.0.
>>
>> This is a release candidate, so while it is not quite suitable for  
>> production environments, we strongly encourage you to download and  
>> test this release on your software.  We expect only critical bugs to  
>> be fixed between now and the final release, currently planned for 03-
>> Dec-2008.
> 
> I'm getting confused. Final release will just say Python 3.0, right?
> 
> And 2.6 is in final release? So when ActiveState speaks of 2.6.0.0
> they mean a final release?
> 
> So, if the IDLE from ActiveState comes up and says 2.6 (indicating
> final release), shouldn't the copywrite message also say 2.6
> instead of 2.6rc1 as shown here?
> 
> 
> Python 2.6rc1 (r26rc1:66438, Sep 13 2008, 09:20:38) [MSC v.1500 32
> bit
> (Intel)] on win32
> Type "copyright", "credits" or "license()" for more information.
> 

Indeed it should. This is my Windows 2.6 installed from 2.6 final on
python.org:

C:\Users\sholden>\python26\python
Python 2.6 (r26:66721, Oct  2 2008, 11:35:03) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

You will note that the Subversion version number is considerably higher.
Don't worry, 2.6.1 will be out in a month or so ;-)

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: RELEASED Python 3.0rc3

2008-11-22 Thread Aahz
In article <[EMAIL PROTECTED]>,
Mensanator  <[EMAIL PROTECTED]> wrote:
>
>So, if the IDLE from ActiveState comes up and says 2.6 (indicating
>final release), shouldn't the copywrite message also say 2.6
>instead of 2.6rc1 as shown here?

That would be an "oops"; please file a bug report, we're going to be
releasing 2.6.1 about the same time as 3.0.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3 __cmp__ semantic change?

2008-11-22 Thread Aahz
In article <[EMAIL PROTECTED]>,
Arnaud Delobelle  <[EMAIL PROTECTED]> wrote:
>
>There's a very simple way of emulating Fraction.__cmp__ in Python 3:
>
>def totally_ordered(cls):
>def __lt__(self, other): return self.cmp(other) < 0
>def __eq__(self, other): return self.cmp(other) == 0
>def __gt__(self, other): return self.cmp(other) > 0
>cls.__lt__ = __lt__
>cls.__eq__ = __eq__
>cls.__gt__ = __gt__
># and same with __le__, __ge__
>return cls
>
>@totally_ordered
>class Fraction:
>def __init__(self, num, den=1):
>assert den > 0, "denomintator must be > 0"
>self.num = num
>self.den = den
>def cmp(self, other):
>return self.num*other.den - self.den*other.num
>
>
>It doesn't suffer the speed penalty incurred when defining comparison
>operators from __eq__ and __lt__.

That's true IIF __sub__() is not substantially slower than __cmp__();
however, your basic technique is sound and one can easily rewrite your
cmp() to use some other algorithm.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need help converting text to csv format

2008-11-22 Thread Steve Holden
John Machin wrote:
> On Nov 22, 11:04 am, r0g <[EMAIL PROTECTED]> wrote:
[...]>> If you can't muster even that level of enthusiasm or courtesy
towards
>> the noobs then you always have the option of not responding.
> 
> Your "if X then Y" logic is somewhat cockeyed -- Y is true independent
> of X. Looking just at X: read some of my posts. You may find some with
> a reasonable level of enthusiam and courtesy, especially where the
> enquirer appears to have helped themselves to a reasonable extent
> first and/or are having ESL difficulties and/or have not had a
> response after 12 hours or more ...
> 
John, you are an industrious and courteous helper on this list, no doubt
about it. I didn't mean to start a long debate about all this, I merely
wanted to point out that since noobs *will* often post without trying to
solve their own problem it's best to just ignore them if you don't feel
like answering.

If nobody takes pity on the questioner it will eventually be obvious
that some further access to one's own resources is necessary.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: how to get all repeated group with regular expression

2008-11-22 Thread MRAB

scsoce wrote:

MRAB wrote:
Steve 
Holden wrote:

Please keep this on the list.

scsoce wrote:

Steve Holden wrote:

scsoce wrote:
 

say, when I try to search and match every char  from variable length
string, such as string '123456',  i tried re.findall( r'(\d)*, 
'12346' )


I think you will find you missed a quote out there. Always better to
copy and paste ...

 
, but only get '6' and Python doc indeed say: "If a group is 
contained
in a part of the pattern that matched multiple times, the last 
match is

returned."


So use

r'(\d*)'

instead and then the group includes all the digits you match.

 
cause the regx engine cannot remember all the past history then ?  
is it

nature to all regx engine or only to Python ?

Different regex engines have different capabilities, so I can't 
speak to
them all. If you wanted *all* the matches of *all* groups, how 
would you
have them returned? As a list? That would make the case where there 
was

only one match  much tricker to handle. And what would you do with

  r'((\w)*\d)*)'

Also, what about named groups? I can see enough potential 
implementation
issues that I can perfectly understand why Python works the way it 
does,
so I'd be interested to know why it doesn't makes sense to you, and 
what

you would prefer it to do.

regards
 Steve
  
maybe my expression was not clear. I  want to capture every matched 
part

in a repeated pattern, not only the last,  say, for string '123456',  I
want to back reference any one char, not only the '6'. and i know the
example is very simple, so we can got the whole string using regx and
get every char using other python statements, but if the pattern in
group is complex?
and I test in VIM, it can do the 'back reference':
==you text in vim:
123456
== pattern:
:%s/\(\d\)*/$2
text will turn to be:
2


'Fraid the Python re implementers just decided not to do it that way.


Nor Perl.

Probably what you want is re.findall(r"(\d)", "123456"), which returns 
a list of what it captured.




Yes, you are right, but this way findall() capture only the 'top' group. 
What I really need to do is to capture nested and repated patterns, say, 
 tag in html contains many ,contains many ,   
the  data in   is i need, so I write the regx like this:

   regx ='''
 \n|\n)*
   \s*\n
  |\n)*
  )
  \s*
   '''
Steve Holden wrote:

I can see enough potential implementation
issues that I can perfectly understand why Python works the way it does,
so I'd be interested to know why it doesn't makes sense to you, and what
you would prefer it to do.
  


As Steve said, if re really cannot do this kind of work , so I have to 
split the one line regx down, and  capture  first, and then loop 
to catpure , and then , and so on ... . I donnot like this way 
compared with the above one clean regx line.



Why not capture just the "" entries?

If you want to know when it's starting a new table or row then how about:

re.compile(r'(If what was captured starts with "" then it's the start of a new 
table; if what was captured starts with "new row; if what was captured starts with "
--
http://mail.python.org/mailman/listinfo/python-list


Re: Module Structure/Import Design Problem

2008-11-22 Thread Steve Holden
Stef Mientki wrote:
> Steve Holden wrote:
>> Stef Mientki wrote:
>>  
>>> Gabriel Genellina wrote:
>>> 
>> [...]
>>  
>>> Sorry I don't understand all that pep-talk (I'm not a programmer ;-)
>>> 
>>
>> And I'm not a plumber. The difference between us is that I don't write
>> blogs telling people how to lay out and connect their pipework.
>>
>> regards
>>  Steve
>>
>> PS: Q: What's the difference between God and a doctor?
>> A: God doesn't think she's a doctor
>>   
> Probably this a a local disease after all,
> as only me and a couple of other non-programmers in my surrounding seems
> to have the same view on imports as me.
> 
> Let me try to explain my point of view.
> Undoubtable the import statement gives enormous functionality and
> flexibility to programmers.
> But for non-programmers the import statement is of no value whatsoever,
> and it's just a necessary evil.
> Above that, the import statement is (for non programmers) one of the
> most difficult to understand parts of Python.
> On the other hand, why do need Lutz and Ascher (which might not be the
> best book) over 50 pages to explain imports and packages ?
> Delphi, known as an "old language", has already automated imports for
> more than 15 years.
> 
> I would love to see a cookbook recipe (of at most 2 pages) , written by
> experts,
> of how to use imports in the right way. Or even better an automated
> import mechanism.
> 
> But as it looks that only a few people have the same problem as me,
> it has no value to pay any further attention to this issue.

I don't think the existing (2.6) documentation on packages is at all
satisfactory, consisting as it does of a single paragraph:

"""
Hierarchical module names: when the module names contains one or more
dots, the module search path is carried out differently. The sequence of
identifiers up to the last dot is used to find a “package”; the final
identifier is then searched inside the package. A package is generally a
subdirectory of a directory on sys.path that has a file __init__.py.
"""

Brett Cannon, a fairly active core developer, gives interesting talks
about the way the import mechanism is broken, and has plans to
eventually include a replacement implemented entirely in Python. When
that happens, we might expect the documentation to improve, but I am
afraid that in open source it has to be an itch that someone needs to
scratch, and it seems like so far nobody is itching badly enough.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Modification of a urllib2 object ?

2008-11-22 Thread jowillia
On Oct 10, 10:57 pm, George Sakkis <[EMAIL PROTECTED]> wrote:
> On Oct 10, 6:12 pm, [EMAIL PROTECTED] wrote:
>
>
>
> > On Oct 10, 1:02 pm, George Sakkis <[EMAIL PROTECTED]> wrote:
>
> > > On Oct 10, 2:32 pm, [EMAIL PROTECTED] wrote:
>
> > > > I have several ways to the following problem.
>
> > > > This is what I have:
>
> > > > ...
> > > > import ClientForm
> > > > import BeautifulSoup from BeautifulSoup
>
> > > > request = urllib2.Request('http://form.com/)
>
> > > > self.first_object = urllib2.open(request)
>
> > > > soup = BeautifulSoup(self.first_object)
>
> > > > forms = ClienForm.ParseResponse(self.first_object)
>
> > > > Now, when I do this, forms returns an index errror because no forms
> > > > are returned, but the BeautifulSoup registers fine.
>
> > > First off, please copy and paste working code; the above has several
> > > syntax errors, so it can't raise IndexError (or anything else for that
> > > matter).
>
> > > > Now, when I switch the order to this:
>
> > > > import ClientForm
> > > > import BeautifulSoup from BeautifulSoup
>
> > > > request = urllib2.Request('http://form.com/)
>
> > > > self.first_object = urllib2.open(request)
>
> > > > forms = ClienForm.ParseResponse(self.first_object)
>
> > > > soup = BeautifulSoup(self.first_object)
>
> > > > Now, the form is returned correctly, but the BeautifulSoup objects
> > > > returns empty.
>
> > > > So what I can draw from this is both methods erase the properties of
> > > > the object,
>
> > > No, that's not the case. What happens is that the http response object
> > > returned by urllib2.open() is read by the ClienForm.ParseResponse or
> > > BeautifulSoup - whatever happens first - and the second call has
> > > nothing to read.
>
> > > The easiest solution is to save the request object and call
> > > urllib2.open twice. Alternatively check if ClientForm has a parse
> > > method that accepts strings instead of urllib2 requests and then read
> > > and save the html text explicitly:
>
> > > >>> text = urllib2.open(request).read()
> > > >>> soup = BeautifulSoup(text)
> > > >>> forms = ClientForm.ParseString(text)
>
> > > HTH,
> > > George
>
> > request = urllib2.Request(settings.register_page)
>
> >                 self.url_obj = urllib2.urlopen(request).read()
>
> >                 soup = BeautifulSoup(self.url_obj);
>
> >                 forms = ClientForm.ParseResponse(self.url_obj,
> > backwards_compat=False)
>
> > Now I am getting this error:
>
> > Traceback (most recent call last):
> >   File "C:\Python25\Lib\site-packages\PyQt4\POS Pounder\Oct7\oct.py",
> > line 1251, in createAccounts
> >     forms = ClientForm.ParseResponse(self.url_obj,
> > backwards_compat=False)
> >   File "C:\Python25\lib\site-packages\clientform-0.2.9-py2.5.egg
> > \ClientForm.py", line 1054, in ParseResponse
> > AttributeError: 'str' object has no attribute 'geturl'
>
> Did you read what I wrote ? ClientForm.ParseResponse() expects a
> response object, not a string. Browsing through its docs, it seems
> there is an alternative parsing fuction, ClienForm.ParseFile(file,
> base_uri, ...).
>
> The following should work (untested):
>
> from cStringIO import StringIO
>
> request = urllib2.Request(settings.register_page)
> response = urllib2.urlopen(request)
> text = response.read()
> soup = BeautifulSoup(text)
> forms = ClientForm.ParseFile(StringIO(text), response.geturl(),
>                              backwards_compat=False)
>
> HTH,
> George

Hello George,

I seem to be running into the same problem as Vince.  Your solution
seems very good, but ClientForm gets a little bit more from the handle
than just the text.

> The following should work (untested):
>
> from cStringIO import StringIO
>
> request = urllib2.Request(settings.register_page)
> response = urllib2.urlopen(request)
> text = response.read()
> soup = BeautifulSoup(text)
> forms = ClientForm.ParseFile(StringIO(text), response.geturl(),
>  backwards_compat=False)

Hello George,

When running your code in my program, which is doing something very
similar to Vince, I get:

AttributeError: 'cStringIO.StringI' object has no attribute 'geturl'

This makes perfect sense in regards to the way ClientForms handles
requests.  It seems that short of figuring out how to deepcopy the
handle, your going to be stuck making the request twice.  But this is
going to hit the URL (server) twice, which I would say is a bad idea.

I've been struggling with this issue for some time now, and this is
the first place I've found a solid discussion about it.

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


Module not included when running "setup.py sdist"

2008-11-22 Thread Leaf
I'm running Python 2.5.2 on Ubuntu Hardy. I'm trying to write a
Distutils setup script to distribute and upload to PyPI a module I
wrote called "Wyzard." My setup script looks like:

setup(name='Wyzard',
  version='0.8',
  author='LeafStorm/Pacific Science',
  author_email='[EMAIL PROTECTED]',
  url='http://pac-sci.homeip.net/index.cgi/swproj/wyzard',
  description='A *very* simple library for command-line wizards.',
  long_description=documentation,
  py_modules=['wyzard'],
  classifiers=['Environment :: Console',
   'Development Status :: 4 - Beta',
   'Intended Audience :: Developers',
   'License :: OSI Approved :: GNU General Public
License (GPL)',
   'Natural Language :: English',
   'Programming Language :: Python :: 2.5',
   ])

Where documentation is a string I had defined earlier in the file. I
created this setup script in a directory called "~/Code/distrib/
wyzard", whose contents were just the setup script. (The file
"wyzard.py" itself lived in "~/Code", which was in sys.path.) Upon
running the "python setup.py install", I got this output:

running sdist
reading manifest file 'MANIFEST'
creating Wyzard-0.8
making hard links in Wyzard-0.8...
hard linking setup.py -> Wyzard-0.8
tar -cf dist/Wyzard-0.8.tar Wyzard-0.8
gzip -f9 dist/Wyzard-0.8.tar
removing 'Wyzard-0.8' (and everything under it)

I then ran tar -tf dist/Wyzard-0.8.tar.gz, and recieved this:

Wyzard-0.8/
Wyzard-0.8/PKG-INFO
Wyzard-0.8/setup.py

I did not see "wyzard.py" anywhere in there, so I copied wyzard.py to
"~/Code/distrib/wyzard" (so that it was living next to the setup
script), deleted the tarball created by the first try, and ran
"setup.py sdist" again. It still hadn't copied to the tarball. I tried
again several times, but nothing happened. Can anyone explain what I
have to do to get Distutils to include the module?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Very simple WSGI question

2008-11-22 Thread Manlio Perillo
Il Mon, 17 Nov 2008 01:35:19 +, Matthew Wilson ha scritto:

> I want to write some middleware to notice when the inner app returns a
> 500 status code.  I'm sure there are already sophisticated loggers that
> do this sort of thing, but I'm using this as a learning exercise.
> 
> Right now, I wrapped the start_response callable.  So when the WSGI
> application calls the start response callable, I look at the first arg
> passed in and do my test.
> 
> What's the right way to do this?
> 

Your method is correct.

As a more elaborated example:
http://hg.mperillo.ath.cx/wsgix/file/tip/wsgix/contrib/error_page.py

This middleware enables the rendering of custom pages for HTTP error 
responses.

> Matt



Regards  Manlio Perillo
--
http://mail.python.org/mailman/listinfo/python-list


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

2008-11-22 Thread Joe Strout

On Nov 22, 2008, at 4:08 AM, Aaron Brady wrote:


Furthermore, to apply c-b-v to Python, you have to
introduce the concept of pointers, which is ostensibly non-native for
human programmers.


Not necessarily "pointers" per se -- any type of object references  
will do, and yes, Python has those in spades.


 You'd have a pretty hard time making the case that c-b-v is 'round  
peg, round hole' for Python.


I didn't find it all that hard: 



 Just describe it and give it a name.


OK: "Python variables contain object references, which are copied from  
the actual parameter expression to the formal parameter.  This  
evaluation strategy is named 'call-by-value,' though some authors use  
the term 'call-by-sharing' to indicate the specific case of call-by- 
value where the values passed are object references."


(I should add that last bit to my web page -- I'll try to do that this  
weekend.)


Cheers,
- Joe

P.S. I've pretty well tired of this thread, but I can't let Greg stand  
up for truth and clarity all by himself...


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


Re: how to dynamically instantiate an object inheriting from several classes?

2008-11-22 Thread Joe Strout

On Nov 21, 2008, at 7:02 PM, Steven D'Aprano wrote:


I have a function that takes a reference to a class,


Hmmm... how do you do that from Python code? The simplest way I can  
think

of is to extract the name of the class, and then pass the name as a
reference to the class, and hope it hasn't been renamed in the  
meantime...


Please quit trying to confuse the kids at home.  Classes in Python are  
first-class objects, and any time you refer to a class or any other  
object in Python, what you have is a reference to it.


   

Cheers,
- Joe

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


Re: Programming exercises/challenges

2008-11-22 Thread Michele Simionato
On Nov 20, 1:28 pm, [EMAIL PROTECTED] wrote:
>     >> a diary manager compatible with my Emacs diary file (sometimes I
>     >> don't want to open Emacs for a quick note)
>
>     Arnaud> You mean that you sometimes don't have emacs open?
>
> I am constantly amazed at work that people open a separate emacs for each
> file they want to edit.  Most of them seem not to even know that find-file
> exists.
>
> Skip

There is a colleague of mine who keeps open a single
Emacs for weeks, with up to fifty buffers open at
the same time; he thinks using multiple
instances of Emacs is an aberration.
I myself usually keep open 3 or 4 instances of Emacs at
the same time. One instance could keep the
bunch of Python files I am editing at the moment, another
instance a bunch of SQL files, another instance
my journal, another the documentation files, etc. I feel
uncomfortable with more than three or four buffer per
Emacs, so I tend to close and reopen them often, or
to use a different Emacs instance.
I mantain my personal journal as a Python script opening
a ReST file with Emacs according to today's date.
Since the code is short, I can as well post it here:

echo $diario.py
# -*- coding: utf-8 -*-
"""
usage: %prog [options]
-p, --publish: publish the journal as a web page
"""

import os, sys, time, datetime, calendar, re, locale
try: # set italian locale
locale.setlocale(locale.LC_ALL, 'it_IT')
except:
locale.setlocale(locale.LC_ALL, 'it_IT.UTF8')
from ms.optionparser import OptionParser

if sys.platform == 'darwin':
EMACS = '/Applications/Aquamacs\ Emacs.app/Contents/MacOS/Aquamacs
\ Emacs'
else:
EMACS = 'emacs'
ROOT = os.path.join(os.environ['HOME'], 'md/diario')
if not os.path.exists(ROOT): os.mkdir(ROOT)
OUTPUT = '/tmp/diario'
DATE = re.compile('\d\d\d\d-\d\d-\d\d.txt$')
today =  datetime.date.today()
current_year = today.isoformat()[:4]
templ = """\
%s
---
"""

def open_today_page():
today_page = os.path.join(ROOT, str(today)) + '.txt'
if not os.path.exists(today_page):
print >> file(today_page, 'w'), templ % today.strftime('%A %d-
%b-%Y')
os.system('%s +4 %s &' % (EMACS, today_page))

def filter_pages_per_month_year(pages, theyear):
yield '.. contents::'
oldmonth = None
for pagename in sorted(pages):
year = pagename[:4]
if year != theyear:
continue
month = pagename[5:7]
if month != oldmonth:
yield '%s %s\n' % (
  calendar.month_name[int(month)], year)
yield file(os.path.join(ROOT, pagename)).read()
oldmonth = month

def publish_journal():
import docutils.core, webbrowser
print >> file(OUTPUT + '.txt', 'w'), '\n\n'.join(
filter_pages_per_month_year(
[f for f in os.listdir(ROOT) if DATE.match(f)], current_year))
docutils.core.publish_cmdline(
writer_name='html',
argv=[OUTPUT + '.txt', OUTPUT + '.html'])
webbrowser.open('file://%s.html' % OUTPUT)

if __name__ == '__main__':
option, args = OptionParser(__doc__).parse_args()
if option.publish:
publish_journal()
else:
open_today_page()


(the OptionParser comes from this recipe: 
http://code.activestate.com/recipes/278844/)
--
http://mail.python.org/mailman/listinfo/python-list


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

2008-11-22 Thread Aaron Brady
On Nov 21, 8:53 pm, greg <[EMAIL PROTECTED]> wrote:
> Aaron Brady wrote:
> > Call-by-value has other characteristics that Python does not
> > meet.
>
> The designers of most other dynamic languages don't
> seem to share that opinion, since they use the term
> call-by-value just as though it *does* mean call-
> by-assignment and nothing more.

The experts are divided.  There is no science that tells you how to
extrapolate a term, such as say, the Japanese equivalent of meat &
potatoes or apple pie, or c-b-v into a language that doesn't have a
copy constructor.  Furthermore, to apply c-b-v to Python, you have to
introduce the concept of pointers, which is ostensibly non-native for
human programmers.  You'd have a pretty hard time making the case that
c-b-v is 'round peg, round hole' for Python.  Just describe it and
give it a name.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic features used

2008-11-22 Thread Aaron Brady
On Nov 21, 3:17 am, [EMAIL PROTECTED] wrote:
snip
> Compared to other languages Python generally allows me to write a
> correctly working program in the shorter time (probably because of the
> Python shell, the built-in safeties, the doctests, the clean and short
> and handy syntax, the quick write-run-test cycle, the logical design,
> its uniformity, the availability of standard data structures and many
> standard or external modules, and the low number (compared to other
> languages) of corner cases and tricky semantic corners).

I like the brevity (conciseness).  The Python implementation of a
program is shorter on average than the C++ implementation.  You don't
have to declare your types, which is just extra words and handcuffs,
looking at everything but performance.  Some of the things that C++
can do are irrelevant to some programs, and Python keeps them off your
mind.  C++ gives you much finer control of a machine, but you don't
always need it.

I think the central decision-making has the advantage that there is
only one Python, whereas C has many versions.  It makes it easier to
share and communicate about programs in the language.  Plus I don't
even need new files to cut-and-paste a snippet from the newsgroup into
the interpreter.

> Today Python is defined a dynamic language (and not a scripting
> language, a term that few languages today seem to want attached to
> them) but being dynamic isn't a binary thing, it's an analog quality,
> a language can be less or be more dynamic. For example I think Ruby is
> more dynamic than Python, Python is more dynamic than CLisp, CLips
> seems more dynamic than C#/Java, Java is more dynamic than D, and D is
> more dynamic than C++. Often such differences aren't sharp, and you
> can find ways to things more dynamically, even with a less nice syntax
> (or creating less idiomatic code). (In C#4 they have even added a
> dynamic feature that may make languages like IronPython/Boo faster and
> simpler to write on the dotnet).

Python can be written in C.  Thus, anything Python can do, C can do,
not to mention the equal expressiveness of the languages.  But I have
a non-trivial observation.

With an STL 'map' and a union, you could make a quick and dirty quasi-
Python in C++.  Dynamic assignment is just a __dict__ member anyway.

Functions (and classes) are first-class objects, but the 'functor'
pattern can approximate it, even including decorators.  Variable-
length arguments are just an STL 'vector', and keyword arguments are
just an STL dict.  You can't get the same flexibility in C++ though,
without parsing the text of a function, and storing argument info
about it.  Syntax can't leave the realm of C++, but just a few classes
could be able to bring C++ a lot closer to Python.

> In the last two years I have seen many answers in the Python
> newsgroups, and I have seen that some of the dynamic features of
> Python aren't much used/appreciated:
> - Metaclasses tricks
> - exec and eval
> - monkey patching done on classes
> - arbitrary cmp among different types removed from Python 3
> While some new static-looking/related features are being introduced:
> - ABCs and function signatures added
> - More tidy exception tree
snip
> What are the dynamic features of Python more used in your programs?
> (From this set try to remove the things that can be done with a
> flexible static template system, like the D one, that for some things
> is more handy and powerful than the C++ template system, and for other
> things less powerful).

You didn't mention 'metaprogramming', which is writing a program to
generate the text code of a program, which you then compile/
interpret.  I think 'exec' enables you to keep such a program in one
piece.  For a rough example, a C++ program might have a dozen
repetitive classes, which you would have to write by hand or generate
externally.  The Python program can just execute the definitions in
place.  That is, if 'setattr' doesn't already do the trick.

The ability to return a class or a function obsoletes some of the
Gamma et al Design Patterns, such as the Factory pattern, IIRC.

And you didn't mention garbage collection.

> If very little or no dynamic features are used in a program it may
> seem a "waste" to use Python to write the code, because the final
> program may be quite slow with no gain from the other features of
> Python. (I think in such situations Python can be a good choice
> anyway, because it's good to write working prototypes in a short
> time).

Some of the value of that comes from the instant gratification that
Python gives one.  'Now' is a good time to test your code.  'Later' is
ok.  I'm thinking of writing graphics with pygame, which lacks the
same quality in C++.  Python is eloquent, whereas I'd feel I'd just
beaten a dead horse by the time I got the C++ equivalents up and
running, though perhaps less so with practice.

snip
> In the last year I have found two situations where exec/eval is a way
> to reduce a lot of th

Re: Python 3 __cmp__ semantic change?

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

> I haven't done any tests but as Fraction.__gt__ calls *both*
> Fraction.__eq__ and Fraction.__lt__ it is obvious that it is going to be
> roughly twice as slow.

There's a very simple way of emulating Fraction.__cmp__ in Python 3:

def totally_ordered(cls):
def __lt__(self, other): return self.cmp(other) < 0
def __eq__(self, other): return self.cmp(other) == 0
def __gt__(self, other): return self.cmp(other) > 0
cls.__lt__ = __lt__
cls.__eq__ = __eq__
cls.__gt__ = __gt__
# and same with __le__, __ge__
return cls

@totally_ordered
class Fraction:
def __init__(self, num, den=1):
assert den > 0, "denomintator must be > 0"
self.num = num
self.den = den
def cmp(self, other):
return self.num*other.den - self.den*other.num


It doesn't suffer the speed penalty incurred when defining comparison
operators from __eq__ and __lt__.

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


Re: Programming exercises/challenges

2008-11-22 Thread Ken

How about this:  http://www.pythonchallenge.com/

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi guys,
>
> I'm learning Python by teaching myself, and after going through several 
> tutorials I feel like I've learned the basics. Since I'm not taking a 
> class or anything, I've been doing challenges/programs to reinforce the 
> material and improve my skills. I started out with stuff like "Guess my 
> number" games, hangman, etc. and moved on to making poker and card games 
> to work with classes. For GUIs I created games like minesweeper, and a GUI 
> stock portfolio tracker. I am out of ideas and am looking for programming 
> projects, challenges, or programs that have helped you'll learn. I'm 
> working on the project Euler problems, but I find that they don't really 
> help my programming skills; they are more math focused. Suggestions? What 
> has been useful or interesting to you? I'd also welcome sources of 
> textbook type problems, because the ones provided in tutorials tend to be 
> repetitive.
>
> Thanks,
> Ben 


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


Re: Python 3 __cmp__ semantic change?

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

> On Sat, 22 Nov 2008 08:27:59 +, Arnaud Delobelle wrote:
>
 Granted it's not as efficient as a __cmp__ function.
>>>
>>> What makes you say that? What do you mean by "efficient"? Are you
>>> talking about memory footprint, runtime speed, disk-space, programmer
>>> efficiency, algorithmic complexity, or something else?
>> 
>> What I'm talking about is very simple - and explained below, with the
>> help of your __cmp__ method.
>>>
>>> As I see it, a __cmp__ method would be written something like this:
>>>
>>> def __cmp__(self, other):
>>> return cmp(self.num*other.den, self.den*other.num)
>> 
>> I'm talking about runtime speed (*not* asymptotic complexity).  My code
>> makes Fraction.__gt__ about twice as slow as Fraction.__lt__ or
>> Fraction.__eq__ even though with __cmp__ they would all be equally fast.
>
>
> Sounds like a premature micro-optimization to me. On my machine, running 
> Python 2.5, the speed difference is nothing like twice as slow.
>
>
 class UseCmp(object):
> ... def __init__(self, num, den=1):
> ... self.num = num
> ... self.den = den
> ... def __cmp__(self, other):
> ... return cmp(self.num*other.den, self.den*other.num)
> ...
 class UseRichCmp(UseCmp):
> ... __lt__ = lambda self, other: self.__cmp__(other) < 0
> ...
 from timeit import Timer
 t1 = Timer('x < y',
> ... 'from __main__ import UseCmp; x=UseCmp(3, 5); y=UseCmp(1, 2)')
 t2 = Timer('x < y',
> ... 'from __main__ import UseRichCmp;'
> ... 'x=UseRichCmp(3, 5); y=UseRichCmp(1, 2)')

 t1.repeat()
> [3.3418200016021729, 2.4046459197998047, 2.2295808792114258]
 t2.repeat()
> [3.8954730033874512, 3.0240590572357178, 3.5528950691223145]
>
> There's a slight speed difference, around 35% slower. But the random 
> variation in speed is almost 50%, so I would conclude from this trial 
> that there is no *significant* speed difference between the methods.

That's not surprising.  You're measuring the wrong things.  If you read
what I wrote, you'll see that I'm talking about Fraction.__gt__ being
slower (as it is defined in terms of Fraction.__eq__ and
Fraction.__lt__) using when my 'totally_ordered' decorator.

I haven't done any tests but as Fraction.__gt__ calls *both*
Fraction.__eq__ and Fraction.__lt__ it is obvious that it is going to be
roughly twice as slow.

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


Re: Module Structure/Import Design Problem

2008-11-22 Thread Stef Mientki

Steve Holden wrote:

Stef Mientki wrote:
  

Gabriel Genellina wrote:


[...]
  

Sorry I don't understand all that pep-talk (I'm not a programmer ;-)



And I'm not a plumber. The difference between us is that I don't write
blogs telling people how to lay out and connect their pipework.

regards
 Steve

PS: Q: What's the difference between God and a doctor?
A: God doesn't think she's a doctor
  

Probably this a a local disease after all,
as only me and a couple of other non-programmers in my surrounding seems 
to have the same view on imports as me.


Let me try to explain my point of view.
Undoubtable the import statement gives enormous functionality and 
flexibility to programmers.
But for non-programmers the import statement is of no value whatsoever, 
and it's just a necessary evil.
Above that, the import statement is (for non programmers) one of the 
most difficult to understand parts of Python.
On the other hand, why do need Lutz and Ascher (which might not be the 
best book) over 50 pages to explain imports and packages ?
Delphi, known as an "old language", has already automated imports for 
more than 15 years.


I would love to see a cookbook recipe (of at most 2 pages) , written by 
experts,
of how to use imports in the right way. Or even better an automated 
import mechanism.


But as it looks that only a few people have the same problem as me,
it has no value to pay any further attention to this issue.

cheers,
Stef

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


Re: Python 3 __cmp__ semantic change?

2008-11-22 Thread Steven D'Aprano
On Sat, 22 Nov 2008 08:27:59 +, Arnaud Delobelle wrote:

>>> Granted it's not as efficient as a __cmp__ function.
>>
>> What makes you say that? What do you mean by "efficient"? Are you
>> talking about memory footprint, runtime speed, disk-space, programmer
>> efficiency, algorithmic complexity, or something else?
> 
> What I'm talking about is very simple - and explained below, with the
> help of your __cmp__ method.
>>
>> As I see it, a __cmp__ method would be written something like this:
>>
>> def __cmp__(self, other):
>> return cmp(self.num*other.den, self.den*other.num)
> 
> I'm talking about runtime speed (*not* asymptotic complexity).  My code
> makes Fraction.__gt__ about twice as slow as Fraction.__lt__ or
> Fraction.__eq__ even though with __cmp__ they would all be equally fast.


Sounds like a premature micro-optimization to me. On my machine, running 
Python 2.5, the speed difference is nothing like twice as slow.


>>> class UseCmp(object):
... def __init__(self, num, den=1):
... self.num = num
... self.den = den
... def __cmp__(self, other):
... return cmp(self.num*other.den, self.den*other.num)
...
>>> class UseRichCmp(UseCmp):
... __lt__ = lambda self, other: self.__cmp__(other) < 0
...
>>> from timeit import Timer
>>> t1 = Timer('x < y',
... 'from __main__ import UseCmp; x=UseCmp(3, 5); y=UseCmp(1, 2)')
>>> t2 = Timer('x < y',
... 'from __main__ import UseRichCmp;'
... 'x=UseRichCmp(3, 5); y=UseRichCmp(1, 2)')
>>>
>>> t1.repeat()
[3.3418200016021729, 2.4046459197998047, 2.2295808792114258]
>>> t2.repeat()
[3.8954730033874512, 3.0240590572357178, 3.5528950691223145]

There's a slight speed difference, around 35% slower. But the random 
variation in speed is almost 50%, so I would conclude from this trial 
that there is no *significant* speed difference between the methods.


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


Chase credit cards HERE ALL

2008-11-22 Thread BUSHRA
Chase Credit Cards & CreditCard Offers at CreditCardFlyers

http://www.chasecreditcardsnews.50webs.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3 __cmp__ semantic change?

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

> On Fri, 21 Nov 2008 17:26:21 +, Arnaud Delobelle wrote:
>
> [...]
>> As classes can be decorated in Python 3, you can write a decorator to
>> make a class totally ordered.  Here is a very simplified proof of
>> concept such decorator:
>> 
>> def totally_ordered(cls):
>> if not hasattr(cls, '__gt__'):
>> def gt(self, other):
>> return self != other and not self < other
>> cls.__gt__ = gt
>> # Do the same with __le__, __ge__
>> return cls
>> 
>> 
>> @totally_ordered
>> class Fraction:
>> def __init__(self, num, den=1):
>> assert den > 0, "denomintator must be > 0" self.num = num
>> self.den = den
>> def __eq__(self, other):
>> return self.num*other.den == self.den*other.num
>> def __lt__(self, other):
>> return self.num*other.den < self.den*other.num
>> 
> q12=Fraction(1, 2)
> q23=Fraction(2, 3)
> q12 < q23
>> True
> q12 > q23
>> False
>> 
>> Granted it's not as efficient as a __cmp__ function.
>
> What makes you say that? What do you mean by "efficient"? Are you talking 
> about memory footprint, runtime speed, disk-space, programmer efficiency, 
> algorithmic complexity, or something else?

What I'm talking about is very simple - and explained below, with the
help of your __cmp__ method.
>
> As I see it, a __cmp__ method would be written something like this:
>
> def __cmp__(self, other):
> return cmp(self.num*other.den, self.den*other.num)

I'm talking about runtime speed (*not* asymptotic complexity).  My code
makes Fraction.__gt__ about twice as slow as Fraction.__lt__ or
Fraction.__eq__ even though with __cmp__ they would all be equally fast.

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


Re: Programming exercises/challenges

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

> I have to point out that I myself use Vim more than
> Emacs. Not because I think it's better (I'm not a religious person)
> but because it has better integration with my Mac... and actually, I
> use them for different programming tasks.

I'm only a very occasional user of vi, so I don't really know how vim
integrates with MacOS X but have you tried aquamacs
(http://aquamacs.org/)?

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