Re: Flatten a list/tuple and Call a function with tuples

2007-07-25 Thread Marc 'BlackJack' Rintsch
On Thu, 26 Jul 2007 00:58:10 +, beginner wrote:

> I need nested lists to represent nested records in a script. Since the
> structure of the underlying data is nested, I think it is probably
> reasonable to represent them as nested lists. For example, if I have
> the below structure:
> 
> Big Record
>Small Record Type A
>Many Small Record Type B
>Small Record Type C
> 
> It is pretty natural to use lists, although after a while it is
> difficult to figure out the meaning of the fields in the lists. If
> only there were a way to 'attach' names to members of the list.

That's where you may start looking into classes.  The simplest one is for
just holding attributes seems to be the "bunch":

In [15]: class Bunch(object):
   : def __init__(self, **kwargs):
   : self.__dict__ = kwargs
   :

In [16]: small_a = Bunch(foo=42, bar=23)

In [17]: many_b = [1, 2, 3]

In [18]: small_c = Bunch(name='eric', profession='viking')

In [19]: big_record = Bunch(small_a=small_a, many_b=many_b, small_c=small_c)

In [20]: big_record.small_a.bar
Out[20]: 23

In [21]: big_record.many_b[1]
Out[21]: 2


> For the unpacking question, I encountered it when working with list
> comprehensions. For example:
> 
> [ f(*x,1,2) for x in list] is difficult to do if I don't want to
> expand *x to x[0]..x[n]. There are usually 7-10 items in the list and
> it is very tedious and error prone.

If you are the designer of `f` then just receive the whole `x` as *one*
argument.

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


Re: Pickled objects over the network

2007-07-25 Thread Paul Rubin
"Hendrik van Rooyen" <[EMAIL PROTECTED]> writes:
> But more seriously - is there any need for a simple serialiser that will
> be able to be used to transfer a subset of the built in types over an
> open network in a safe manner, for the transfer of things like lists of
> parameters?
> 
> Or am I the only person in the squad that hears this particular drum?

This has been open for 5+ years:

http://sourceforge.net/tracker/index.php?func=detail&aid=467384&group_id=5470&atid=355470

Related:

http://sourceforge.net/tracker/index.php?func=detail&aid=471893&group_id=5470&atid=105470
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading files, splitting on a delimiter and newlines.

2007-07-25 Thread Hendrik van Rooyen
: <[EMAIL PROTECTED]> Wrote:

> On Jul 25, 10:46 am, [EMAIL PROTECTED] wrote:
> > Hello,
> >
> > I have a situation where I have a file that contains text similar to:
> >
> > myValue1 = contents of value1
> > myValue2 = contents of value2 but
> > with a new line here
> > myValue3 = contents of value3
> >
> > My first approach was to open the file, use readlines to split the
> > lines on the "=" delimiter into a key/value pair (to be stored in a
> > dict).
> >
> > After processing a couple files I noticed its possible that a newline
> > can be present in the value as shown in myValue2.
> >
> > In this case its not an option to say remove the newlines if its a
> > "multi line" value as the value data needs to stay intact.
> >
> > I'm a bit confused as how to go about getting this to work.
> >
> > Any suggestions on an approach would be greatly appreciated!
> 
> I'm confused. You don't want the newline to be present, but you can't
> remove it because the data has to stay intact? If you don't want to
> change it, then what's the problem?

I think the OP's trouble is that the value he wants gets split up by the
newline at the end of the line when he uses readline().

One can try adding the single value to the previous value in the previous
key/value pair when the split does not yield two values - a bit hackish,
but given structured input data it might work.

- Hendrik

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


Re: How to create a single executable of a Python program

2007-07-25 Thread NicolasG
> You need to tell us why you "think" you need this and perhaps we can make a
> suggestion.  Question: Have you installed ANY applications recently that
> consisted of only a single file on your hard drive?  Answer: No.  Most
> applications install many (sometimes hundreds) of files.  So what is the
> problem.  If you want a single file to distribute, look at Inno Installer.  
> Use
> it to make a single, setup.exe out of all the files that come out of py2exe
> along with documentation, shortcuts, etc. that a good modern application 
> needs.
>
> -Larry

I "want" to create a single file for two of my very simple/small
programs. For very simple/small programs I don't need to distribute
documentation, shortcuts etc.. I just want a single file to run !
Another reason is that for another program I wrote has to do with
displaying an Image file and I want that this image file can be
visible only through my program and not exposed in the same directory
where my program is located.

Thank you all for the suggestions, I will try some methods you
mentioned.

Regards,
Nicolas.

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


Re: From D

2007-07-25 Thread Ben Finney
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> On Jul 25, 9:04?pm, Steven D'Aprano
> <[EMAIL PROTECTED]> wrote:
> Why does it make no sense? Have you never had to scrape a web page
> or read a CSV file?

Again, unrelated to the way the Python compiler syntactically treats
the source code.

> So this proposal would only apply to string literals at compile
> time, not running programs?

Exactly the same way that it works for string literals in source code:
once the source code is compiled, the literal is indistinguishable
from the same value written a different way.

> And I want the same error to occur if my CSV parser tries to convert
> '123 456' into a single number.  I don't want it to assume the
> number is '123456'.

Once again, this is a discussion about Python syntax, not the
behaviour of the csv module.

-- 
 \"I always had a repulsive need to be something more than |
  `\   human."  -- David Bowie |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pickled objects over the network

2007-07-25 Thread Hendrik van Rooyen
"Marco Mariani"  wrote:


> Hendrik van Rooyen ha scritto:
> 
> > But more seriously - is there any need for a simple serialiser that will
> > be able to be used to transfer a subset of the built in types over an
> > open network in a safe manner, for the transfer of things like lists of
> > parameters?
> 
> Yes, there seems to be a need for XML/YAML/JSON   :-)

Looks like it - else there would not be so many of them.
Are they all safe and secure?

- Hendrik

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


Re: From D

2007-07-25 Thread Ben Finney
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> On Jul 25, 8:54?pm, Steven D'Aprano
> <[EMAIL PROTECTED]> wrote:
> Any number of whitespace characters? Just spaces or all whitespace
> characters?

> What about searching source code files? What's the regular
> expression for locating a number with an arbitrary number of digits
> seperated into an arbitrary number of blocks of an arbitray number
> of digits with an arbitrary number of whitespace characters between
> each block?

These issues all exist for implicitly concatenated string literals. It
seems the same rules would apply; that would both make sense from an
implementation standpoint, and result in consistency for the Python
programmer too.

-- 
 \ "Are you pondering what I'm pondering?" "I think so, Brain, but |
  `\   wouldn't his movies be more suitable for children if he was |
_o__)   named Jean-Claude van Darn?"  -- _Pinky and The Brain_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Keyword argument 'from'; invalid syntax

2007-07-25 Thread Stargaming
On Thu, 26 Jul 2007 12:08:40 +1000, Steven D'Aprano wrote:

> On Thu, 26 Jul 2007 03:33:20 +0200, Kai Kuehne wrote:
> 
>> I have tried to prepare a dict and then passing it to the method
>> afterwards:
> d = {'person': 'user', 'from': vorgestern}
> magnolia.bookmarks_find(d)
>> : bookmarks_find() takes exactly 1
>> argument (2 given)
>> 
>> I'm out of ideas so help is greatly appreciated!
> 
> Try this:
> 
> magnolia.bookmarks_find(**d)
> 
> although I suspect that will probably raise an exception as well.
> Judging by the error message, it looks like bookmarks_find() takes only
> a single argument, which I imagine would be the "self" instance
> automatically provided at runtime.

Could be bookmarks_find(person, **other), unpacking other manually.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cls & self

2007-07-25 Thread Stargaming
On Thu, 26 Jul 2007 03:07:56 +, james_027 wrote:

> hi,
> 
> is cls & self the same thing?
> 
> I have seen something like
> 
> class A:
> def dosomething(cls):
>#doing something
> 
> How is cls & self differ? How is it use?
> 
> Thanks
> james

First, you have to understand that the choice of this name is *completely 
arbitrary*. You could call it self, cls, this, bogus, helloworld or 
whatsoever. The important thing is just: The first argument is (by 
default) the instance.

Amongst python developers, many things aren't enforced by the language 
(eg. implicit `this` referencing the instance, as in other languages) but 
by conventions. It's just way more convenient to call it `self` always. 
We call it `cls` when speaking about classmethods. Your method there 
might have been headed by a line containing [EMAIL PROTECTED]

See http://docs.python.org/lib/built-in-funcs.html#l2h-16 for classmethod 
and http://docs.python.org/tut/node11.html#SECTION001140 
for this conventional stuff (paragraph "Often, the first argument ...").

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


Re: I am giving up perl because of assholes on clpm -- switching to Python

2007-07-25 Thread Ben Finney
[EMAIL PROTECTED] writes:

> Python is a better language, with php support, anyway, but I am fed
> up with attitudes of comp.lang.perl.misc.

Please, if you must fred the troll, drop comp.lang.python from the
discussion (i.e. post trplies only to the newsgroup this message
relates to).

-- 
 \  "I like to reminisce with people I don't know. Granted, it |
  `\  takes longer."  -- Steven Wright |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: From D

2007-07-25 Thread Ben Finney
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> IDLE 1.2c1
> >>> s = '123 456'
> >>> s.split()
> ['123', '456']

The str.split method has no bearing on this discussion, which is about
the Python language syntax, and numeric literal values in particular.

-- 
 \"Pinky, are you pondering what I'm pondering?" "Wuh, I think |
  `\so, Brain, but burlap chafes me so."  -- _Pinky and The Brain_ |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: From D

2007-07-25 Thread [EMAIL PROTECTED]
On Jul 25, 9:04?pm, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:
> On Wed, 25 Jul 2007 18:17:19 -0700, [EMAIL PROTECTED] wrote:
> > On Jul 25, 8:00 pm, Ben Finney <[EMAIL PROTECTED]>
> > wrote:
> >> "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:
> >> > On Jul 24, 6:08 pm, Steven D'Aprano
> >> > <[EMAIL PROTECTED]> wrote:
> >> > > Python already does:
> >> > > "hello-" "world" => "hello-world"
>
> >> > > Propose:
> >> > > 123 456 789 => 123456789
> >> > > 123.456 789 => 123.456789
>
> >> > So, spaces will no longer be delimiters?
>
> >> I don't see how you get that conclusion from Steven's proposal.
>
> > IDLE 1.2c1
>  s = '123 456'
>  s.split()
> > ['123', '456']
>
> > The only way to get '123 456' would be to treat a space as a
> > non-delimiter. But what if those actually WERE two different numbers?
>
> That makes no sense at all. Your example is about splitting a _string_.

Why does it make no sense? Have you never had to
scrape a web page or read a CSV file?

> You can construct and split the string any way you like:
>
> >>> s = '123SURPRISE456'
> >>> s.split('SURPRISE')
>
> ['123', '456']
>
> Notice that the results aren't ints, they are strings.

Duh. I took for granted you knew how to convert
an string to an integer.

>
> To get an int literal, you currently type something like 123456. 123 456
> is currently not valid in Python, it raises an SyntaxError. Try it for
> yourself:

So this proposal would only apply to string literals
at compile time, not running programs?

>
> >>> 123 456
>
>   File "", line 1
> 123 456
>   ^
> SyntaxError: invalid syntax

And I want the same error to occur if my CSV parser
tries to convert '123 456' into a single number.
I don't want it to assume the number is '123456'.

>
> If you want two numbers, you would do exactly the same thing you would now:
>
> >>> x, y = 123, 456
> >>> print "x is %d and y is %d" % (x, y)
>
> x is 123 and y is 456
>
> --
> Steven

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


Re: From D

2007-07-25 Thread [EMAIL PROTECTED]
On Jul 25, 8:54?pm, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:
> On Wed, 25 Jul 2007 10:22:46 -0700, [EMAIL PROTECTED] wrote:
> > On Jul 24, 6:08 pm, Steven D'Aprano
> > <[EMAIL PROTECTED]> wrote:
> >> On Tue, 24 Jul 2007 20:09:00 +0200, Bjoern Schliessmann wrote:
> >> > Stargaming wrote:
> >> >> On Tue, 24 Jul 2007 03:19:53 -0700, bearophileHUGS wrote:
>
> >> >>> While in a syntax like:
> >> >>> for i in xrange(1_000_000):
> >> >>> my eyes help me group them at once.
>
> >> >> Sounds like a good thing to be but the arbitrary positioning
> >> >> doesnt make any sense.
>
> >> > Checking underscore positions would only add complexity. Why not
> >> > just ignore them, no matter where they are?
>
> >> Underscores in numerics are UGLY. Why not take a leaf out of implicit
> >> string concatenation and allow numeric literals to implicitly concatenate?
>
> >> Python already does:
> >> "hello-" "world" => "hello-world"
>
> >> Propose:
> >> 123 456 789 => 123456789
> >> 123.456 789 => 123.456789
>
> > So, spaces will no longer be delimiters? Won't that cause
> > much wailing and gnashing of teeth?
>
> Did you miss the bit where Python ALREADY does this for strings?

Did you miss the bit where I agreed this was a GOOD feature?
You didn't miss it because I didn't say it.

>
> Yes, whitespace will still delimit tokens. No, it won't be a problem,
> because two int tokens can be "concatenated" to make a single int token,
> exactly as happens for strings.

Any number of whitespace characters? Just spaces or all
whitespace characters?

>
> (I say "no problem", but of course I don't know how much _actual_ coding
> effort will be needed to Make This Work. It might be a little, it might be
> a lot.)
>
> Currently, 234 567 is a syntax error in Python, so there are no problems
> with backward compatibility or breaking code that relies on the meaning of
> whitespace between two ints.

That's the ONLY issue? What about searching source
code files? What's the regular expression for
locating a number with an arbitrary number of digits
seperated into an arbitrary number of blocks of an
arbitray number of digits with an arbitrary number
of whitespace characters between each block?

>
> --
> Steven

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


Re: Singleton in Python Cookbook

2007-07-25 Thread Steve Holden
Alex Popescu wrote:
> Alex Popescu <[EMAIL PROTECTED]> wrote in 
> news:[EMAIL PROTECTED]:
> 
>> "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote in
>> news:[EMAIL PROTECTED]: 
>>
>>> Alex Popescu schrieb:
 Hi all!

 I was reading through Python Cookbook the Singleton recipe. At this
 moment I am a bit puzzled as the example in the book is not working
 resulting in: 

 TypeError: type.__new__(SingleSpam): SingleSpam is not a subtype of
 type 

 (I haven't presented the original code as I am not sure about
 copyrights). 
>>> AFAIK the cookbook is completely found online at ASPN. So no sweat 
>>> publishing it here.
>>>
>>>
>>> And regarding the problem: is it possible that you forgot to subclass 
>>> SingleSpam from object?
>>>
>>> Diez
>> The exact code:
>> class Singleton(object):
>> """ A Pythonic Singleton """
>> def _ _new_ _(cls, *args, **kwargs):
>> if '_inst' not in vars(cls):
>> cls._inst = type._ _new_ _(cls, *args, **kwargs)
>> return cls._inst
>>
>> if _ _name_ _ == '_ _main_ _':
>> class SingleSpam(Singleton):
>> def _ _init_ _(self, s): self.s = s
>> def _ _str_ _(self): return self.s
>> s1 = SingleSpam('spam')
>> print id(s1), s1.spam( )
>> s2 = SingleSpam('eggs')
>> print id(s2), s2.spam( )
>>
>> ./alex
>> --
>> .w( the_mindstorm )p.
>>
> I got it working in 2 ways:
> 
> class Singleton(object):
>   """ A Pythonic Singleton """
>   def __new__(cls, *args, **kwargs):
> if '_singletoninstance' not in vars(cls):
>   #variant 1: cls._singletoninstance = object.__new__(cls, *args, 
> **kwargs)
>   #variant 2: cls._singletoninstance = super(type, cls).__new__(cls, 
> *args, **kwargs)
> return cls._singletoninstance
> 
> Both of these seem to work.
> 
If, that is, "work" means "Raise an AttributeError due to the missing 
spam() method". This appears to fix that problem:

class Singleton(object):
 """ A Pythonic Singleton """
 def __new__(cls, *args, **kwargs):
 if '_inst' not in vars(cls):
 cls._inst = object.__new__(cls, *args, **kwargs)
 return cls._inst

if __name__ == '__main__':
 class SingleSpam(Singleton):
 def __init__(self, s): self.s = s
 def __str__(self): return self.s
 s1 = SingleSpam('spam')
 print id(s1), s1
 s2 = SingleSpam('eggs')
 print id(s2), s2
 print str(s1)

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Locale-specific string comparasion

2007-07-25 Thread Yuan HOng

Hi,

The locale modules privides a strcoll function that can perform locale
specific string comparision, and based on this, we can design custom
comparision function for the sorting.

However, this is quite cumbersome, for we have to derive custom
classes from from the string / unicode objects, and provide
comparision function to use locale.strcoll.

Is there a way to 'install' a system wide LC_COLLATE function, so that
string and unicode objects will automatically use the locale for their
comparision?

--
Hong Yuan

大管家网上建材超市
装修装潢建材一站式购物
http://www.homemaster.cn
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: idiom for RE matching

2007-07-25 Thread Gordon Airporte
Ben Finney wrote:
> 
> Not that I want to pick on you; I just don't want something wrong
> labelled as "proper" to go unchallenged in the archives :-)

Oh gawd :-P

I swear I have it right in the actual file! heh.
Copy and paste something that's compiled kids, copy and paste.

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


Re: Singleton in Python Cookbook

2007-07-25 Thread O.R.Senthil Kumaran
* Alex Popescu <[EMAIL PROTECTED]> [2007-07-25 21:30:14]:

> TypeError: type.__new__(SingleSpam): SingleSpam is not a subtype of type

That's hardly helpful. All I can think about is, SingleSpam is a class and you
have to defined the Class in your program, or it could be something else also.

> (I haven't presented the original code as I am not sure about copyrights).
> 
If there is an online version of the code, please point to us that. Or you can
ask the author of the book directly.

-- 
O.R.Senthil Kumaran
http://uthcode.sarovar.org
-- 
http://mail.python.org/mailman/listinfo/python-list


cls & self

2007-07-25 Thread james_027
hi,

is cls & self the same thing?

I have seen something like

class A:
def dosomething(cls):
   #doing something

How is cls & self differ? How is it use?

Thanks
james

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


Re: idiom for RE matching

2007-07-25 Thread Ben Finney
Gordon Airporte <[EMAIL PROTECTED]> writes:

> The actual code uses the proper 'if foo in line or if bar in line:'
> form.

>>> line = "spam eggs ham"
>>> foo = "spam"
>>> bar = "sausage"
>>> if foo in line or if bar in line:
  File "", line 1
if foo in line or if bar in line:
   ^
SyntaxError: invalid syntax

Not that I want to pick on you; I just don't want something wrong
labelled as "proper" to go unchallenged in the archives :-)

-- 
 \ "Never do anything against conscience even if the state demands |
  `\  it."  -- Albert Einstein |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: idiom for RE matching

2007-07-25 Thread Wildemar Wildenburger
Gordon Airporte wrote:
> Yes, that's pseudo code even though I didn't really mean it that way 
> when I typed it. The actual code uses the proper 'if foo in line or if 
> bar in line:' form.
>   
One 'if' too many.
/W
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unable to abort a FTP command?

2007-07-25 Thread _wdx
Thank you. You are right, retrbinary did not notice I want to abort,
so it won't break the recv loop and close data connection. I changed
getpart and callback like this, now it works:

def getpart_callback(self, received):
print "received a packet"
if self.cnt <= 0:
return True
else:
print 'received packet, [0] = %x' % ord(received[0])
self.outf.write(received)
self.cnt -= len(received)

def getpart(self, ftp_filename, rest, cnt, out_filename):
self.outf = open(out_filename, 'wb')
self.cnt = cnt
self.handle.voidcmd('TYPE I')
conn = self.handle.transfercmd('RETR ' + ftp_filename, rest)
while 1:
data = conn.recv(8192)
if not data:
break
if self.getpart_callback(data):
try:
self.handle.abort()
break
except:
pass
self.outf.close()
self.handle.voidresp()
conn.close()

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


Re: Keyword argument 'from'; invalid syntax

2007-07-25 Thread Kai Kuehne
Hi Steven,

On 7/26/07, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> On Thu, 26 Jul 2007 03:33:20 +0200, Kai Kuehne wrote:
> Try this:
>
> magnolia.bookmarks_find(**d)

This works perfectly, thank you guys.
Kai
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: first, second, etc line of text file

2007-07-25 Thread Gabriel Genellina
En Wed, 25 Jul 2007 19:14:28 -0300, James Stroud <[EMAIL PROTECTED]>  
escribió:

> Daniel Nogradi wrote:
>> A very simple question: I currently use a cumbersome-looking way of
>> getting the first, second, etc. line of a text file:
>
> to_get = [0, 3, 7, 11, 13]
> got = dict((i,s) for (i,s) in enumerate(open(textfile)) if i in to_get)
> print got[3]
>
> This would probably be the best way for really big files and if you know
> all of the lines you want ahead of time.

But it still has to read the complete file (altough it does not keep the  
unwanted lines).
Combining this with Paul Rubin's suggestion of itertools.islice I think we  
get the best solution:
got = dict((i,s) for (i,s) in  
enumerate(islice(open(textfile),max(to_get)+1)) if i in to_get)

-- 
Gabriel Genellina

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


Re: Keyword argument 'from'; invalid syntax

2007-07-25 Thread Steven D'Aprano
On Thu, 26 Jul 2007 03:33:20 +0200, Kai Kuehne wrote:

> I have tried to prepare a dict and then passing it to the
> method afterwards:
 d = {'person': 'user', 'from': vorgestern}
 magnolia.bookmarks_find(d)
> : bookmarks_find() takes exactly 1
> argument (2 given)
> 
> I'm out of ideas so help is greatly appreciated!

Try this:

magnolia.bookmarks_find(**d)

although I suspect that will probably raise an exception as well. Judging
by the error message, it looks like bookmarks_find() takes only a single
argument, which I imagine would be the "self" instance automatically
provided at runtime.



-- 
Steven.

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


Re: From D

2007-07-25 Thread Steven D'Aprano
On Wed, 25 Jul 2007 18:17:19 -0700, [EMAIL PROTECTED] wrote:

> On Jul 25, 8:00 pm, Ben Finney <[EMAIL PROTECTED]>
> wrote:
>> "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:
>> > On Jul 24, 6:08 pm, Steven D'Aprano
>> > <[EMAIL PROTECTED]> wrote:
>> > > Python already does:
>> > > "hello-" "world" => "hello-world"
>>
>> > > Propose:
>> > > 123 456 789 => 123456789
>> > > 123.456 789 => 123.456789
>>
>> > So, spaces will no longer be delimiters?
>>
>> I don't see how you get that conclusion from Steven's proposal.
> 
> IDLE 1.2c1
 s = '123 456'
 s.split()
> ['123', '456']
> 
> The only way to get '123 456' would be to treat a space as a
> non-delimiter. But what if those actually WERE two different numbers?

That makes no sense at all. Your example is about splitting a _string_.
You can construct and split the string any way you like:

>>> s = '123SURPRISE456'
>>> s.split('SURPRISE')
['123', '456']

Notice that the results aren't ints, they are strings.

To get an int literal, you currently type something like 123456. 123 456
is currently not valid in Python, it raises an SyntaxError. Try it for
yourself:

>>> 123 456
  File "", line 1
123 456
  ^
SyntaxError: invalid syntax

If you want two numbers, you would do exactly the same thing you would now:

>>> x, y = 123, 456
>>> print "x is %d and y is %d" % (x, y)
x is 123 and y is 456



-- 
Steven.

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


Re: win32com ppt embedded object numbers reverting back to original numbers - SOLVED

2007-07-25 Thread Lance Hoffmeyer
Hey all,

I solved this problem.  Here is the final version of this def for anyone who
someday may be interested:

def attributesbyID(row,base,slideID,spreadsheet):
sh = wb.Worksheets (spreadsheet)
sh.Select()
LIST = xlparams(row, base)
 POWERPOINT SECTION ##
for shape in WB.Slides.FindBySlideID(slideID).Shapes:
if (shape.Type== 7):
for oXLROW,oXLBASE,oXLLASTCOL,oPPTCELL,oPPTHEADERCELL 
in LIST:
oVALUE = sh.Cells(oXLROW,oXLLASTCOL).Value
oHEADER = sh.Cells(base-1,oXLLASTCOL).Value  + 
" (n="  +  str(int(sh.Cells(oXLBASE,oXLLASTCOL).Value))  + ")"
PWB = 
WB.Slides.FindBySlideID(slideID).Shapes(shape.Name)
oGraph = PWB.OLEFormat.Object
#   oGraph = shape.OLEFormat.Object

oGraph.Application.datasheet.Range(oPPTCELL).Value = oVALUE

oGraph.Application.datasheet.Range(oPPTHEADERCELL).Value = oHEADER
oGraph.Application.datasheet.Font.Bold=False
oGraph.Application.Update()
oGraph.Application.Quit()   
del oGraph
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Keyword argument 'from'; invalid syntax

2007-07-25 Thread Paul Rubin
"Kai Kuehne" <[EMAIL PROTECTED]> writes:
> >>> d = {'person': 'user', 'from': vorgestern}
> >>> magnolia.bookmarks_find(d)
> : bookmarks_find() takes exactly 1
> argument (2 given)
> 
> I'm out of ideas so help is greatly appreciated!

Try 
  magnolia.bookmarks_find(**d)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: From D

2007-07-25 Thread Steven D'Aprano
On Wed, 25 Jul 2007 10:22:46 -0700, [EMAIL PROTECTED] wrote:

> On Jul 24, 6:08 pm, Steven D'Aprano
> <[EMAIL PROTECTED]> wrote:
>> On Tue, 24 Jul 2007 20:09:00 +0200, Bjoern Schliessmann wrote:
>> > Stargaming wrote:
>> >> On Tue, 24 Jul 2007 03:19:53 -0700, bearophileHUGS wrote:
>>
>> >>> While in a syntax like:
>> >>> for i in xrange(1_000_000):
>> >>> my eyes help me group them at once.
>>
>> >> Sounds like a good thing to be but the arbitrary positioning
>> >> doesnt make any sense.
>>
>> > Checking underscore positions would only add complexity. Why not
>> > just ignore them, no matter where they are?
>>
>> Underscores in numerics are UGLY. Why not take a leaf out of implicit
>> string concatenation and allow numeric literals to implicitly concatenate?
>>
>> Python already does:
>> "hello-" "world" => "hello-world"
>>
>> Propose:
>> 123 456 789 => 123456789
>> 123.456 789 => 123.456789
> 
> So, spaces will no longer be delimiters? Won't that cause
> much wailing and gnashing of teeth?


Did you miss the bit where Python ALREADY does this for strings?

Yes, whitespace will still delimit tokens. No, it won't be a problem,
because two int tokens can be "concatenated" to make a single int token,
exactly as happens for strings.

(I say "no problem", but of course I don't know how much _actual_ coding
effort will be needed to Make This Work. It might be a little, it might be
a lot.)

Currently, 234 567 is a syntax error in Python, so there are no problems
with backward compatibility or breaking code that relies on the meaning of
whitespace between two ints.


-- 
Steven

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


Re: Reading files, splitting on a delimiter and newlines.

2007-07-25 Thread chrispwd
On Jul 25, 7:56 pm, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> On Jul 25, 8:46 am, [EMAIL PROTECTED] wrote:
>
>
>
> > Hello,
>
> > I have a situation where I have a file that contains text similar to:
>
> > myValue1 = contents of value1
> > myValue2 = contents of value2 but
> > with a new line here
> > myValue3 = contents of value3
>
> > My first approach was to open the file, use readlines to split the
> > lines on the "=" delimiter into a key/value pair (to be stored in a
> > dict).
>
> > After processing a couple files I noticed its possible that a newline
> > can be present in the value as shown in myValue2.
>
> > In this case its not an option to say remove the newlines if its a
> > "multi line" value as the value data needs to stay intact.
>
> > I'm a bit confused as how to go about getting this to work.
>
> > Any suggestions on an approach would be greatly appreciated!
>
> Check the length of the list returned from split; this allows
> your to append to the previously extracted value if need be.
>
> import StringIO
> import pprint
>
> buf = """\
> myValue1 = contents of value1
> myValue2 = contents of value2 but
>with a new line here
> myValue3 = contents of value3
> """
>
> mockfile = StringIO.StringIO(buf)
>
> record=dict()
>
> for line in mockfile:
> kvpair = line.split('=', 2)
> if len(kvpair) == 2:
> key, value = kvpair
> record[key] = value
> else:
> record[key] += line
>
> pprint.pprint(record)
>
> # lstrip() to remove newlines if needed ...
>
> --
> Hope this helps,
> Steven

Great thank you! That was the logic I was looking for.

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


Keyword argument 'from'; invalid syntax

2007-07-25 Thread Kai Kuehne
Hi list!
I'm using pygmalion (magnolia api access lib) and want to
use the following method that it is offering:

magnolia.bookmarks_find(person='user', from=some_datetime)

As you may noticed, from is a keyword argument and so I
get the following error message from python:

   File "", line 1
 magnolia.bookmarks_find(person='user', from=some_datetime)
  ^
: invalid syntax

I have tried to prepare a dict and then passing it to the
method afterwards:
>>> d = {'person': 'user', 'from': vorgestern}
>>> magnolia.bookmarks_find(d)
: bookmarks_find() takes exactly 1
argument (2 given)

I'm out of ideas so help is greatly appreciated!
Thanks
Kai
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: From D

2007-07-25 Thread [EMAIL PROTECTED]
On Jul 25, 8:00 pm, Ben Finney <[EMAIL PROTECTED]>
wrote:
> "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:
> > On Jul 24, 6:08 pm, Steven D'Aprano
> > <[EMAIL PROTECTED]> wrote:
> > > Python already does:
> > > "hello-" "world" => "hello-world"
>
> > > Propose:
> > > 123 456 789 => 123456789
> > > 123.456 789 => 123.456789
>
> > So, spaces will no longer be delimiters?
>
> I don't see how you get that conclusion from Steven's proposal.

IDLE 1.2c1
>>> s = '123 456'
>>> s.split()
['123', '456']

The only way to get '123 456' would be to treat a space as a
non-delimiter. But what if those actually WERE two different numbers?

> If the
> latter implied that "spaces will no longer be delimiters", then surely
> the former must also imply that.
>
> The former already exists, spaces are still delimiters when syntax
> allows, so your conclusion is baseless.
>
> --
>  \   "I got food poisoning today. I don't know when I'll use it."  |
>   `\  -- Steven Wright |
> _o__)  |
> Ben Finney


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


Re: Flatten a list/tuple and Call a function with tuples

2007-07-25 Thread Jeff
> For example, if I have
> the below structure:
>
> Big Record
>Small Record Type A
>Many Small Record Type B
>Small Record Type C
>
> It is pretty natural to use lists, although after a while it is
> difficult to figure out the meaning of the fields in the lists. If
> only there were a way to 'attach' names to members of the list.

You could use dictionaries:

big_record = {
  "small_record_a": { ... },
  "many_small_record_b": {
"sub_record_of_b": { ... },
"sub_record_of_b2": { ... },
  },
  "small_record_c": { ... },
}

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


Re: Why PHP is so much more popular for web-development

2007-07-25 Thread Jeff McNeil
On 7/25/07, Steve Holden <[EMAIL PROTECTED]> wrote:
> Jeff McNeil wrote:
> > Unfortunately, I also find that PHP programmers are usually more
> > plentiful than their Python counterparts.  When thinking of staffing
> > an organization, it's common to target a skill set that's cheaper to
> > employ and easier to replace down the road if need be.
> >
> Right, that's why hospitals are replacing their surgeons with butchers.
> There are so many more of them available. It's only cutting meat, after all.
>

I prefer Python by a long shot, but I'm confident there are a lot of
shops making the PHP vs. Python decision every day and this is up
there on the list of PHP's benefits.  Of the 10 guys I've interviewed
in the past two months, I think one had Python experience. In digging
a bit deeper, it turns out he got that installing Anaconda packages.

> > Also, larger hosting shops are hesitant to run things such as TG and
> > Rails that require an additional server process.  The name of the game
> > is density.  Sure, it may be easy to manage and run a TG project, but
> > it's a pain to set one up on a shared hosting server.
> >
> Virtualization will solve that problem.

It will help, sure.  I run a few things in a FreeBSD VPS right now,
actually. I really like the freedom it brings.

The problem again goes back to density, though.  I work for one of the
large web hosting firms.  When talking straight shared hosting, we can
put well over 50,000 web sites on a cluster of servers.  On our VPS
products? That number drops down to about 1,000 on the same hardware
configuration.  If we start talking about hardware virtualization,
divide by ten again.

The technology is getting there, but it's still just not feasible to
hit the same scale with virtualization that one can hit when building
a standard shared hosting platform.

All of that said, we *do* offer Python on our products. We just don't
provide additional support for things such as TurboGears, Zope, or
Django. All of our provisioning and management infrastructure is in
Python as well.

>
> > Lastly, I personally think it has something to do with the fact that
> > so many of the popular, free, web applications are PHP based. It's
> > easy for the average Web Administrator to get started with your
> > standard PHP package. From there, picking up the language is the next
> > logical step.
> >
> There's some justice to that.
>
> regards
>   Steve
> --
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC/Ltd   http://www.holdenweb.com
> Skype: holdenweb  http://del.icio.us/steve.holden
> --- Asciimercial --
> Get on the web: Blog, lens and tag the Internet
> Many services currently offer free registration
> --- Thank You for Reading -
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Flatten a list/tuple and Call a function with tuples

2007-07-25 Thread Steven D'Aprano
On Wed, 25 Jul 2007 09:33:26 -0700, Paul Rubin wrote:

> Things
> are logically single values or they are logically lists of values

Except for strings, and string-like objects.

And files.

And records/structs, and tuples.

And lists. And sets.

And bit strings. And tree-like structures. 

And, well, just about everything really.

But apart from those minor exceptions, I agree completely with your
recommendation.

(Ha ha only serious.)


-- 
Steven.

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



Re: Flatten a list/tuple and Call a function with tuples

2007-07-25 Thread Steven D'Aprano
On Wed, 25 Jul 2007 15:46:58 +, beginner wrote:

> I know the * operator. However, a 'partial unpack' does not seem to
> work.
> 
> def g():
>   return (1,2)
> 
> def f(a,b,c):
>   return a+b+c
> 
> f(*g(),10) will return an error.


No it doesn't, it _raises_ an exception. This is a function that returns
an error:

def function():
"""Returns an error."""
return Error()  # defined elsewhere

But to answer your question:

> Do you know how to get that to work?

It's a little bit messy, but this works:

>>> f(*(g() + (10,)))
13

This is probably easier to read:

>>> t = g() + (10,); f(*t)
13


-- 
Steven.

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


Re: From D

2007-07-25 Thread Ben Finney
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> On Jul 24, 6:08 pm, Steven D'Aprano
> <[EMAIL PROTECTED]> wrote:
> > Python already does:
> > "hello-" "world" => "hello-world"
> >
> > Propose:
> > 123 456 789 => 123456789
> > 123.456 789 => 123.456789
> 
> So, spaces will no longer be delimiters?

I don't see how you get that conclusion from Steven's proposal. If the
latter implied that "spaces will no longer be delimiters", then surely
the former must also imply that.

The former already exists, spaces are still delimiters when syntax
allows, so your conclusion is baseless.

-- 
 \   "I got food poisoning today. I don't know when I'll use it."  |
  `\  -- Steven Wright |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I 'stat' online files?

2007-07-25 Thread Gabriel Genellina
En Wed, 25 Jul 2007 15:11:19 -0300, Carsten Haese <[EMAIL PROTECTED]>  
escribió:

> On Tue, 2007-07-24 at 22:23 -0300, Gabriel Genellina wrote:
>> En Tue, 24 Jul 2007 10:47:16 -0300, Carsten Haese <[EMAIL PROTECTED]>
>> escribió:
>>
>> > On Tue, 2007-07-24 at 09:07 -0400, DB Daniel Brown wrote:
>> >> I am working on a program that needs to stat files (gif, swf, xml,
>> >> dirs, etc) from the web. I know how to stat a local file…
>> >
>> > That's because urlopen returns a file-like object, not a file. The  
>> best
>> > you can hope for is to inspect the headers that the web server  
>> returns:
>> >
>>  f = urllib.urlopen("http://www.python.org";)
>>
>> This generates an HTTP GET request - transfering the contents too,
>> innecesarily.
>
> Yes, but how much of that content will actually be transferred if I
> don't call f.read?

Transferred? The server perhaps has sent all of it, depending on its  
configuration and available bandwidth. The first packets will be in your  
TCP receiving buffers even if you never call f.read(). So be nice to the  
origin server, the whole Internet, and our planet, and don't waste  
bandwidth and energy in requesting things that you're going to throw away  
anyway.

> I doubt that my computer just downloaded 4 MB of stuff in 0.3 seconds.

Probably not, but I'd use netstat or ntop to find out how much has  
actually been downloaded.

-- 
Gabriel Genellina

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

Re: Flatten a list/tuple and Call a function with tuples

2007-07-25 Thread beginner

> Not the most beautiful solution, but it works.
>
> Diez- Hide quoted text -
>
> - Show quoted text -

Yeah it works! Thanks.

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


Re: Flatten a list/tuple and Call a function with tuples

2007-07-25 Thread beginner

> Well, there are several ways to solve this. You could either invoke f(*g
> () + (10,)). Might be a bit nasty and unreadable, though. Or you could
> just change your function f to accept them in reversed order (f(10, *g)
> should work) or convert g() to return a dictionary like {'b': 1, 'c': 2}
> and use f(10, **g). But if your function f's hugest use case is being
> called with g(), changing f to accept something and g's result (tuple) --
> unpacking it inside f -- might be better.- Hide quoted text -
>
> - Show quoted text -

These all work. Thanks.

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


Re: Flatten a list/tuple and Call a function with tuples

2007-07-25 Thread beginner
> Also, this has not been suggested:
>
> py> def g():
> ...   return (1,2)
> ...
> py> def f(a,b,c):
> ...   return a+b+c
> ...
> py> f(c=10, *g())
> 13
>
> James- Hide quoted text -
>
> - Show quoted text -

Great idea.

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


Re: Flatten a list/tuple and Call a function with tuples

2007-07-25 Thread beginner
On Jul 25, 11:33 am, Paul Rubin  wrote:
> beginner <[EMAIL PROTECTED]> writes:
> > I know the * operator. However, a 'partial unpack' does not seem to work.
>
> A few other posters have mentioned ways around this, but you might ask
> yourself what coding situation makes you want to do this stuff in the
> first place.  I won't say there's never a reason for it, but a lot of
> times, a list containing a mixture of scalars and lists/tuples is a
> sign that your underlying data representation is contorted.  Things
> are logically single values or they are logically lists of values, and
> that mixed representation is often a sign that the item logically
> should be a list, and you're hairing up the program with special
> treatment of the case where the list has exactly one element.
>
> I.e. instead of [[1,2,], 3, [5,6,]] maybe you really want
> [[1,2,], [3,], [5,6]] without the special treatment and flattening.

Very good question. It is well possible that the problem is my
programming style. I am new to python and am still developing a style
that works for me. A lot of things that work in perl does not seem to
work. Unpacking and flattening are just two examples.

I need nested lists to represent nested records in a script. Since the
structure of the underlying data is nested, I think it is probably
reasonable to represent them as nested lists. For example, if I have
the below structure:

Big Record
   Small Record Type A
   Many Small Record Type B
   Small Record Type C

It is pretty natural to use lists, although after a while it is
difficult to figure out the meaning of the fields in the lists. If
only there were a way to 'attach' names to members of the list.

For the unpacking question, I encountered it when working with list
comprehensions. For example:

[ f(*x,1,2) for x in list] is difficult to do if I don't want to
expand *x to x[0]..x[n]. There are usually 7-10 items in the list and
it is very tedious and error prone.

The second problem is from a nested list comprehension. I just needed
something to flatten the list at the moment.

I am still forming my way to do things in python via trial and error.
It is well possible that this is not the natural way to do things.


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


Re: classmethod & staticmethod

2007-07-25 Thread Steven D'Aprano
On Wed, 25 Jul 2007 00:55:17 +, Alex Popescu wrote:

> Neil Cerutti <[EMAIL PROTECTED]> wrote in news:eRwpi.36813$G23.28496
> @newsreading01.news.tds.net:
> 
>> On 2007-07-25, Alex Popescu <[EMAIL PROTECTED]> wrote:
>>> As a matter of style, how do you figure out that class_list is
>>> a class attribute and not an instance attribute? (I don't
>>> remember seeing anything in the PEP describing the coding
>>> style).
>> 
>> Check out dir(MyClass) and dir(MyClass()) for some insight, if it
>> turns out that it matters. 
> 
> I must confess that I am a bit confused by this advise, as both are 
> returning exactly the same thing.
> 
>> Preferably, the user of a class
>> doesn't have to really think about it much.
>> 
> I know that this would be prefered, but in case you are getting 3rd party 
> code and you modify a class attribute without knowing it is a class 
> attribute then you may get into trouble (indeed the real problem is with 
> the designer of the 3rd party code, but still I think it is a valid 
> concern).

# warning: doesn't consider slots
if "attribute" in instance.__dict__:
print "instance attribute"
elif "attribute" in instance.__class__.__dict__:
print "class attribute"
else:
print "either no attribute at all, or in a parent class"



-- 
Steven.

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


Re: code indentation

2007-07-25 Thread Ben Finney
[EMAIL PROTECTED] writes:

> On this group I ask for serious help and now we talk about
> communication.

Yes. You're asking for volunteer help from a group of people who have
their own priorities separate from yours. The way to garner help from
these people is to respect their time. One excellent way to do that is
to communicate clearly and maturely, so that your messages are easier
(and therefore faster) to read.

Please, before going further, read this document on how to ask
questions the smart way:

http://catb.org/~esr/faqs/smart-questions.html>

> Then I you don't know how to help me then please DON'T SAY ANYTHING

This is a volunteer group, run for the benefit of the community. We
want to help not only you, but *anyone* who might come here asking for
help, and especially those who are inclined to help them.

Advice on improving communication is one good way to do that: it
actively works toward better communication in future, which helps
questions get answered quicker and consumes less of the helpers' time.

-- 
 \ "I put contact lenses in my dog's eyes. They had little |
  `\   pictures of cats on them. Then I took one out and he ran around |
_o__)   in circles."  -- Steven Wright |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: classmethod & staticmethod

2007-07-25 Thread Steven D'Aprano
On Wed, 25 Jul 2007 00:22:18 +, Alex Popescu wrote:

> "Steven D'Aprano" <[EMAIL PROTECTED]> wrote in
> news:[EMAIL PROTECTED]: 
> 
>> On Tue, 24 Jul 2007 21:35:58 +, Alex Popescu wrote:
>> 
>>> Neil Cerutti <[EMAIL PROTECTED]> wrote in
>>> news:[EMAIL PROTECTED]: 
>>> 
 On 2007-07-24, Alex Popescu <[EMAIL PROTECTED]> wrote:
> Bruno Desthuilliers
> <[EMAIL PROTECTED]> wrote in
> news:[EMAIL PROTECTED]: 
>

 [snip...]

>> 
>> Use self.class_list when you want to use inheritance.
>> 
> 
> As a matter of style, how do you figure out that class_list is a class 
> attribute and not an instance attribute? (I don't remember seeing anything 
> in the PEP describing the coding style).


The whole point of inheritance is that you don't care where the attribute
is (the instance, the class, a parent class...) just that it exists.



-- 
Steven.

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


Re: Why PHP is so much more popular for web-development

2007-07-25 Thread Jeff
No programming language can fix bad programmers.  And if cost is an
issue, www.nearlyfreespeech.net has Python, clisp, and OCaml.

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


Re: python-fam documentation.

2007-07-25 Thread Evan Klitzke
On 7/25/07, Evan Klitzke <[EMAIL PROTECTED]> wrote:
> On 7/23/07, Shriphani <[EMAIL PROTECTED]> wrote:
> > Folks,
> > I am trying to create an app which stares at a file and when the file
> > is altered, the script joins a channel on freenode and reports that
> > the file has been altered.
> > I found a module called python-fam, unfortunately i have been unable
> > to find documentation for it. Can someone please help me ?
> > Thanks,
> > Shriphani Palakodety.
>
> If you're running a newish version of Linux; this module has fairly
> complete documentation.

Oops, that was supposed to be

If you're running a newish version of Linux, you might try pyinotify;
this module has fairly complete documentation.

-- 
Evan Klitzke <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python-fam documentation.

2007-07-25 Thread Evan Klitzke
On 7/23/07, Shriphani <[EMAIL PROTECTED]> wrote:
> Folks,
> I am trying to create an app which stares at a file and when the file
> is altered, the script joins a channel on freenode and reports that
> the file has been altered.
> I found a module called python-fam, unfortunately i have been unable
> to find documentation for it. Can someone please help me ?
> Thanks,
> Shriphani Palakodety.

If you're running a newish version of Linux; this module has fairly
complete documentation.

-- 
Evan Klitzke <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cleaning up a string

2007-07-25 Thread MRAB
On Jul 24, 8:47 pm, James Stroud <[EMAIL PROTECTED]> wrote:
> Hello all,
>
> I dashed off the following function to clean a string in a little
>
> program I wrote:
>
> def cleanup(astr, changes):
>for f,t in changes:
>  atr = astr.replace(f, t)
>return astr
>
> where changes would be a tuple, for example:
>
> changes = (
>   ('%', '\%'),
>   ('$', '\$'),
>   ('-', '_')
>)
>
> If these were were single replacements (like the last), string.translate
> would be the way to go. As it is, however, the above seems fairly
> inefficient as it potentially creates a new string at each round. Does
> some function or library exist for these types of transformations that
> works more like string.translate or is the above the best one can hope
> to do without writing some C? I'm guessing that "if s in astr" type
> optimizations are already done in the replace() method, so that is not
> really what I'm getting after.
>
A simple way of replacing single characters would be this:

def cleanup(astr, changes):
changes = dict(changes)
return "".join(changes.get(c, c) for c in astr)

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


Re: Closures / Blocks in Python

2007-07-25 Thread Gabriel Genellina
En Wed, 25 Jul 2007 11:45:00 -0300, Jeff <[EMAIL PROTECTED]> escribió:

> You can create a lexical closure using a Python generator function,
> which allows iteration using a block of code while maintaining
> internal state.  A generator is a regular function which uses yield
> (like Ruby) to define the point at which the function should return an
> expression to the calling code.  For example:
>
> # Generic counter
> def counter(min=None, max):
>   if not min:
> min = 0
>   for i in xrange(min, max):
> yield i
> i = i + 1
>
> When called, this function will yield the value of i and remember its
> state.  The next time it's called, it will increment i, then continue
> on another iteration of the loop, yielding the new value of i.
>
> For example:
>
> my_counter = counter(0, 10)
> my_counter() # <-- 0
> my_counter() # <-- 1
> for i in my_counter():
>   print i
> # Prints 2-10 (the remaining numbers in xrange(min, max))

Uhmm, I think this won't win the Best Python Code Of The Week Award :)
Apart from the already noted syntax error in the function definition, the  
`i = i + 1` is useless because `i` gets reassigned right on the next loop.
And you don't "call" a generator, you have to iterate over it;  
my_counter() will raise an error. This would be the right way:

my_counter = counter(0, 10)
my_counter.next() <-- 0
my_counter.next() <-- 1
for value in my_counter:
   print value  <-- 2 to 9

-- 
Gabriel Genellina

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


Re: Reading files, splitting on a delimiter and newlines.

2007-07-25 Thread [EMAIL PROTECTED]
On Jul 25, 8:46 am, [EMAIL PROTECTED] wrote:
> Hello,
>
> I have a situation where I have a file that contains text similar to:
>
> myValue1 = contents of value1
> myValue2 = contents of value2 but
> with a new line here
> myValue3 = contents of value3
>
> My first approach was to open the file, use readlines to split the
> lines on the "=" delimiter into a key/value pair (to be stored in a
> dict).
>
> After processing a couple files I noticed its possible that a newline
> can be present in the value as shown in myValue2.
>
> In this case its not an option to say remove the newlines if its a
> "multi line" value as the value data needs to stay intact.
>
> I'm a bit confused as how to go about getting this to work.
>
> Any suggestions on an approach would be greatly appreciated!



Check the length of the list returned from split; this allows
your to append to the previously extracted value if need be.

import StringIO
import pprint

buf = """\
myValue1 = contents of value1
myValue2 = contents of value2 but
   with a new line here
myValue3 = contents of value3
"""

mockfile = StringIO.StringIO(buf)

record=dict()

for line in mockfile:
kvpair = line.split('=', 2)
if len(kvpair) == 2:
key, value = kvpair
record[key] = value
else:
record[key] += line

pprint.pprint(record)

# lstrip() to remove newlines if needed ...

--
Hope this helps,
Steven

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


Re: first, second, etc line of text file

2007-07-25 Thread Paul Rubin
"Daniel Nogradi" <[EMAIL PROTECTED]> writes:

> A very simple question: I currently use a cumbersome-looking way of
> getting the first, second, etc. line of a text file:
> 
> for i, line in enumerate( open( textfile ) ):
> if i == 0:
> print 'First line is: ' + line
> elif i == 1:
> print 'Second line is: ' + line
> ...
> ...

from itertools import islice
first_five_lines = list(islice(open(textfile), 5))

print 'first line is', first_five_lines[0]
print 'second line is', first_five_lines[1]
...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading a Directory of Emails - Problems

2007-07-25 Thread StatsJunkie

Thanks. I tried that, but absolutely nothing is printed to the screen. 

This is the code I am trying to use.

mbox = mailbox.MHMailbox("stat_inbox.mbox/Messages",email.message_from_file) 
for msg in mbox:
 print(msg)  #just to see if anything is happening

Which mailbox type did you use? Perhaps MHMailbox in the wrong one...?


Joshua J. Kugler-2 wrote:
> 
> On Tuesday 24 July 2007 09:38, Ryan Rosario wrote:
> 
>> Hi,
>> 
>> I have a directory that contains a bunch of email messages and I would
>> like to parse them using the email and mailbox packages. The emails were
>> exported from Apple Mail. From what I gather, I need to use MHMailbox,
>> but
>> I can't get it to do anything useful and I cannot find any examples of
>> how
>> to use this particular mailbox type.
>> 
> 
>> 
>> I get an error. AttributeError: MHMailbox instance has no attribute
>> 'keys'. Yet this works when using PortableUnixMailbox (on an mbox file,
>> not a directory of emails).
> 
> I fought with this a while back.  It seems it is nested one level lower. 
> You might have to get at the message by doing something like
> 
> real_message = msg[0]
> 
> Instead of print msg.keys(), just do a 'print msg' and see what data
> structure is returned.  That will tell you a lot.
> 
> j
> 
> -- 
> Joshua Kugler
> Lead System Admin -- Senior Programmer
> http://www.eeinternet.com
> PGP Key: http://pgp.mit.edu/  ID 0xDB26D7CE
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

-- 
View this message in context: 
http://www.nabble.com/Reading-a-Directory-of-Emails---Problems-tf4137576.html#a11801990
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: first, second, etc line of text file

2007-07-25 Thread Jeff McNeil

Yup, I actually had log files in mind, too.  I process Apache logs from an
8-way cluster every 15 minutes. There are 32,000 sites on said cluster;
that's a lot of log data!

I didn't actually think anyone would go *try* to
open("war_and_peace.txt").readlines().. I just meant it as a generalization
for "really large file." =)

-Jeff

On 7/25/07, Jay Loden <[EMAIL PROTECTED]> wrote:


Grant Edwards wrote:
> On 2007-07-25, Jeff <[EMAIL PROTECTED]> wrote:
>
>> That might be a memory problem if you are running multiple processes
>> regularly, such as on a webserver.
>
> I suppose if you did it in parallel 50 processes, you could use
> up 250MB of RAM.  Still not a big deal on many servers.  A
> decent OS will swap regions that aren't being used to disk, so
> it's likely not to be a problem.

Or, you might be reading from a text file dramatically larger than a 3MB
copy of War and Peace. I regularly deal with log files that are often many
times that, including some that have been well over a GB or more. Trust me,
you don't want to read in the entire file when it's a 1.5GB text file.
It's true that many times readlines() will work fine, but there are also
certainly cases where it's not acceptable for memory and performance
reasons.

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

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

Re: Singleton in Python Cookbook

2007-07-25 Thread John J. Lee
Alex Popescu <[EMAIL PROTECTED]> writes:

> Hi all!
>
> I was reading through Python Cookbook the Singleton recipe. At this moment 
> I am a bit puzzled as the example in the book is not working resulting in:
>
> TypeError: type.__new__(SingleSpam): SingleSpam is not a subtype of type

Haven't looked at that recipe, but take a look at this related one:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531



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


Re: Singleton in Python Cookbook

2007-07-25 Thread John J. Lee
"Diez B. Roggisch" <[EMAIL PROTECTED]> writes:
[...]
> AFAIK the cookbook is completely found online at ASPN. So no sweat
> publishing it here.
[...]

No: the book-form cookbook is edited, and has extra text.

I believe the recipes are under a BSD-style license, though.


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


Re: Singleton in Python Cookbook

2007-07-25 Thread Alex Popescu
Alex Popescu <[EMAIL PROTECTED]> wrote in 
news:[EMAIL PROTECTED]:

> "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote in
> news:[EMAIL PROTECTED]: 
> 
>> Alex Popescu schrieb:
>>> Hi all!
>>> 
>>> I was reading through Python Cookbook the Singleton recipe. At this
>>> moment I am a bit puzzled as the example in the book is not working
>>> resulting in: 
>>> 
>>> TypeError: type.__new__(SingleSpam): SingleSpam is not a subtype of
>>> type 
>>> 
>>> (I haven't presented the original code as I am not sure about
>>> copyrights). 
>> 
>> AFAIK the cookbook is completely found online at ASPN. So no sweat 
>> publishing it here.
>> 
>> 
>> And regarding the problem: is it possible that you forgot to subclass 
>> SingleSpam from object?
>> 
>> Diez
> 
> The exact code:
> class Singleton(object):
> """ A Pythonic Singleton """
> def _ _new_ _(cls, *args, **kwargs):
> if '_inst' not in vars(cls):
> cls._inst = type._ _new_ _(cls, *args, **kwargs)
> return cls._inst
> 
> if _ _name_ _ == '_ _main_ _':
> class SingleSpam(Singleton):
> def _ _init_ _(self, s): self.s = s
> def _ _str_ _(self): return self.s
> s1 = SingleSpam('spam')
> print id(s1), s1.spam( )
> s2 = SingleSpam('eggs')
> print id(s2), s2.spam( )
> 
> ./alex
> --
> .w( the_mindstorm )p.
> 
I got it working in 2 ways:

class Singleton(object):
  """ A Pythonic Singleton """
  def __new__(cls, *args, **kwargs):
if '_singletoninstance' not in vars(cls):
  #variant 1: cls._singletoninstance = object.__new__(cls, *args, 
**kwargs)
  #variant 2: cls._singletoninstance = super(type, cls).__new__(cls, 
*args, **kwargs)
return cls._singletoninstance

Both of these seem to work.

./alex
--
.w( the_mindstorm )p.

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


Re: I am giving up perl because of assholes on clpm -- switching to Python

2007-07-25 Thread James Matthews

Wow! They might leave this newsgroup now also!

On 7/25/07, Jürgen Exner <[EMAIL PROTECTED]> wrote:


[EMAIL PROTECTED] wrote:
> Python is a better language, with php support, anyway, but I am fed up
> with attitudes of comp.lang.perl.misc. Assholes in this newsgroup ruin
> Perl experience for everyone. Instead of being helpful, snide remarks,
> back-biting, scare tactings, and so on proliferate and self
> reinforce. All honest people have left this sad newsgroup. Buy bye,
> assholes, I am not going to miss you!!!

Considering that your total posting history according to DejaNews consists
of exactly 3 posts (not including this last one) from 2001 to 2003 in NGs
that are so closely related to programming as pregnancy, marriage, and
cancer I believe the last sentiment is very mutual. After all, you didn't
ever leave any trace in CLPM until today.

jue


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





--
http://www.goldwatches.com/watches.asp?Brand=55
http://www.jewelerslounge.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Singleton in Python Cookbook

2007-07-25 Thread Alex Popescu
"Diez B. Roggisch" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Alex Popescu schrieb:
>> Hi all!
>> 
>> I was reading through Python Cookbook the Singleton recipe. At this
>> moment I am a bit puzzled as the example in the book is not working
>> resulting in: 
>> 
>> TypeError: type.__new__(SingleSpam): SingleSpam is not a subtype of
>> type 
>> 
>> (I haven't presented the original code as I am not sure about
>> copyrights). 
> 
> AFAIK the cookbook is completely found online at ASPN. So no sweat 
> publishing it here.
> 
> 
> And regarding the problem: is it possible that you forgot to subclass 
> SingleSpam from object?
> 
> Diez

The exact code:
class Singleton(object):
""" A Pythonic Singleton """
def _ _new_ _(cls, *args, **kwargs):
if '_inst' not in vars(cls):
cls._inst = type._ _new_ _(cls, *args, **kwargs)
return cls._inst

if _ _name_ _ == '_ _main_ _':
class SingleSpam(Singleton):
def _ _init_ _(self, s): self.s = s
def _ _str_ _(self): return self.s
s1 = SingleSpam('spam')
print id(s1), s1.spam( )
s2 = SingleSpam('eggs')
print id(s2), s2.spam( )

./alex
--
.w( the_mindstorm )p.

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


Re: idiom for RE matching

2007-07-25 Thread Gordon Airporte
Miles wrote:
> On 7/24/07, Gordon Airporte <[EMAIL PROTECTED]> wrote:
>> I did already find that it speeds things up to pre-test a line like
>>
>> if 'bets' or 'calls' or 'raises' in line:
>> run the appropriate re's
> 
> Be careful: unless this is just pseudocode, this Python doesn't do
> what you think it does; it always runs the regular expressions, so any
> speed-up is imaginary.

Yes, that's pseudo code even though I didn't really mean it that way 
when I typed it. The actual code uses the proper 'if foo in line or if 
bar in line:' form.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading files, splitting on a delimiter and newlines.

2007-07-25 Thread John Machin
On Jul 26, 3:08 am, Stargaming <[EMAIL PROTECTED]> wrote:
> On Wed, 25 Jul 2007 09:16:26 -0700, kyosohma wrote:
> > On Jul 25, 10:46 am, [EMAIL PROTECTED] wrote:
> >> Hello,
>
> >> I have a situation where I have a file that contains text similar to:
>
> >> myValue1 = contents of value1
> >> myValue2 = contents of value2 but
> >> with a new line here
> >> myValue3 = contents of value3
>
> >> My first approach was to open the file, use readlines to split the
> >> lines on the "=" delimiter into a key/value pair (to be stored in a
> >> dict).
>
> >> After processing a couple files I noticed its possible that a newline
> >> can be present in the value as shown in myValue2.
>
> >> In this case its not an option to say remove the newlines if its a
> >> "multi line" value as the value data needs to stay intact.
>
> >> I'm a bit confused as how to go about getting this to work.
>
> >> Any suggestions on an approach would be greatly appreciated!
>
> > I'm confused. You don't want the newline to be present, but you can't
> > remove it because the data has to stay intact? If you don't want to
> > change it, then what's the problem?
>
> > Mike
>
> It's obviously that simple line-by-line filtering won't handle multi-line
> statements.
>
> You could solve that by saving the last item you added something to and,
> if the line currently handles doesn't look like an assignment, append it
> to this item. You might run into problems with such data:
>
>   foo = modern maths
>   proved that 1 = 1
>   bar = single
>
> If your dataset always has indendation on subsequent lines, you might use
> this. Or if the key's name is always just one word.
>

My take: all of the above, plus: Given that you want to extract stuff
of the form  =  I'd suggest developing a fairly precise
regular expression for LHS, maybe even for RHS, and trying this on as
many of these files as you can.

Why an RE for RHS? Consider:

foo = somebody said "I think that
REs = trouble
maybe_better = pyparsing"

:-)

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


Re: first, second, etc line of text file

2007-07-25 Thread Jay Loden
Grant Edwards wrote:
> On 2007-07-25, Jeff <[EMAIL PROTECTED]> wrote:
> 
>> That might be a memory problem if you are running multiple processes
>> regularly, such as on a webserver.
> 
> I suppose if you did it in parallel 50 processes, you could use
> up 250MB of RAM.  Still not a big deal on many servers.  A
> decent OS will swap regions that aren't being used to disk, so
> it's likely not to be a problem.  

Or, you might be reading from a text file dramatically larger than a 3MB copy 
of War and Peace. I regularly deal with log files that are often many times 
that, including some that have been well over a GB or more. Trust me, you don't 
want to read in the entire file when it's a 1.5GB text file. It's true that 
many times readlines() will work fine, but there are also certainly cases where 
it's not acceptable for memory and performance reasons.

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


Re: Why PHP is so much more popular for web-development

2007-07-25 Thread walterbyrd
On Jul 25, 3:55 pm, Steve Holden <[EMAIL PROTECTED]> wrote:
> Jeff McNeil wrote:

> > Unfortunately, I also find that PHP programmers are usually more
> > plentiful than their Python counterparts.  When thinking of staffing
> > an organization, it's common to target a skill set that's cheaper to
> > employ and easier to replace down the road if need be.
>
> Right, that's why hospitals are replacing their surgeons with butchers.
> There are so many more of them available. It's only cutting meat, after all.
>

Hospitals probably would if they could. Healthcare is extremely
regulated. Software development, web or otherwise, is still the wild-
west. Besides, I don't think it's quite fair to characterize all PHP
developers as "butchers" and Python developers as "surgeons." Python
may be superior to PHP, but come on now. Besides, I see about 100X
more ads for PHP programmers, than Python programmers. My guess is
that there probably are a lot more PHP developers, especially web-
developers.

> > Also, larger hosting shops are hesitant to run things such as TG and
> > Rails that require an additional server process.  The name of the game
> > is density.  Sure, it may be easy to manage and run a TG project, but
> > it's a pain to set one up on a shared hosting server.
>
> Virtualization will solve that problem.
>

I can get PHP hosting for $10/year. Will I be able to get a virtual
host for that?

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


Re: I am giving up perl because of assholes on clpm -- switching to Python

2007-07-25 Thread J�rgen Exner
[EMAIL PROTECTED] wrote:
> Python is a better language, with php support, anyway, but I am fed up
> with attitudes of comp.lang.perl.misc. Assholes in this newsgroup ruin
> Perl experience for everyone. Instead of being helpful, snide remarks,
> back-biting, scare tactings, and so on proliferate and self
> reinforce. All honest people have left this sad newsgroup. Buy bye,
> assholes, I am not going to miss you!!!

Considering that your total posting history according to DejaNews consists 
of exactly 3 posts (not including this last one) from 2001 to 2003 in NGs 
that are so closely related to programming as pregnancy, marriage, and 
cancer I believe the last sentiment is very mutual. After all, you didn't 
ever leave any trace in CLPM until today.

jue 


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


Re: TypeError: 'int' object is not callable for max(2,3)

2007-07-25 Thread Steve Holden
Arash Arfaee wrote:
> Hi all,
> I have a problem. if I enter max(2,3) before I run my program in command 
> line it returns 3. However if I start to debug my program, I have this 
> error:
> 
> [Dbg]>>> max(2,3)
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: 'int' object is not callable
> 
> Any idea what should be the reason?
> 
You have assigned an integer value to the name max, thereby shadowing 
the builtin function.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: first, second, etc line of text file

2007-07-25 Thread James Stroud
Daniel Nogradi wrote:
> A very simple question: I currently use a cumbersome-looking way of
> getting the first, second, etc. line of a text file:
> 
> for i, line in enumerate( open( textfile ) ):
>if i == 0:
>print 'First line is: ' + line
>elif i == 1:
>print 'Second line is: ' + line
>...
>...
> 
> I thought about f = open( textfile ) and then f[0], f[1], etc but that
> throws a TypeError: 'file' object is unsubscriptable.
> 
> Is there a simpler way?

This is the same logic but less cumbersome, if that's what you mean:

to_get = [0, 3, 7, 11, 13]
got = dict((i,s) for (i,s) in enumerate(open(textfile)) if i in to_get)
print got[3]

This would probably be the best way for really big files and if you know 
all of the lines you want ahead of time. If you need to access the file 
multiple times at arbitrary positions, you may need to seek(0), cache 
lines already read, or slurp the whole thing, which has already been 
suggested.

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Singleton in Python Cookbook

2007-07-25 Thread Diez B. Roggisch
Alex Popescu schrieb:
> Hi all!
> 
> I was reading through Python Cookbook the Singleton recipe. At this moment 
> I am a bit puzzled as the example in the book is not working resulting in:
> 
> TypeError: type.__new__(SingleSpam): SingleSpam is not a subtype of type
> 
> (I haven't presented the original code as I am not sure about copyrights).

AFAIK the cookbook is completely found online at ASPN. So no sweat 
publishing it here.


And regarding the problem: is it possible that you forgot to subclass 
SingleSpam from object?

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


Re: is_iterable function.

2007-07-25 Thread Steve Holden
Carsten Haese wrote:
> On Wed, 2007-07-25 at 19:26 +, Neil Cerutti wrote:
>> Speaking of the iter builtin function, is there an example of the
>> use of the optional sentinel object somewhere I could see?
> 
> Example 1: If you use a DB-API module that doesn't support direct cursor
> iteration with "for row in cursor", you can simulate it this way:
> 
> for row in iter(cursor.fetchone, None):
># do something
> 
[...]
This would, of course, be a horribly inefficient way to handle a 
database result with 1,500,000 rows. Calling fetchall() might also have 
its issues. The happy medium is to use a series of calls to fetchmany(N) 
with an appropriate value of N.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Why PHP is so much more popular for web-development

2007-07-25 Thread Steve Holden
Jeff McNeil wrote:
> Unfortunately, I also find that PHP programmers are usually more
> plentiful than their Python counterparts.  When thinking of staffing
> an organization, it's common to target a skill set that's cheaper to
> employ and easier to replace down the road if need be.
> 
Right, that's why hospitals are replacing their surgeons with butchers. 
There are so many more of them available. It's only cutting meat, after all.

> Also, larger hosting shops are hesitant to run things such as TG and
> Rails that require an additional server process.  The name of the game
> is density.  Sure, it may be easy to manage and run a TG project, but
> it's a pain to set one up on a shared hosting server.
> 
Virtualization will solve that problem.

> Lastly, I personally think it has something to do with the fact that
> so many of the popular, free, web applications are PHP based. It's
> easy for the average Web Administrator to get started with your
> standard PHP package. From there, picking up the language is the next
> logical step.
> 
There's some justice to that.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Why PHP is so much more popular for web-development

2007-07-25 Thread Steve Holden
walterbyrd wrote:
> On Jul 25, 2:12 pm, Carsten Haese <[EMAIL PROTECTED]> wrote:
> 
>> Also, CherryPy's requirements are very
>> minimal.
> 
> In terms of memory and CPU, maybe. But I think that *requires* apache
> 2.x and a very recent version of   mod_python. By web-hosting
> standards, those are very steep requirements.
> 
You are wrong. CherryPy is a standalone web server environment.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


TypeError: 'int' object is not callable for max(2,3)

2007-07-25 Thread Arash Arfaee

Hi all,
I have a problem. if I enter max(2,3) before I run my program in command
line it returns 3. However if I start to debug my program, I have this
error:

[Dbg]>>> max(2,3)
Traceback (most recent call last):
 File "", line 1, in 
TypeError: 'int' object is not callable

Any idea what should be the reason?


Cheers,
Arash
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Why PHP is so much more popular for web-development

2007-07-25 Thread Steve Holden
Carsten Haese wrote:
> On Wed, 2007-07-25 at 10:42 -0700, walterbyrd wrote:
>> "Once you start down the Dark path, forever will it dominate your
>> desiny. Consume you, it will."
>> - Yoda
>>
>> I'm fairly new to web-development, and I'm trying out different
>> technologies. Some people wonder why PHP is so popular, when the
>> language is flawed in so many ways. To me, it's obvious: it's because
>> it's much easier to get started with PHP, and once somebody gets
>> started with a particular language, that person is likely to stay with
>> that language.
> 
> That's a major reason, yes.
[...]
> What exactly could Python learn from PHP? PHP is a one-trick pony. It
> was designed for web applications. People claim they write desktop
> applications in PHP, but I don't believe them.
> 
> Python is more powerful and offers a lot more choices. In order for
> Python to become more like PHP, somebody would have to make One True Way
> of developing web applications in Python, and that's never going to
> happen.
> 
> Just my two cents,
> 
I had a client who produced AJAX-based electronic cash registers. For 
the second generation of their technology they decided to use some 
bastardized version of PHP with GUI capabilities bolted on. At that 
point we parted company. I literally couldn't help them.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Why PHP is so much more popular for web-development

2007-07-25 Thread Daniel
On Wed, 25 Jul 2007 20:42:54 +0300, walterbyrd <[EMAIL PROTECTED]>  
wrote:

> I'm fairly new to web-development, and I'm trying out different
> technologies. Some people wonder why PHP is so popular, when the
> language is flawed in so many ways. To me, it's obvious: it's because
> it's much easier to get started with PHP, and once somebody gets
> started with a particular language, that person is likely to stay with
> that language.

I think Python is the computer scientist based language, whereas PHP is  
for weekend hobbyists. Not to say you can't produce serious code with PHP  
(or quick and dirty code with Python).

Having used both, I can tell you that Python will take 10 times the  
initial effort to produce the same functionality as a PHP implementation -  
since Python programmers will not opt for quick hacks and workarounds like  
PHP coders will. The trade off however is that Python code is much more  
readable and 100 times more maintainable in the long run, which I consider  
more important.

However this is the problem: Web Development is not about being perfect,  
it's about getting your application to production as quick as possible,  
worrying about bugs and added functionality later on. No good putting your  
idea on the web 6 months after your competitor has taken all the market  
share. PHP lets you do this very quickly, Python does not. I find myself  
trying to 'finish' the Python app whereas in PHP I would have already gone  
live.

Today I've found the best approach for me is a hybrid solution. Since  
database models are quite definitive - it doesn't matter if I use PHP or  
Python, the underlying datastructure for my app won't change. Therefore,  
using a library of custom helpers and framework-like tools for PHP, I can  
create a working site in less than a couple days in PHP. This is made live.

Then I have the time to rewrite the app in Python, which will take me a  
couple weeks, but due to the much better language properties of Python,  
will mean that I can also maintain it a year after writing it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Singleton in Python Cookbook

2007-07-25 Thread Alex Popescu
Hi all!

I was reading through Python Cookbook the Singleton recipe. At this moment 
I am a bit puzzled as the example in the book is not working resulting in:

TypeError: type.__new__(SingleSpam): SingleSpam is not a subtype of type

(I haven't presented the original code as I am not sure about copyrights).

bests,
./alex
--
.w( the_mindstorm )p.

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


Re: Why PHP is so much more popular for web-development

2007-07-25 Thread Carsten Haese
On Wed, 2007-07-25 at 13:55 -0700, walterbyrd wrote:
> On Jul 25, 2:12 pm, Carsten Haese <[EMAIL PROTECTED]> wrote:
> 
> > Also, CherryPy's requirements are very
> > minimal.
> 
> In terms of memory and CPU, maybe. But I think that *requires* apache
> 2.x and a very recent version of   mod_python. By web-hosting
> standards, those are very steep requirements.

Apache 2 came out 5 years ago. I wouldn't trust a web hosting provider
who can't be bothered to install software that's been out for 5 years to
stay up to date on security patches. You get what you pay for.

Also, CherryPy does not *require* Apache. It supplies its own web
server. Getting that server to run on a shared host may be a problem,
but it is incorrect to state that CherryPy *requires* Apache 2.

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


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


Re: first, second, etc line of text file

2007-07-25 Thread Grant Edwards
On 2007-07-25, Jeff <[EMAIL PROTECTED]> wrote:

> That might be a memory problem if you are running multiple processes
> regularly, such as on a webserver.

I suppose if you did it in parallel 50 processes, you could use
up 250MB of RAM.  Still not a big deal on many servers.  A
decent OS will swap regions that aren't being used to disk, so
it's likely not to be a problem.  

If you're talking several hundred instances, you could start to
use up serios amounts of VM. Still, I say do it the simple,
obvious way first, and optimize it _after_ you've determined
you have a performance problem (and determined where the
bottleneck is).  Premature optimization...

-- 
Grant Edwards   grante Yow! This PORCUPINE knows
  at   his ZIPCODE ... And he has
   visi.com"VISA"!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is_iterable function.

2007-07-25 Thread Marc 'BlackJack' Rintsch
On Wed, 25 Jul 2007 15:46:14 -0400, Carsten Haese wrote:

> On Wed, 2007-07-25 at 19:11 +, Marc 'BlackJack' Rintsch wrote:
>> And just calling `iter()` doesn't work either:
>> 
>> In [72]: class A:
>>: def __getitem__(self, key):
>>: if key == 42:
>>: return 'answer'
>>: raise KeyError
>>:
>> 
>> In [73]: iter(A())
>> Out[73]: 
>> 
>> In [74]: a = iter(A())
>> 
>> In [75]: a.next()
>> ---
>> Traceback (most recent call last)
>> 
>> /home/bj/ in ()
>> 
>> /home/bj/ in __getitem__(self, key)
>> 
>> :
>> 
>> 
>> So there's no reliable way to test for "iterables" other than actually
>> iterate over the object.
> 
> You seem to say that your 'a' object is not iterable. I disagree. While
> it's true that it raises an exception upon retrieval of the zeroth
> iteration, that situation is quite different from attempting to iterate
> over the number 10, where you can't even ask for a zeroth iteration.

But it raises that exception on every attempt to iterate and was clearly
not meant to be iterable.  The docs say objects that offer no `__iter__()`
but a `__getitem__()` are iterable if this `__getitem__()` can be called
with consecutive integers from zero up and if there is an upper limit it
must be signaled by an `IndexError`.  The object above doesn't follow this
protocol.  For me an "iterable" is about behavior.  If it doesn't quack
like a duck…

> To illustrate this point further, imagine you write an object that
> iterates over the lines of text read from a socket. If the connection is
> faulty and closes the socket before you read the first line, the zeroth
> iteration raises an exception. Does that mean the object is iterable or
> not depending on the reliability of the socket connection? I find that
> notion hard to swallow.

It is an iterable as there is at least the chance or the intent of the
programmer that it will behave like an iterable.  The duck tries hard to
quack but may be hoarse.  :-)

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

Re: I am giving up perl because of assholes on clpm -- switching to Python

2007-07-25 Thread James Stroud
[EMAIL PROTECTED] wrote:
> Python is a better language, with php support, anyway, but I am fed up
> with attitudes of comp.lang.perl.misc. Assholes in this newsgroup ruin
> Perl experience for everyone. Instead of being helpful, snide remarks,
> back-biting, scare tactings, and so on proliferate and self
> reinforce. All honest people have left this sad newsgroup. Buy bye,
> assholes, I am not going to miss you!!!
> 
> Martha

You have convinced me to subscribe to clpm! Sounds like it will be fun 
reading.

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: first, second, etc line of text file

2007-07-25 Thread Bjoern Schliessmann
Grant Edwards wrote:
> On 2007-07-25, Jeff McNeil <[EMAIL PROTECTED]> wrote:
 
>> Depending on the size of your file, you can just use
>> file.readlines. Note that file.readlines is going to read the
>> entire file into memory, so don't use it on your plain-text
>> version of War and Peace.
> 
> I don't think that would actually be a problem for any recent
> machine.
> 
> The Project Gutenberg version of W&P is 3.1MB of text in 67403
> lines.  I just did an f.readlines() on it and it was pretty
> much instantaneous, and the python interpreter instance that
> contains that list of 67403 lines is using a bit less than 8MB
> of RAM. 

YMMD :)

Regards,


Björn

-- 
BOFH excuse #335:

the AA battery in the wallclock sends magnetic interference

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


Re: I am giving up perl because of assholes on clpm -- switching to Python

2007-07-25 Thread Abigail
   _
[EMAIL PROTECTED] ([EMAIL PROTECTED]) wrote on VLXXVI September
MCMXCIII in news:[EMAIL PROTECTED]>:
}}  Python is a better language, with php support, anyway, but I am fed up
}}  with attitudes of comp.lang.perl.misc. Assholes in this newsgroup ruin
}}  Perl experience for everyone.

Bullshit. Over 99.9% of the Perl users have never read a single article
in comp.lang.perl.misc, and never will.

}}Instead of being helpful, snide remarks,
}}  back-biting, scare tactings, and so on proliferate and self
}}  reinforce. All honest people have left this sad newsgroup. Buy bye,
}}  assholes, I am not going to miss you!!!

No longer reading a newsgroup because you don't like the way people
act in the group is one thing (and a sensible thing as well), but
your action is like switching from coffee to tea because you don't
like the people in rec.food.drink.coffee. 



Abigail
-- 
perl -wle 'print "Prime" if (0 x shift) !~ m 0^\0?$|^(\0\0+?)\1+$0'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why PHP is so much more popular for web-development

2007-07-25 Thread walterbyrd
On Jul 25, 2:12 pm, Carsten Haese <[EMAIL PROTECTED]> wrote:

> Also, CherryPy's requirements are very
> minimal.

In terms of memory and CPU, maybe. But I think that *requires* apache
2.x and a very recent version of   mod_python. By web-hosting
standards, those are very steep requirements.

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


Re: first, second, etc line of text file

2007-07-25 Thread Jeff
Grant,

That might be a memory problem if you are running multiple processes
regularly, such as on a webserver.

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


Re: Why PHP is so much more popular for web-development

2007-07-25 Thread walterbyrd
On Jul 25, 2:10 pm, Jeff <[EMAIL PROTECTED]> wrote:

> I can tell you exactly why PHP
> is so popular: it acts as an extension of HTML and is syntactically
> similar to Perl.
>

Although, that can lead to problems, if you're not careful:

Perl:
my $x = 5 + 9000 || 1; # $x is 9005

PHP:
$x = 5 + 9000 || 1; # $x is 6...

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


Re: I am giving up perl because of assholes on clpm -- switching to Python

2007-07-25 Thread James Matthews

Welcome aboard

On 7/25/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:


Python is a better language, with php support, anyway, but I am fed up
with attitudes of comp.lang.perl.misc. Assholes in this newsgroup ruin
Perl experience for everyone. Instead of being helpful, snide remarks,
back-biting, scare tactings, and so on proliferate and self
reinforce. All honest people have left this sad newsgroup. Buy bye,
assholes, I am not going to miss you!!!

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





--
http://www.goldwatches.com/watches.asp?Brand=55
http://www.jewelerslounge.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: first, second, etc line of text file

2007-07-25 Thread Grant Edwards
On 2007-07-25, Jeff McNeil <[EMAIL PROTECTED]> wrote:

> Depending on the size of your file, you can just use
> file.readlines. Note that file.readlines is going to read the
> entire file into memory, so don't use it on your plain-text
> version of War and Peace.

I don't think that would actually be a problem for any recent
machine.  

The Project Gutenberg version of W&P is 3.1MB of text in 67403
lines.  I just did an f.readlines() on it and it was pretty
much instantaneous, and the python interpreter instance that
contains that list of 67403 lines is using a bit less than 8MB
of RAM. An "empty" interpreter uses about 2.7MB. So, doing
f.readlines() on War and Peace requires a little over 5MB of RAM
-- not really much of a concern on any machine that's likely to
be running Python.

-- 
Grant Edwards   grante Yow! Now I understand the
  at   meaning of "THE MOD SQUAD"!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Bug in cPickle with packages and 'object' inherited class

2007-07-25 Thread Conrado PLG
Say you have this structure:

pna/
__init__.py
model.py


__init__.py is empty.

model.py is:


import cPickle as pickle

class A(object):
pass

def serialize():
pickle.dump(A(), open('temp.dat', 'wb'))


Now open a python interpreter on the root directory of that structure
and type:


import pna.model
pna.model.serialize()


The following exception is thrown:


Traceback (most recent call last):
  File "test.py", line 2, in 
pna.model.serialize()
  File "...\pna\model.py", line 7, in serialize
pickle.dump(A(), open('temp.dat', 'wb'))
cPickle.PicklingError: Can't pickle : import of
module pna.model failed


If you use 'pickle' instead of 'cPickle', it works.
If you don't inherit from 'object' in 'A', it works.

I'm using Python 2.5.1 on Windows XP. I've tested in Python 2.4.4 on
Linux and it works.

Any ideas of what is going on?

Thanks,
Conrado

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


Re: first, second, etc line of text file

2007-07-25 Thread Daniel Nogradi
Thanks all! I think I will stick to my original method because the
files can be quite large and without reading the whole file into
memory probably enumerate( open( textfile ) ) is the only way to
access an arbitrary Nth line.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: first, second, etc line of text file

2007-07-25 Thread George Sakkis
On Jul 25, 3:44 pm, "Daniel Nogradi" <[EMAIL PROTECTED]> wrote:

> A very simple question: I currently use a cumbersome-looking way of
> getting the first, second, etc. line of a text file:
>
> for i, line in enumerate( open( textfile ) ):
> if i == 0:
> print 'First line is: ' + line
> elif i == 1:
> print 'Second line is: ' + line
> ...
> ...
>
> I thought about f = open( textfile ) and then f[0], f[1], etc but that
> throws a TypeError: 'file' object is unsubscriptable.
>
> Is there a simpler way?

If all you need is sequential access, you can use the next() method of
the file object:

nextline = open(textfile).next
print 'First line is: %r' % nextline()
print 'Second line is: %r' % nextline()
...

For random access, the easiest way is to slurp all the file in a list
using file.readlines().

HTH,
George

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


Re: Why PHP is so much more popular for web-development

2007-07-25 Thread Jeff
I'm an ex-PHP programmer (well, I still have to use some PHP at work,
but I don't tell anyone that at parties) who now uses Python or Lisp
wherever possible for web development.  I can tell you exactly why PHP
is so popular: it acts as an extension of HTML and is syntactically
similar to Perl.

PHP mixes with HTML and removes the separation of model and view.  It
has its roots in strictly procedural code (and its OO colors were
obviously painted on later), which is simple for non-programmers or
beginning programmers to understand.  When considered from the
standpoint of a template language, it's a wonderful language.  When
considered as a real programming environment, its limitations show.

PHP began as a series of Perl scripts.  If you have ever looked at a
huge PHP project, it looks just as unreadable as a huge Perl project.
But there is a large number of programmers who began writing Perl-
based CGI for the web, and PHP was a very natural next step for them.
This is also a big reason why Ruby is popular among the same crowd
(...I say as I duck the inevitable flame war I've just started).  Ruby
takes a lot of concepts from Perl and tries to make them work in an OO
framework (the ~ operator and the built in regex type, for instance).

I started with PHP for both of those reasons.  Perl was becoming too
much of a chore and PHP offered a solution without learning a new
templating language: a way to embed perl code in the page itself.

Of course, now I am in recovery and am proceeding well with my 12
steps, thanks for asking.

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


Re: first, second, etc line of text file

2007-07-25 Thread Jeff McNeil
Depending on the size of your file, you can just use file.readlines.
Note that file.readlines is going to read the entire file into memory,
so don't use it on your plain-text version of War and Peace.

>>> f = open("/etc/passwd")
>>> lines = f.readlines()
>>> lines[5]
'# lookupd DirectoryServices  \n'
>>>

You can also check out the fileinput module. That ought to be sightly
more efficient and provides some additional functionality.  I think
there are some restrictions on accessing lines out of order, though.

-Jeff

On 7/25/07, Daniel Nogradi <[EMAIL PROTECTED]> wrote:
> A very simple question: I currently use a cumbersome-looking way of
> getting the first, second, etc. line of a text file:
>
> for i, line in enumerate( open( textfile ) ):
> if i == 0:
> print 'First line is: ' + line
> elif i == 1:
> print 'Second line is: ' + line
> ...
> ...
>
> I thought about f = open( textfile ) and then f[0], f[1], etc but that
> throws a TypeError: 'file' object is unsubscriptable.
>
> Is there a simpler way?
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why PHP is so much more popular for web-development

2007-07-25 Thread Carsten Haese
On Wed, 2007-07-25 at 12:34 -0700, walterbyrd wrote:
> On Jul 25, 12:40 pm, Carsten Haese <[EMAIL PROTECTED]> wrote:
> 
> > What exactly could Python learn from PHP?
> 
> Remember, I'm a noob, I'm not trolling.

I know.

> When I posted "Python" I meant the Python web-developement world. In
> particular, python frameworks, like CherryPy, have requirements that
> are not realistic for most shared hosting plans.

CherryPy is not a framework. Also, CherryPy's requirements are very
minimal. You either need a "vanilla" Apache/mod_python setup (which is
no harder to set up than a vanilla Apache/PHP setup), or just Python
itself if you use the webserver that is in CherryPy.

> Maybe I'm wrong, but I often get the idea that those  who develop
> python frameworks don't give a thought to the realities of shared
> hosting. They seem to think that everybody has complete control over
> the server. Things are very different in the PHP universe.

Again, CherryPy is not a web programming framework. It is a web server
that "publishes" object methods.

Also, things are only easy in the PHP world if you only use the modules
that the hosting provider pre-installed. I doubt you'll easily find a
PHP hosting provider that will allow connections to Informix or Oracle
databases.

> To use codeignitor as an example, again. On the "why  codeignitor"
> part of the welcome page you will find:
> 
> ---
> CodeIgniter is right for you if...
> * You need broad compatibility with standard hosting accounts that run
> a variety of PHP versions and configurations.
> * You want a framework that requires nearly zero configuration.
> * You want a framework that does not require you to use the command
> line.
> ---
> 
> I don't seem to see Python frameworks using those sorts of selling
> points. Posting as a noob, who is struggling to get django configured
> on dreamhost, I gotta tell 'ya: those selling points look awfully
> attractive.
> 
> The point is: PHP framework makers are very considerate of the
> realities of shared hosting.

It may look like that to you, but that's not a property of the PHP
language. I haven't seen CodeIgniter, but I imagine it's easy for you to
set up because it's already installed by the hosting provider, which is
due to PHP's popularity. If you could find a provider that can give you
an out-of-the-box Django or TG set up, you'd probably find that just as
easy. Finding a hosting provider that'll do this is the problem, of
course, but that's not because these frameworks are designed to be hard
to install. It's just that most providers don't pre-install these
frameworks because there isn't enough demand.

>  Python framework makers don't seem to
> give it a thought.

Python framework makers have no influence over what web hosting
providers do.

>  Just maybe, that's something that Python could
> learn from PHP.

What is "that", and what can Python developers do to learn "that"?

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


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


Re: Why PHP is so much more popular for web-development

2007-07-25 Thread Paul McNett
Steve Holden wrote:
> When someone starts to push the limits of PHP they either continue to 
> push until they get where they want to be (producing an ugly or 
> ill-maintained bunch of code along the way) or they choose a more 
> appropriate tool.
> 
> The latter behavior is typical of programmers. The former is typical of 
> typical users. There are many people producing web sites who I wouldn't 
> let within yards of any of my code. but it's some kind of tribute to PHP 
> that it manages to satisfy so many of them. This doesn't mean that 
> grafting PHP features into Python mindlessly will improve the language.
> 
> The Python approach is a scalpel, which can easily cut your fingers off. 
> The PHP approach is a shovel, which will do for many everyday tasks.

Exactly right on. I actually use PHP quite a bit. For websites that 
would otherwise be static html pages other than the fact that I want to 
reuse elements (header, footer, etc.), I choose PHP in a heartbeat, 
because it's easy, and I'm lazy. Ditto if it is a simple db-driven site.

Start adding business rules and complex program flow and I run away from 
PHP as fast as I can. I wouldn't want to actually code anything in it, 
after all. ;)

I've seen comments that mod_python is hard to use, but I just haven't 
found that to be the case. For me, mod_python is the next step up when 
PHP no longer suits my needs. Granted, I'm spoiled because I run my own 
server and don't rely on some hosting provider to tell me what I can and 
cannot do. :)

-- 
pkm ~ http://paulmcnett.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is_iterable function.

2007-07-25 Thread George Sakkis
On Jul 25, 3:26 pm, Neil Cerutti <[EMAIL PROTECTED]> wrote:

> Speaking of the iter builtin function, is there an example of the
> use of the optional sentinel object somewhere I could see?

# iterate over random numbers from 1 to 10; use 0 as a sentinel to
stop the iteration
for n in iter(lambda:random.randrange(10), 0):
print n

More generally, iter(callable, sentinel) is just a convenience
function for the following generator:

def iter(callable, sentinel):
while True:
c = callable()
if c == sentinel: break
yield c


George

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


Re: is_iterable function.

2007-07-25 Thread Neil Cerutti
On 2007-07-25, Carsten Haese <[EMAIL PROTECTED]> wrote:
> On Wed, 2007-07-25 at 19:26 +, Neil Cerutti wrote:
>> Speaking of the iter builtin function, is there an example of the
>> use of the optional sentinel object somewhere I could see?
>
> Example 1: If you use a DB-API module that doesn't support direct cursor
> iteration with "for row in cursor", you can simulate it this way:
>
> for row in iter(cursor.fetchone, None):
># do something
>
> Example 2: Reading a web page in chunks of 8kB:
>
> f = urllib.urlopen(url)
> for chunk in iter(lambda:f.read(8192), ""):
>   # do something

Ah! Thanks for the examples. That's much simpler than I was
imagining. It's also somewhat evil, but I suppose it conserves a
global name to do it that way.

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


Re: first, second, etc line of text file

2007-07-25 Thread Jeff
Files should be iterable on their own:

filehandle = open('/path/to/foo.txt')
for line in filehandle:
# do something...

But you could also do a generic lines = filehandle.readlines(), which
returns a list of all lines in the file, but that's a bit memory
hungry.

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


Re: Why PHP is so much more popular for web-development

2007-07-25 Thread Christoph Haas
On Wed, Jul 25, 2007 at 12:34:08PM -0700, walterbyrd wrote:
> When I posted "Python" I meant the Python web-developement world. In
> particular, python frameworks, like CherryPy, have requirements that
> are not realistic for most shared hosting plans.

It's true that the requirements are higher than what the old-school
CGI/PHP web hosters offer. But with todays virtual root servers it's
really inexpensive to run such a server. And using frameworks allows you
to control all aspects of the web serving like URL dispatching, error
handling and is probably even faster than PHP because necessary
resources (like database connections) are initalized upon startup of the
web application. PHP and CGIs do this everytime they get called.

> Maybe I'm wrong, but I often get the idea that those  who develop
> python frameworks don't give a thought to the realities of shared
> hosting. They seem to think that everybody has complete control over
> the server. Things are very different in the PHP universe.

Without wanting to sound arrogant: it's my belief that web hosters just
offering htdocs/PHP will probably just be useful for the noob-customers
who have no idea of operating systems but just want their blinking
personal homepage online.

There are good PHP applications and I wouldn't want to give up
phpmyadmin or squirrelmail. But with today's demand for fully
controllable interactive (you will never hear me propagate that bullshit
buzzword "Web x.0") web sites a framework seems to be a viable way.
For me PHP has a bitter taste of "easy enough for every noob to use it"
which makes it the language the most insecure applications are written
in.

> The point is: PHP framework makers are very considerate of the
> realities of shared hosting. Python framework makers don't seem to
> give it a thought. Just maybe, that's something that Python could
> learn from PHP.

Perhaps. But the hosting market changes. And I believe that PHP suits
the simpler applications better. I would point a beginner in web
programming more likely to PHP than torture them with frameworks. It's
just too heavy. OTOH full-featured frameworks are way more complicated
and have eviler requirements but there are hardly any limitation on the
kinds of sites you can power with them.

EO2¢

Cheers
 Christoph

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


I am giving up perl because of assholes on clpm -- switching to Python

2007-07-25 Thread Martha_Jones
Python is a better language, with php support, anyway, but I am fed up
with attitudes of comp.lang.perl.misc. Assholes in this newsgroup ruin
Perl experience for everyone. Instead of being helpful, snide remarks,
back-biting, scare tactings, and so on proliferate and self
reinforce. All honest people have left this sad newsgroup. Buy bye,
assholes, I am not going to miss you!!!

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


Re: is_iterable function.

2007-07-25 Thread Neil Cerutti
On 2007-07-25, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> So there's no reliable way to test for "iterables" other than
> actually iterate over the object.

A TypeError exception is perhaps too generic for comfort in this
use case:

def deeply_mapped(func, iterable):
  for item in iterable:
try:
  for it in flattened(item):
yield func(it)
except TypeError:
  yield func(item)

I'd be more confortable excepting some sort of IterationError (or
using an is_iterable function, of course). I guess there's always
itertools. ;)

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


Re: is_iterable function.

2007-07-25 Thread Duncan Booth
Neil Cerutti <[EMAIL PROTECTED]> wrote:

> Speaking of the iter builtin function, is there an example of the
> use of the optional sentinel object somewhere I could see?

for line in iter(open('somefile.txt', 'r').readline, ''):
print line

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


Re: adding a docstring to an instancemethod

2007-07-25 Thread Gabriel Genellina
En Wed, 25 Jul 2007 08:05:37 -0300, jelle <[EMAIL PROTECTED]>  
escribió:

> I'm working on documenting wrapped C++ methods.
> The thing is that I'd like to add docstrings to a method, but python
> won't allow me to:
> TypeError: attribute '__doc__' of 'instancemethod' objects is not
> writable

Set the __doc__ on the *function* from which you build the instance method.

-- 
Gabriel Genellina

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


Re: is_iterable function.

2007-07-25 Thread Carsten Haese
On Wed, 2007-07-25 at 19:26 +, Neil Cerutti wrote:
> Speaking of the iter builtin function, is there an example of the
> use of the optional sentinel object somewhere I could see?

Example 1: If you use a DB-API module that doesn't support direct cursor
iteration with "for row in cursor", you can simulate it this way:

for row in iter(cursor.fetchone, None):
   # do something

Example 2: Reading a web page in chunks of 8kB:

f = urllib.urlopen(url)
for chunk in iter(lambda:f.read(8192), ""):
  # do something

HTH,

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


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


  1   2   3   >