Friday, April 2, 2010

comp.lang.python - 25 new messages in 8 topics - digest

comp.lang.python
http://groups.google.com/group/comp.lang.python?hl=en

comp.lang.python@googlegroups.com

Today's topics:

* (a==b) ? 'Yes' : 'No' - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/b985d5727945d2b4?hl=en
* Is it possible to store data in a Python file in a way similar to Ruby's __
END__ section? - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/2c546676032d5e3f?hl=en
* Getting Local MAC Address - 7 messages, 4 authors
http://groups.google.com/group/comp.lang.python/t/876b51563e5c0ec5?hl=en
* Splitting a string - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/f4133c2d3583357a?hl=en
* off topic but please forgive me me and answer - 6 messages, 4 authors
http://groups.google.com/group/comp.lang.python/t/0d4f564a49022b74?hl=en
* C-style static variables in Python? - 4 messages, 4 authors
http://groups.google.com/group/comp.lang.python/t/ce1a7abe2f3816b9?hl=en
* Generating text from a regular expression - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/c16f904e698a42b3?hl=en
* psycopg2 / psycopg2.ProgrammingError: syntax error at or near "E'mytable'" -
2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/52208bb7a4b2e338?hl=en

==============================================================================
TOPIC: (a==b) ? 'Yes' : 'No'
http://groups.google.com/group/comp.lang.python/t/b985d5727945d2b4?hl=en
==============================================================================

== 1 of 2 ==
Date: Fri, Apr 2 2010 1:48 pm
From: Patrick Maupin


On Apr 2, 3:12 pm, kj <no.em...@please.post> wrote:
> Is that for real???  It's the QWERTY rationale all over again.  Swell.

Well, bearing in mind that everybody seems to have an agenda, so you
can't (or shouldn't, anyway) take all your news from a single source,
it may be that the common wisdom about the QWERTY thing is incorrect:

http://reason.com/archives/1996/06/01/typing-errors

I have to confess that I haven't done any real deep research on the
subject, but yet again, we find there is more than one side to a
story.

Regards,
Pat


== 2 of 2 ==
Date: Fri, Apr 2 2010 5:53 pm
From: Steven D'Aprano


On Fri, 02 Apr 2010 20:12:59 +0000, kj wrote:

> In <mailman.1326.1269971785.23598.python-list@python.org> Steve Holden
> <steve@holdenweb.com> writes:
[...]
>>Yes, that's deliberately awful syntax. Guido designed it that way to
>>ensure that people didn't aver-use it, thereby reducing the readability
>>of Python applications.
>
> Is that for real??? It's the QWERTY rationale all over again. Swell.

Not according to the PEP. No fewer than 16 alternatives were put to a
vote, and with no clear winner (but many obvious losers) Guido made the
final decision.

http://www.python.org/dev/peps/pep-0308/

Although the results of the voting are given, unaccountably no final
tally was given. Possibly because nobody could agree on how to tally the
votes. Using a simple counting procedure (I give 3 votes for a rank1
vote, 2 votes for a rank2 and 1 for a rank3, signed according to whether
it was an Accept or Reject vote) I find the top four candidates were:

C. (if C: x else: y) 27%
D. C ? x : y 20%
B. if C then x else y 13%
A. x if C else y 11%

with everything else an order of magnitude smaller (6% or less). If you
choose a different voting scheme, no doubt you will get different results.

Since no candidate syntax got a majority of the vote, it came down to the
only vote that really mattered: Guido's.

Ankh-Morpork had dallied with many forms of government
and had ended up with that form of democracy known as
One Man, One Vote. The Patrician was the Man; he had the
Vote. -- (T. Pratchett, "Mort")


Guido did say "Note that all these are intentionally ugly" but this was
followed by a smiley and was obviously tongue-in-cheek.

http://mail.python.org/pipermail/python-dev/2005-September/056846.html


> "Let's preserve readability by making the syntax so ugly that people
> won't use it."??? That's just perverse. (It would have been more
> reassuring if the reason had been simply that Guido has an inexplicable
> dislike of ternary expressions just like one may have an inexplicable
> dislike of Broadway musicals.)

"Inexplicable"? They're musicals, and they're on Broadway. Surely that's
two good reasons to dislike them *wink*


> Second, sticking the test between the two alternatives goes against a
> vast tradition in programming languages.

As I've pointed out before, it is natural syntax in English. Not
necessarily the most common, but common enough to be completely
unexceptional:

"I'll be there in ten minutes, if I can find a parking space close by,
otherwise you should start without me."

--
Steven

==============================================================================
TOPIC: Is it possible to store data in a Python file in a way similar to Ruby'
s __END__ section?
http://groups.google.com/group/comp.lang.python/t/2c546676032d5e3f?hl=en
==============================================================================

== 1 of 1 ==
Date: Fri, Apr 2 2010 1:52 pm
From: Stephen Hansen


On 2010-04-02 13:08:00 -0700, Christopher Roach said:

> I have a script that I am working on to process a bunch of data. A
> good portion of the Tk-based GUI is driven by a large set of YAML data
> and I'd love to store that data inside of the script so that I can
> send just a single file to my colleague. Ruby has a mechanism for
> doing this whereby I can load the data by doing a YAML.load(DATA)
> which loads everything in the file after the __END__ keyword (for a
> better explanation of this see http://bit.ly/V9w8m). I was wondering
> if anyone knew of a way to do something similar in Python?

If its just like a YAML file or such, the idiomatic thing to do is just
use a triple-quoted string, I think.

Such as:

DATA="""
My stuff
and stuff
and more stuff
and other stuff"""

If you're wanting to include binary stuff like images, that gets more
complicated. I've seen it done a couple different ways, but usually
storing as above but base64 encoding the strings first.

Anything more, and its usually time to start packaging the thing wiht
py2exe or similar things :)

Now, one concern you may have is order-- you may not want this stuff on
top of your script, but instead on the bottom so its sort of 'out of
the way'. For that, I'd do like:

import YAML

def random_thing(arg):
return arg + 1

def main():
config = YAML.load(DATA)

# Code ends

DATA="""
blah blah
blah"""

# Bootstrap

if __name__ == "__main__":
main()

--
--S

... p.s: change the ".invalid" to ".com" in email address to reply privately.


==============================================================================
TOPIC: Getting Local MAC Address
http://groups.google.com/group/comp.lang.python/t/876b51563e5c0ec5?hl=en
==============================================================================

== 1 of 7 ==
Date: Fri, Apr 2 2010 1:52 pm
From: "danmcleran@yahoo.com"


On Apr 2, 2:14 pm, Booter <colo.av...@gmail.com> wrote:
> Hello all,
>
> I am new to python ans was wondering if there was a way to get the mac
> address from the local NIC?
>
> Thanks for your help.
>
> Gerad

for windows parse p.stdout.read():

import subprocess

p = subprocess.Popen('ipconfig', shell = True, stdout =
subprocess.PIPE)

p.wait()

print p.stdout.read()


== 2 of 7 ==
Date: Fri, Apr 2 2010 1:55 pm
From: "danmcleran@yahoo.com"


On Apr 2, 2:52 pm, "danmcle...@yahoo.com" <danmcle...@yahoo.com>
wrote:
> On Apr 2, 2:14 pm, Booter <colo.av...@gmail.com> wrote:
>
> > Hello all,
>
> > I am new to python ans was wondering if there was a way to get the mac
> > address from the local NIC?
>
> > Thanks for your help.
>
> > Gerad
>
> for windows parse p.stdout.read():
>
> import subprocess
>
> p = subprocess.Popen('ipconfig', shell = True, stdout =
> subprocess.PIPE)
>
> p.wait()
>
> print p.stdout.read()

sorry, posted too soon. looks like this is for ip address only.


== 3 of 7 ==
Date: Fri, Apr 2 2010 1:59 pm
From: Irmen de Jong


On 2-4-2010 22:55, danmcleran@yahoo.com wrote:
> On Apr 2, 2:52 pm, "danmcle...@yahoo.com"<danmcle...@yahoo.com>
> wrote:
>> On Apr 2, 2:14 pm, Booter<colo.av...@gmail.com> wrote:
>>
>>> Hello all,
>>
>>> I am new to python ans was wondering if there was a way to get the mac
>>> address from the local NIC?
>>
>>> Thanks for your help.
>>
>>> Gerad
>>
>> for windows parse p.stdout.read():
>>
>> import subprocess
>>
>> p = subprocess.Popen('ipconfig', shell = True, stdout =
>> subprocess.PIPE)
>>
>> p.wait()
>>
>> print p.stdout.read()
>
> sorry, posted too soon. looks like this is for ip address only.

Actually you can get more info including the MAC address when you pass
the /all switch.

-irmen

== 4 of 7 ==
Date: Fri, Apr 2 2010 1:58 pm
From: "danmcleran@yahoo.com"


On Apr 2, 2:52 pm, "danmcle...@yahoo.com" <danmcle...@yahoo.com>
wrote:
> On Apr 2, 2:14 pm, Booter <colo.av...@gmail.com> wrote:
>
> > Hello all,
>
> > I am new to python ans was wondering if there was a way to get the mac
> > address from the local NIC?
>
> > Thanks for your help.
>
> > Gerad
>
> for windows parse p.stdout.read():
>
> import subprocess
>
> p = subprocess.Popen('ipconfig', shell = True, stdout =
> subprocess.PIPE)
>
> p.wait()
>
> print p.stdout.read()

try this instead:

import subprocess

p = subprocess.Popen('ipconfig /all', shell = True, stdout =
subprocess.PIPE)

p.wait()

print p.stdout.read()

== 5 of 7 ==
Date: Fri, Apr 2 2010 2:48 pm
From: Michael Torrie


On 04/02/2010 03:30 PM, Dan McLeran wrote:
> i'm running python 2.6 on win xp sp3 and i get:

Your code isn't portable to non-Windows OS's. On my Mac and on my Linux
workstations it simply doesn't work. Using '/usr/sbin/ifconfig' as the
executable name in Popen does work, however.

The OP didn't state his platform, so we shouldn't assume that a
windows-only solution will work for him may.

Since this list covers the use of many kinds of operating systems, it is
foolish to make assumptions. This was my point.


== 6 of 7 ==
Date: Fri, Apr 2 2010 2:51 pm
From: Michael Torrie


On 04/02/2010 02:14 PM, Booter wrote:
> I am new to python ans was wondering if there was a way to get the mac
> address from the local NIC?

As Dan has indicated, you have to Popen an external command to get this
information. Every OS has different commands and syntaxes for this.
You'll have to have a different Popen for each operating system. Also
you must take into account that most computers have more than one
ethernet interface these days (real and virtual). So you'll likely end
up with between 2 and 5 different MAC addresses. And some of those are
fake as well, like the MAC addresses used by VMware's virtual networking
interfaces.

What operating system are you targeting? Windows? Linux? Mac? To
really answer your question you must supply more information.


== 7 of 7 ==
Date: Fri, Apr 2 2010 3:18 pm
From: Steve Holden


Booter wrote:
> Hello all,
>
> I am new to python ans was wondering if there was a way to get the mac
> address from the local NIC?
>
> Thanks for your help.
>
>>> import uuid
>>> uuid.getnode()
246090452741227L
>>>

This is supposed to return the MAC address, but I am not sure it does.
The documentation says:

"""
getnode( )

Get the hardware address as a 48-bit positive integer. The first time
this runs, it may launch a separate program, which could be quite slow.
If all attempts to obtain the hardware address fail, we choose a random
48-bit number with its eighth bit set to 1 as recommended in RFC 4122.
"Hardware address" means the MAC address of a network interface, and on
a machine with multiple network interfaces the MAC address of any one of
them may be returned.
"""

So the return value isn't *guaranteed* to be an ethernet address, and
I'm not sure whether that code gets any regular testing.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/


==============================================================================
TOPIC: Splitting a string
http://groups.google.com/group/comp.lang.python/t/f4133c2d3583357a?hl=en
==============================================================================

== 1 of 2 ==
Date: Fri, Apr 2 2010 2:32 pm
From: Peter Otten <__peter__@web.de>


Thomas Heller wrote:

> Thanks to all for these code snippets. Peter's solution is the winner -
> most elegant and also the fastest. With an additional list comprehension
> to remove the possible empty strings at the start and at the end I get
> 16 us. Interesting is that Xavier's solution (which is similar to
> some code that I wrote myself) isn't so much slower; it get timings of
> around 22 us.

Deleting the first or last item is probably faster than looping over the
whole list. If there aren't any empty strings the overhead is constant.

_split = re.compile(r"(\d+)").split
def split(s):
if not s:
return ()
parts = _split(s)
parts[1::2] = map(int, parts[1::2])
if parts[-1] == "":
del parts[-1]
if parts[0] == "":
del parts[0]
return tuple(parts)

Peter


== 2 of 2 ==
Date: Fri, Apr 2 2010 3:53 pm
From: Patrick Maupin


On Apr 2, 4:32 pm, Peter Otten <__pete...@web.de> wrote:

> _split = re.compile(r"(\d+)").split
> def split(s):
>     if not s:
>         return ()
>     parts = _split(s)
>     parts[1::2] = map(int, parts[1::2])
>     if parts[-1] == "":
>         del parts[-1]
>     if parts[0] == "":
>         del parts[0]
>     return tuple(parts)
>

That's certainly faster than a list comprehension (at least on long
lists), but it might be a little obscure why the "if not s:" is
needed, so unless Thomas has a really long result list, he might want
to just keep the list comprehension, which is (IMO) very readable.

Alternatively, this is halfway between the previous example and the
list comprehension:

_split = re.compile(r"(\d+)").split
def split(s):
parts = _split(s)
parts[1::2] = map(int, parts[1::2])
for index in (-1, 0):
if parts and parts[index] == "":
del parts[index]
return tuple(parts)

BTW, I just remembered that, although I have often used the fact that
split returns alternating non-match/match/.../match/non-match in the
past, the last time I did this particular task (of splitting out
digits from a string), I didn't make use of that fact. But I wasn't
expecting very many splits for this case. FWIW, here's a class I
wrote that does this to a string for the express purpose of making
sorts work better:

http://code.google.com/p/pyeda/source/browse/trunk/kipy/kipy/utility/istring.py

Regards,
Pat

==============================================================================
TOPIC: off topic but please forgive me me and answer
http://groups.google.com/group/comp.lang.python/t/0d4f564a49022b74?hl=en
==============================================================================

== 1 of 6 ==
Date: Fri, Apr 2 2010 3:11 pm
From: Dave Angel


Mensanator wrote:
> On Apr 1, 9:44 pm, Steven D'Aprano <st...@REMOVE-THIS-
> cybersource.com.au> wrote:
>
>> <snip>
>>>>> 1/2.0
>>>>>
>> 0.25
>>
>> If you want an exact result when multiplying arbitrary fractions, you
>> need to avoid floats and decimals and use Fractions:
>>
>>
>>>>> Fraction(1, 2)**2
>>>>>
>> Fraction(1, 4)
>>
>
> Where do you get that from?
>
>
In Python2.6,

from fractions import Fraction

And Fraction is now a class which supports fractional arithmetic.

== 2 of 6 ==
Date: Fri, Apr 2 2010 4:07 pm
From: Steven D'Aprano


On Fri, 02 Apr 2010 12:35:55 -0700, Mensanator wrote:

>> If you want an exact result when multiplying arbitrary fractions, you
>> need to avoid floats and decimals and use Fractions:
>>
>> >>> Fraction(1, 2)**2
>>
>> Fraction(1, 4)
>
> Where do you get that from?

Where do I get what from? Fraction? Oops, sorry about that.

In Python2.6:

>>> from fractions import Fraction

In older Pythons, there was a demo module Demo/classes/Rat.py but it may
not be installed on your system. See http://bugs.python.org/issue1682

If you meant, where did I get the statement about exact results from,
both float and Decimal are fixed precision numbers. float precision is
fixed by the operating system and/or hardware; Decimal precision can be
arbitrarily chosen by the caller, but having made that choice,
calculations are rounded to that precision. Only Fraction gives exact
results for any arbitrary rational number.

--
Steven


== 3 of 6 ==
Date: Fri, Apr 2 2010 4:48 pm
From: Mensanator


On Apr 2, 6:07 pm, Steven D'Aprano <st...@REMOVE-THIS-
cybersource.com.au> wrote:
> On Fri, 02 Apr 2010 12:35:55 -0700, Mensanator wrote:
> >> If you want an exact result when multiplying arbitrary fractions, you
> >> need to avoid floats and decimals and use Fractions:
>
> >> >>> Fraction(1, 2)**2
>
> >> Fraction(1, 4)
>
> > Where do you get that from?
>
> Where do I get what from? Fraction? Oops, sorry about that.
>
> In Python2.6:
>
> >>> from fractions import Fraction

Ok, thanks. I've been using gmpy to do rational arithmetic:

>>> import gmpy
>>> gmpy.mpq(1,2)**2
mpq(1,4)

But I don't have a lot of call for it.

>
> In older Pythons, there was a demo module Demo/classes/Rat.py but it may
> not be installed on your system. Seehttp://bugs.python.org/issue1682
>
> If you meant, where did I get the statement about exact results from,
> both float and Decimal are fixed precision numbers. float precision is
> fixed by the operating system and/or hardware; Decimal precision can be
> arbitrarily chosen by the caller, but having made that choice,
> calculations are rounded to that precision. Only Fraction gives exact
> results for any arbitrary rational number.

Yes, rationals are handy sometimes.

>
> --
> Steven

== 4 of 6 ==
Date: Fri, Apr 2 2010 4:50 pm
From: Mensanator


On Apr 2, 2:34 pm, Patrick Maupin <pmau...@gmail.com> wrote:
> On Apr 2, 2:41 pm, Andreas Waldenburger <use...@geekmail.INVALID>
> wrote:
>
> > While everyone else is mocking you: Can you please elaborate on why you
> > want to know and what kind of problem you're trying to solve with this?
> > Also, don't you think you should have picked a maths forum for this
> > kind of question?
>
> Methinks the OP is fluent in the way of choosing newsgroups.
> According to google, he has posted 6855 messages in 213 groups.

Does that really mean anything? Hell, I have 12765 messages
posted to 332 groups, but I only use 10 regularly.

>
> http://groups.google.com/groups/profile?enc_user=ul3SQhIAAAAYmLD0Oj5Y...
>
> And I can't speak for anybody else, but I just assumed it was an April
> Fool's question.  I meant to be laughing with the OP, not at him, so
> sorry if I misunderstood.
>
> Regards,
> Pat

== 5 of 6 ==
Date: Fri, Apr 2 2010 5:32 pm
From: Patrick Maupin


On Apr 2, 6:50 pm, Mensanator <mensana...@aol.com> wrote:
> On Apr 2, 2:34 pm, Patrick Maupin <pmau...@gmail.com> wrote:
>
> > Methinks the OP is fluent in the way of choosing newsgroups.
> > According to google, he has posted 6855 messages in 213 groups.
>
> Does that really mean anything? Hell, I have 12765 messages
> posted to 332 groups, but I only use 10 regularly.

Well, I have been very wrong in my assumptions before, but yes, I do
assume it means something:

- I assume that the OP knows of the existence of more than one
newsgroup.

- I assume the OP knows how to locate different newsgroups, either via
search or some directory like yahoo, and is able to think about which
one he wants to post to and why.

- I assume that he is comfortable with the process of posting. In
fact, looking at the stats, about half as comfortable as mensanator,
and over 18 times as comfortable as me ;-)

Of course, I could be all wet in my assumptions, and it may just be
that the OP has a cat constantly walking back and forth across his
keyboard...

Regards,
Pat


== 6 of 6 ==
Date: Fri, Apr 2 2010 6:29 pm
From: Mensanator


On Apr 2, 7:32 pm, Patrick Maupin <pmau...@gmail.com> wrote:
> On Apr 2, 6:50 pm, Mensanator <mensana...@aol.com> wrote:
>
> > On Apr 2, 2:34 pm, Patrick Maupin <pmau...@gmail.com> wrote:
>
> > > Methinks the OP is fluent in the way of choosing newsgroups.
> > > According to google, he has posted 6855 messages in 213 groups.
>
> > Does that really mean anything? Hell, I have 12765 messages
> > posted to 332 groups, but I only use 10 regularly.
>
> Well, I have been very wrong in my assumptions before, but yes, I do
> assume it means something:

Yes, you are, in fact, all wet.

>
> - I assume that the OP knows of the existence of more than one
> newsgroup.

"More than one", that's fair. 213, unlikely.

>
> - I assume the OP knows how to locate different newsgroups, either via
> search or some directory like yahoo, and is able to think about which
> one he wants to post to and why.

And most of those probably involved no thought at all, probably
due to cross-posting from a relatively small number of sources
(certainly in my case). So, no, this stat proves nothing about
the OP's ability to find newsgroups or think about their
appropriateness.

>
> - I assume that he is comfortable with the process of posting.  In
> fact, looking at the stats, about half as comfortable as mensanator,
> and over 18 times as comfortable as me ;-)

Well, _I've_ been here on Usenet for 10 years. But despite the stats,
I know little about most to the groups I've "posted to".

>
> Of course, I could be all wet in my assumptions, and it may just be
> that the OP has a cat constantly walking back and forth across his
> keyboard...

Don't you know how Usenet works?

>
> Regards,
> Pat


==============================================================================
TOPIC: C-style static variables in Python?
http://groups.google.com/group/comp.lang.python/t/ce1a7abe2f3816b9?hl=en
==============================================================================

== 1 of 4 ==
Date: Fri, Apr 2 2010 3:59 pm
From: kj


In <Xns9D4EC021DC8EAduncanbooth@127.0.0.1> Duncan Booth <duncan.booth@invalid.invalid> writes:

>class Spam(object):
> mongo = None
> def __call__(self, x, y, z):
> if self.mongo is None:
> self.mongo = heavy_lifting_at_runtime()
> return frobnicate(x, y, z, self.mongo)
>spam = Spam()

>ham = spam(1, 2, 3)

I really like this. Thanks.

>That's natural and readable.

From reading this thread, and the "(a==b) ? 'Yes' : 'No'" one, the
inescapable conclusion is that "readability" (like beauty) is very
much in the eye of the beholder, or, in this case, in the eye of
Guido.

~K


== 2 of 4 ==
Date: Fri, Apr 2 2010 4:57 pm
From: Steven D'Aprano


On Fri, 02 Apr 2010 12:39:16 -0700, Patrick Maupin wrote:

> On Apr 2, 2:38 pm, Ethan Furman <et...@stoneleaf.us> wrote:
[...]
>> Sounds like a personal preference issue, rather than a necessary /
>> unnecessary issue -- after all, if you call that function a thousand
>> times, only once is mongo not defined... clearly the exception.  ;)
>>
>> ~Ethan~
>
> Well, I think the whole discussion has basically been about personal
> preference. OTOH, but if you call the function a few million times, you
> might find the cost of try/except to be something that you would rather
> not incur -- it might become a performance issue rather than a personal
> choice issue.


The cost of a try...except is *very* low -- about the same as a pass
statement:

>>> from timeit import Timer
>>> t1 = Timer("pass", "")
>>> t2 = Timer("try:\n pass\nexcept Exception:\n pass", "")
>>> min(t2.repeat())/min(t1.repeat())
1.9227982449955801


Actually catching the exception, on the other hand, is quite expensive:

>>> t1 = Timer("len('')", "")
>>> t2 = Timer("try:\n len(0)\nexcept Exception:\n pass", "")
>>> min(t2.repeat())/min(t1.repeat())
10.598482743564809


The heuristic I use is, if I expect the try block to raise an exception
more than about one time in ten, I change to an explicit test. In this
case, since the exception should only be raised once, and then never
again, I would use a try...except block.

--
Steven


== 3 of 4 ==
Date: Fri, Apr 2 2010 5:25 pm
From: Patrick Maupin


On Apr 2, 6:57 pm, Steven D'Aprano <st...@REMOVE-THIS-
cybersource.com.au> wrote:
> On Fri, 02 Apr 2010 12:39:16 -0700, Patrick Maupin wrote:
> > On Apr 2, 2:38 pm, Ethan Furman <et...@stoneleaf.us> wrote:
> [...]
> >> Sounds like a personal preference issue, rather than a necessary /
> >> unnecessary issue -- after all, if you call that function a thousand
> >> times, only once is mongo not defined... clearly the exception.  ;)
>
> >> ~Ethan~
>
> > Well, I think the whole discussion has basically been about personal
> > preference.  OTOH, but if you call the function a few million times, you
> > might find the cost of try/except to be something that you would rather
> > not incur -- it might become a performance issue rather than a personal
> > choice issue.
>
> The cost of a try...except is *very* low -- about the same as a pass
> statement:

Agreed. In the example above, if frobnicate() is a null function, the
try/except adds about 5% to execution time on my machine. If I were
really worried about execution time, I would use a closure *for this
particular example* as I mentioned elsewhere. However, the cost of
the try/except is not zero, and when I have something I prefer looking
at (the __getattr__ doesn't clutter up the main-line execution with
conditionals for stuff that only gets used once at initialization)
that is always known to be cheaper in execution, that's what I use. I
suppose some people might not like looking at the __getattr__, but
this is a memoization technique I use quite often, so I find it
idiomatic.

Regards,
Pat

== 4 of 4 ==
Date: Fri, Apr 2 2010 6:46 pm
From: Terry Reedy


On 4/2/2010 6:59 PM, kj wrote:
> In<Xns9D4EC021DC8EAduncanbooth@127.0.0.1> Duncan Booth<duncan.booth@invalid.invalid> writes:
>
>> class Spam(object):
>> mongo = None
>> def __call__(self, x, y, z):
>> if self.mongo is None:
>> self.mongo = heavy_lifting_at_runtime()
>> return frobnicate(x, y, z, self.mongo)

Unless one wants the intialization of mongo delayed in case spam is
never called, it can go in __init__ instead.


>> spam = Spam()
>
>> ham = spam(1, 2, 3)
>
> I really like this. Thanks.
>
>> That's natural and readable.
>
>> From reading this thread, and the "(a==b) ? 'Yes' : 'No'" one, the
> inescapable conclusion is that "readability" (like beauty) is very
> much in the eye of the beholder, or, in this case, in the eye of
> Guido.
>
> ~K

==============================================================================
TOPIC: Generating text from a regular expression
http://groups.google.com/group/comp.lang.python/t/c16f904e698a42b3?hl=en
==============================================================================

== 1 of 1 ==
Date: Fri, Apr 2 2010 4:22 pm
From: Nathan Harmston


Thanks everyone, the invRegexInf is perfect.

Thanks again,

Nathan

On 1 April 2010 10:17, Gabriel Genellina <gagsl-py2@yahoo.com.ar> wrote:
> En Wed, 31 Mar 2010 12:23:48 -0300, Paul McGuire <ptmcg@austin.rr.com>
> escribió:
>>
>> On Mar 31, 5:49 am, Nathan Harmston <iwanttobeabad...@googlemail.com>
>> wrote:
>>>
>>> I have a slightly complicated/medium sized regular expression and I
>>> want to generate all possible words that it can match (to compare
>>> performance of regex against an acora based matcher).
>>
>> The pyparsing wiki Examples page includes this regex inverter:
>> http://pyparsing.wikispaces.com/file/view/invRegex.py
>>
>>> From the module header:
>>
>> # Supports:
>> # - {n} and {m,n} repetition, but not unbounded + or * repetition
>> # - ? optional elements
>> # - [] character ranges
>> # - () grouping
>> # - | alternation
>
> I took the liberty of modifying your invRegex.py example, adding support
> for infinite repeaters. It depends on two other modules:
>
> mergeinf.py (from http://code.activestate.com/recipes/577041) provides the
> infinite merge operation.
>
> enumre.py provides the basic functions (merge, prod, repeat, closure)
> necessary to enumerate the language generated by a given regular
> expression, even if it contains unbounded repeaters like *,+.  The key is
> to generate shorter strings before longer ones, so in 'a*|b*' it doesn't
> get stuck generating infinite a's before any b.
>
> By example, "(a|bc)*d" corresponds to this code:
>
>      prod(
>        closure(
>          merge(
>            'a',
>             prod('b','c'))),
>        'd')
>
> which returns an infinite generator starting with:
>
> d
> ad
> aad
> bcd
> aaad
> abcd
> bcad
> aaaad
> aabcd
> abcad
> bcaad
> bcbcd
> aaaaad
> aaabcd
> aabcad
> ...
>
>
> I got the idea from
> http://userweb.cs.utexas.edu/users/misra/Notes.dir/RegExp.pdf
>
> Finally, invRegexInf.py is based on your original regex parser. I only
> modified the generation part, taking advantage of the above
> infrastructure; the parser itself remains almost the same. It essentially
> saves oneself the very tedious work of converting a regular expression
> into the equivalent sequence of function calls as shown above. (I hope I
> got it right: I like pyparsing a lot and use it whenever I feel it's
> appropriate, but not as often as to remember the details...)
>
> --
> Gabriel Genellina
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>

==============================================================================
TOPIC: psycopg2 / psycopg2.ProgrammingError: syntax error at or near "E'
mytable'"
http://groups.google.com/group/comp.lang.python/t/52208bb7a4b2e338?hl=en
==============================================================================

== 1 of 2 ==
Date: Fri, Apr 2 2010 5:26 pm
From: mrdrew


Hey all,

Right now I'm completely unable to pass parameters to queries under
any circumstances. I've got a fairly trivial query as a test...

c.execute('SELECT * FROM %(table_name)s LIMIT 1',
{'table_name':"mytable"})

It fails, giving the error message...

Traceback (most recent call last):
File "test.py", line 7, in <module>
c.execute('SELECT * FROM %(table_name)s LIMIT 1',
{'table_name':"mytable"})
psycopg2.ProgrammingError: syntax error at or near "E'mytable'"
LINE 1: SELECT * FROM E'mytable' LIMIT 1

This may be similar to the problem that ASh had (http://
groups.google.com/group/comp.lang.python/browse_thread/thread/
7463ded0971425f8/538e60ba0ccf2ad3?#538e60ba0ccf2ad3
)

I'd really appreciate any ideas. At the moment, I'm stuck
concatenating strings and hoping for the best.


== 2 of 2 ==
Date: Fri, Apr 2 2010 6:27 pm
From: MRAB


mrdrew wrote:
> Hey all,
>
> Right now I'm completely unable to pass parameters to queries under
> any circumstances. I've got a fairly trivial query as a test...
>
> c.execute('SELECT * FROM %(table_name)s LIMIT 1',
> {'table_name':"mytable"})
>
> It fails, giving the error message...
>
> Traceback (most recent call last):
> File "test.py", line 7, in <module>
> c.execute('SELECT * FROM %(table_name)s LIMIT 1',
> {'table_name':"mytable"})
> psycopg2.ProgrammingError: syntax error at or near "E'mytable'"
> LINE 1: SELECT * FROM E'mytable' LIMIT 1
>
> This may be similar to the problem that ASh had (http://
> groups.google.com/group/comp.lang.python/browse_thread/thread/
> 7463ded0971425f8/538e60ba0ccf2ad3?#538e60ba0ccf2ad3)
>
> I'd really appreciate any ideas. At the moment, I'm stuck
> concatenating strings and hoping for the best.

I think that you're confusing Python's string formatting with SQL
placeholders.

The "%(table_name)s" works only with Python's '%' operator. You should
use only the "%s" form (or possibly "?", I'm not sure which!) in the
template string and pass the parameters in a tuple (maybe a list will
also work) when calling .execute().


==============================================================================

You received this message because you are subscribed to the Google Groups "comp.lang.python"
group.

To post to this group, visit http://groups.google.com/group/comp.lang.python?hl=en

To unsubscribe from this group, send email to comp.lang.python+unsubscribe@googlegroups.com

To change the way you get mail from this group, visit:
http://groups.google.com/group/comp.lang.python/subscribe?hl=en

To report abuse, send email explaining the problem to abuse@googlegroups.com

==============================================================================
Google Groups: http://groups.google.com/?hl=en

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate