Re: Syntactic sugar for assignment statements: one value to multiple targets?

2011-08-17 Thread Chris Angelico
On Wed, Aug 17, 2011 at 1:14 AM, gc  wrote:
> Perfectly reasonable request! Maybe there aren't as many cases when
> multiple variables need to be initialized to the same value as I think
> there are.
>

Minor clarification: You don't want to initialize them to the same
value, which you can do already:

a=b=c=d=e=dict()

You want to initialize them each to a fresh evaluation of the same
expression. What you're asking for is a syntax that writes an
expression once, but evaluates it many times; I think it's going to
work out something very similar to a list comprehension (as has been
mentioned).

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


Re: Wait for a keypress before continuing?

2011-08-17 Thread Chris Angelico
On Wed, Aug 17, 2011 at 7:12 AM, Seebs  wrote:
>> Yes, even the common term "command line" is foreign to me. I do
>> some powerful stuff in Windows, without need for a command line.
>
> So apparently you *do* know the term.  Normally, to say that a term is
> foreign to you is to say that you have no idea what it means, not that
> you know what it means but don't use it.
>

Unless you're saying it for deliberate effect.

Smith: "To whom do you pay rent?"
Arcadian girl: "Rent? We do not know what it is to pay rent!"
Smith: "Ah. They're Irish."

They know full well what "rent" means, but don't truly comprehend the
concept, as they've never done it. I would say that for many people,
command lines are the same thing. For me, photo editing is like that.

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


Re: Wait for a keypress before continuing?

2011-08-17 Thread John Doe
Seebs  wrote: 

> John Doe  wrote: 

>> Context is lost when you quote only one level. 
> 
> Not significantly. 

Whatever you say, Jeebs. 

>> I was not answering a question about my code. I was pointing 
>> out the fact that my questioner's terminology is 
>> strange/corrupt. 
> 
> Well, that's the thing.  There was a question there, with 
> perfectly valid terminology. 

And I respect your opinion, Jeebs. 

>>> If you do, it suggests that perhaps one or more of the terms 
>>> are unfamiliar to you? 
> 
>> Yes, even the common term "command line" is foreign to me. I do
>> some powerful stuff in Windows, without need for a command 
>> line. 
> 
> So apparently you *do* know the term.  

Not very well, obviously. 

> Normally, to say that a term is foreign to you is to say that 
> you have no idea what it means, 

Sounds like being a lexicographer is a fantasy of yours, Jeebs. 

> not that you know what it means but don't use it. 

But in fact I do not have a clear understanding of what it means, 
Jeebs, but I know that it's a common term. 

You are not a lexicographer, dude. 

>> I realize it exists and that some people live by it, but it has
>> been nearly useless to me. 
> 
> In which case, you're not using a command line, and are using a 
> GUI, and the other poster's question is answered. 

That might have been clear to most normal people in my first reply
to the first follow-up. 

"I am using Windows XP SP3. Komodo Edit 6 for editing the *.py 
file. Dragon Naturally Speaking, Natlink, and Dragonfly might all 
be part of the process." 

The answer was pointless by the time the question was asked 
straightforward. Thanks to the prior replies, by then I had 
already figured out that I need a keyboard hook. The answer 
doesn't matter anymore. 

> The Google results you cite to are uninteresting and frankly 
> irrelevant. 

You have every right to an opinion, Fuckturd. 

> If someone asks me whether the ornamental fish in my 55-gallon 
> tank is a koi, that Google has no hits for "ornamental fish in 
> your 55-gallon tank is a koi" does not mean that the terminology
> is "strange" or "corrupt". 

No wonder you don't quote relevant material, Jeebs. If anybody 
knew what you were comparing that expression to, you would look 
stupid. 

> The terminology was fine. 

Are you a master of terminology on wikishit, Jeebs? I think 
wikishit sucks. Wannabe lexicographers like you might be a reason. 
I've dealt with some real lexicographers, Jeebs, you aren't one.  
-- 



















> 
> -s
> -- 
> Copyright 2011, all wrongs reversed.  Peter Seebach / usenet-nospam seebs.net
> http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
> http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
> I am not speaking for my employer, although they do rent some of my opinions.
> 
> 

> Path: 
> news.astraweb.com!border6.newsrouter.astraweb.com!news.glorb.com!newsfeeds.sol.net!post2.nntp.sol.net!posts.news.megabitz.net!nnrp3-asbnva.megabitz.net!not-for-mail
> Newsgroups: comp.lang.python
> From: Seebs 
> Subject: Re: Wait for a keypress before continuing?
> References: <4e3f2827$0$5826$c3e8da3$12bcf670 news.astraweb.com> 
> <4e4ad039$0$9663$c3e8da3$76491128 news.astraweb.com> 
>  
> <4e4ae844$0$29730$c3e8da3$92d0a893 news.astraweb.com> 
>  
> <4e4b3b02$0$30718$c3e8da3$f017e9df news.astraweb.com> 
>  
> <4e4b566c$0$3959$c3e8da3$b23f186d news.astraweb.com>
> User-Agent: slrn/0.9.9p1 (Darwin)
> Mime-Version: 1.0
> Content-Type: text/plain; charset=us-ascii
> Content-Transfer-Encoding: 7bit
> Message-ID: 
> Date: 17 Aug 2011 06:12:02 GMT
> Lines: 40
> Organization: Megabitz - More USENET, Faster USENET
> NNTP-Posting-Date: 17 Aug 2011 06:12:02 GMT
> NNTP-Posting-Host: 3c8d6a06.news.megabitz.net
> X-Trace: 
> DXC=BKlkN0:D\OSc::[BQideGP><6FU_Q:4mR^W\Y;gN2lO]C2e6efi]<9Z?jW6Mmc0=4W7d 
> DE\31QYU2V739; X-Complaints-To: abuse megabitz.net
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why no warnings when re-assigning builtin names?

2011-08-17 Thread Chris Angelico
On Wed, Aug 17, 2011 at 2:35 AM, Seebs  wrote:
> On 2011-08-17, Chris Angelico  wrote:
>> It mightn't be very significant, but there'd still be some cost.
>> However, IMHO the greatest cost is the spamminess; forcing the user to
>> deal with lines and lines of warnings is not a useful way to design a
>> language.
>
> Lines and lines?
>
> I'd say if it's to be allowed to shadow built-ins (and I'm not sure that's
> a good thing at all), you'd still be looking at one warning per shadowing,
> which shouldn't be too many.

One warning per shadowing. Okay.

def foo(list):
   """Foo's the list provided and returns True on success or False on
failure."""

def bar(list):
"""Counts the number of bars in the list, assuming it to be made
of music."""
if not foo(list): return

You call foo() once and bar() twice. How many shadowings have there
been? How many warnings do you get?

A simple implementation would give five warnings for this case - once
for each invocation that shadows a builtin. Another simple
implementation would give two warnings, at the time that the def
statements are executed; this is preferred, but it's still two
warnings, and if you have a huge set of functions that do this, that
can easily be "lines and lines" of warnings. Or should it set a flag
and say "I've already warned this session about shadowing 'list', so
suppress all others"? That seems confusing.

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


Re: Why no warnings when re-assigning builtin names?

2011-08-17 Thread Chris Angelico
On Wed, Aug 17, 2011 at 1:58 AM, Steven D'Aprano
 wrote:
>> My thoughts would be:
>> 1.  It's hard to avoid shadowing anything unless you know the entire
>> language and never forget things.
>
> Define the "entire language". Does that include the names of all the
> plethora of exceptions? How about the standard library?

The shadowing issue applies to the standard library as well as the
builtins, so yes; to avoid shadowing *anything*, you would have to
know the entire language. I posit that this is a practical
impossibility, and that unexpected shadowing will always be possible
(and won't always be prevented by syntax highlighting). Some day
you'll discover that you can't use module X because you have a
function called X, and you'll have to rename.

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


Re: Wait for a keypress before continuing?

2011-08-17 Thread peter
Is there an equivalent to msvcrt for Linux users?  I haven't found
one, and have resorted to some very clumsy code which turns off
keyboard excho then reads stdin. Seems such an obvious thing to want
to do I am surprised there is not a standard library module for it. Or
have I missed someting (wouldn't be the first time!)

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


Re: Why no warnings when re-assigning builtin names?

2011-08-17 Thread Steven D'Aprano
On Wed, 17 Aug 2011 01:17 pm Seebs wrote:

[...]
> "Another" scope is normally a horizontal thing -- you're talking about
> a different scope such that you are *either* in this one *or* in that
> one.
> 
> Built-ins are not in a scope you are never not in.

That's technically incorrect. Built-ins are a scope you are never in, if
by "in" you mean "code is executed in this scope".

You have three scopes in general:

Local
Global
Built-ins

(There's also zero or more nonlocal scopes, between local and global, that
applies to closures and nested functions, but never mind that.)

Code is almost(?) always executed in the local scope. (eval and exec let you
mess around with that, somewhat.) E.g. an assignment "x = 1" applies to the
local namespace unless you explicitly declare it global. If you are in the
top level of a module, the local namespace is also the global one, the
global statement does nothing, and the assignment occurs in the global
namespace.

However, name lookup rules are such that while assignments are always local,
unsuccessful lookups may fall through to global then built-in. 

See also: http://www.python.org/dev/peps/pep-0227/

The only way to put something into the built-in namespace is by using the
fully-qualified name:

>>> import builtins  # Use __builtin__ in Python 2
>>> builtins.x = 1  # Kids! Don't try this at home!
>>>
>>> x
1
>>> del x  # prove it isn't a global or local
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'x' is not defined

So a top-level (global) assignment, say:

def sum(list):
...

*shadows* the built-ins sum and list, it doesn't replace them. It defines a
local variable "list" and a global variable "sum", but it doesn't touch
either built-in. They are still available via the fully qualified name
builtins.sum and builtins.list.


[...]
>> (4) And then, after a while, you decide that perhaps shadowing is not
>> always so bad. (It helps if the Effbot tells you off for objecting to
>> shadowing in a two-line function.) At first, you limit yourself to using
>> parameter names that shadow built-ins in small tool-like functions. Then
>> when the world doesn't implode, you rethink the use of top-level function
>> names like "izip" and realise that namespaces exist so that you don't
>> need to care about shadowing functions you don't use, and if people call
>> import * they have nobody to blame but themselves if things break.
> 
> Hmm.  See, I've never reached that, in Python or any other language.  I
> figure it creates a new potential for confusion, and that I would rather
> avoid any ambiguity.  I don't *like* ambiguity in code.

Ah, well you see the thing is, this is Python. As soon as you call any
function you don't control, you no longer know what your environment is
with any certainty. For all you know, the harmless-looking function is
monkey-patching builtins like there's no tomorrow. Speaking broadly,
perhaps too broadly, we're incredibly proud of the ability to modify nearly
everything at runtime.

Fortunately, while we are proud of having that ability, actually *using* it
is considered a mortal sin. We're not Ruby developers -- if you actually
monkey-patch something, especially built-ins, you can expect to be taken
outside and slapped around with a fish if you get caught.

http://www.youtube.com/watch?v=IhJQp-q1Y1s

 
> So I don't shadow stuff that's part of the language, because doing that
> makes it possible for a line of code to have a clear and obvious meaning
> to someone who looks at that line out of context, and a *completely
> different* clear and obvious meaning to someone who looks at it with a bit
> more
> context.  I don't like that!  It means that someone reading my code can
> never, ever, assume that a standard language feature is actually itself
> and not a local shadow which does something different unless they go
> walking back up the scope chain checking.  And that's a pretty big cost
> to attach to stuff that is, by design, basic and universally available.

Sure. But they can't have that certainty regardless of whether you shadow
something, because how do they know whether you've shadowed it or not?

In theory, anything could be anything at any time, and you have no
protection. In practice, I worry more about being eaten by
genetically-engineered flying piranhas than about rogue monkey-patching
code.


-- 
Steven

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


Re: Wait for a keypress before continuing?

2011-08-17 Thread Steven D'Aprano
On Wed, 17 Aug 2011 05:23 pm John Doe wrote:

> You have every right to an opinion, Fuckturd. 

I shouldn't need to say this to anyone over the age of four, but being
obnoxious to people trying to help does not encourage others to answer your
question. You don't win points for insulting people who are trying to solve
your problems.


-- 
Steven

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


CGI: Assign FieldStorage values to variables

2011-08-17 Thread Gnarlodious
I get a construct like this:

form=FieldStorage(None, None, [MiniFieldStorage('name1', 'Val1'),
MiniFieldStorage('name2', 'Val2'), MiniFieldStorage('name3', 'Val3')])

Now how would I assign every variable name* its value?

lI did try locals().update(form) however I get
>>> name2
-> MiniFieldStorage('name2', 'Val2')

when I need to assign the variable name2 the value Val2

This is Py3

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


CGI: Assign FieldStorage values to variables

2011-08-17 Thread Gnarlodious
I get a construct like this:

form=FieldStorage(None, None, [MiniFieldStorage('name1', 'Val1'),
MiniFieldStorage('name2', 'Val2'), MiniFieldStorage('name3', 'Val3')])

Now how would I assign every variable name* its value?

lI did try locals().update(form) however I get
>>> name2
-> MiniFieldStorage('name2', 'Val2')

when I need to assign the variable name2 the value Val2

This is Py3

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


Re: CGI: Assign FieldStorage values to variables

2011-08-17 Thread Gnarlodious
I should add that this does what I want, but something a little more
Pythonic?

import cgi, os
os.environ["QUERY_STRING"] = "name1=Val1&name2=Val2&name3=Val3"
form=cgi.FieldStorage()

form

dict = {}
for key in form.keys(): dict[ key ] = form[ key ].value

dict
locals().update(dict)
name3

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


Re: CGI: Assign FieldStorage values to variables

2011-08-17 Thread Chris Angelico
On Wed, Aug 17, 2011 at 10:06 AM, Gnarlodious  wrote:
> I get a construct like this:
>
> form=FieldStorage(None, None, [MiniFieldStorage('name1', 'Val1'),
> MiniFieldStorage('name2', 'Val2'), MiniFieldStorage('name3', 'Val3')])
>
> when I need to assign the variable name2 the value Val2

You can probably do this with some kind of list comprehension, but I
recommend against it, if this has come from a web form. You do NOT
want end users having the power to set variables. Keep it in a
separate object (such as 'form') such that you must always be explicit
about fetching form data. PHP has learned the risks; here's a decent
summary:

http://www.php.net/manual/en/security.globals.php

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


Re: Syntactic sugar for assignment statements: one value to multiple targets?

2011-08-17 Thread gc
On Aug 17, 3:13 am, Chris Angelico  wrote:

> Minor clarification: You don't want to initialize them to the same
> value, which you can do already:
>
> a=b=c=d=e=dict()

Right. Call the proposed syntax the "instantiate separately for each
target" operator.  (It can be precisely defined as a * on the RHS of a
one-into-many assignment statement--i.e. an assignment statement with
1 object on the RHS and more than 1 on the LHS).

It has only one very modest function, which is to unpack

a, b, c, d, e = *dict()

to

a, b, c, d, e = dict(), dict(), dict(), dict(), dict()

so that you have n separate objects instead of one. If you want the
same object duplicated five times, you'd best use a=b=c=d=e=dict().
(I'd guess that 90% of the people who try the a=b=c version actually
*want* separate objects and are surprised at what they get--I made
that mistake a few times!--but changing either behavior would be a
very bad idea. This proposed syntax would be the Right Way to get
separate objects.)

Maybe this is more visibly convenient with a complex class, like

x, y, z = *SuperComplexClass(param1, param2, kwparam = "3", ...)

where you need three separate objects but don't want to duplicate the
class call (for obvious copy-paste reasons) and where bundling it in a
list comprehension:

x, y, z = [SuperComplexClass(param1, etc, ...) for _ in range(3)]

layers gunk on top of something that's already complex.

> I think it's going to work out something very similar to a
> list comprehension (as has been mentioned).

Right; kind of a self-limiting generator[1], although that sounds MUCH
more complex than it needs to. It's really just sugar. Not that it
this is a suggestion :) but it could easily be done with a pre-
processor. It would also be perfectly amenable to automated code
conversion (i.e. 3to2).

On Aug 16, 10:11 pm, MRAB  wrote:

> 1. Repeated evaluation of an expression: "dict()" would be evaluated as
> many times as necessary. In other words, it's an unlimited generator.

> 2. Lazy unpacking: unpacking normally continues until the source is
> exhausted, but here you want it to stop when the destination (the RHS)
> is satisfied.

Yes, this is a good way to think of it. (Although I think you meant to
type LHS, right?) * in this context would tell Python to do both of
these things at once: evaluate successively and unpack lazily to the
destination. Although it's still fully (and more simply) explainable
as sugar.

[1] Self-limiting is the key here. As above, the only proposed methods
which don't require manual tallying on the RHS are Tim's very creative
a,b,c,d,e,*scrap = (dict() for _ in range()), which in this case
creates a list containing 9994 unnecessary dicts, or the purer but
Python-crashing a,b,c,d,e,*scrap = (dict() for _ in
itertools.count()). Tim's intuition, which I share, is that in both
cases *scrap should, since it's in final position, actually become the
generator-in-state-6, rather than slurping the rest into a list. One
argument for this is that the present behavior is (surprisingly,
counterintuitively) identical for list comprehensions and generator
expressions. Changing the outer parens to brackets yields the same
results. But that's a separate, more complex proposal which would need
its own use cases.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CGI: Assign FieldStorage values to variables

2011-08-17 Thread Chris Angelico
On Wed, Aug 17, 2011 at 10:19 AM, Gnarlodious  wrote:
> import cgi, os
> os.environ["QUERY_STRING"] = "name1=Val1&name2=Val2&name3=Val3"
> form=cgi.FieldStorage()
>
> form
>
> dict = {}
> for key in form.keys(): dict[ key ] = form[ key ].value
>

You could probably use a list comp for this, but there's not a lot of
difference. (By the way, you should be aware that you're shadowing the
builtin 'dict' here. That's not a problem, but be aware.)

dict.update(((key,form[key].value) for key in form))

That's a generator that returns a (key,value) tuple for each form
element, which update() will happily use.

But the last line:
> locals().update(dict)
is, IMHO, a very bad idea. Rename your dictionary to 'request' or
'data' or 'form' or something, and then reference form['name3']
instead; or, be explicit:
name3=form['name3']

Incidentally, you seem to be working at the module level, where
locals() is globals() (and I mean that literally - 'locals() is
globals()' is True). You may not be able to do this with locals() in a
function:
http://docs.python.org/library/functions.html#locals

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


Re: Syntactic sugar for assignment statements: one value to multiple targets?

2011-08-17 Thread Chris Angelico
On Wed, Aug 17, 2011 at 10:26 AM, gc  wrote:
> On Aug 17, 3:13 am, Chris Angelico  wrote:
>
>> Minor clarification: You don't want to initialize them to the same
>> value, which you can do already:
>>
>> a=b=c=d=e=dict()
>
> Right. Call the proposed syntax the "instantiate separately for each
> target" operator.  (It can be precisely defined as a * on the RHS of a
> one-into-many assignment statement--i.e. an assignment statement with
> 1 object on the RHS and more than 1 on the LHS).
>

Agreed, but there's no requirement for it to be instantiating
something (although that will be common). "dict()" is an expression
that you want to evaluate five (or however many) times. It might just
as easily be some other function call; for instance:

head1,head2,head3=file.readline()

to read three lines from a file. Or it mightn't even be a function call per se.

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


Re: CGI: Assign FieldStorage values to variables

2011-08-17 Thread Gnarlodious
I should add that this does what I want, but something a little more
Pythonic?

import cgi, os
os.environ["QUERY_STRING"] = "name1=Val1&name2=Val2&name3=Val3"
form=cgi.FieldStorage()

form

dict = {}
for key in form.keys(): dict[ key ] = form[ key ].value

dict
locals().update(dict)
name3

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


Re: Syntactic sugar for assignment statements: one value to multiple targets?

2011-08-17 Thread gc
On Aug 17, 5:45 am, Chris Angelico  wrote:
(snip)
> > Right. Call the proposed syntax the "instantiate separately for each
> > target" operator.
>
(snip)
> It might just
> as easily be some other function call; for instance:
>
> head1,head2,head3=file.readline()

Hm--that's interesting! OK, call it the "evaluate separately for each
target" operator.

Same benefits in this use case; if I realize that the file only has
two header lines, I can just change

head1, head2, head3 = *file.readline()

to

head1, head2 = *file.readline()

without needing to keep a RHS like = [file.readline() for _ in
range(3)] in lockstep with the number of variables I'm assigning.

Presumably this syntax should be disallowed, as a grammatical matter,
when there's a starred target (per PEP 3132/language reference 6.2).
That is,

head, *body, tail = *file.readline()

is disallowed, since it is (by definition) simply sugar for

head = file.readline()
*body = file.readline()
tail = file.readline()

and

*body = file.readline() is disallowed (see PEP 3132). (Here, of
course, you'd just want head, *body, tail = file.readlines(), which is
perfectly good code.)

PS.

Off-topic, but the *target syntax already gets into similar territory,
since

a, *b, c = itertools.count()

crashes with a MemoryError--but what else could it do? Ruling out such
infinite-assignment statements on a grammatical basis would require
solving the halting problem through static analysis, which might be a
bit inefficient :P



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


How to package a gui with py2exe

2011-08-17 Thread Benji Ara.
Hello
I wonder how you package a Tkinter gui with py2exe?
Thanks
Benji


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


Re : Messed up Mac installation

2011-08-17 Thread fmder1
Checkout Homebrew. It can install in a very easy and clean way different 
version of Python (as well as a lot of other stuff). It tried for a long time 
to keep my Mac clean and this is so far the best I found.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re : Messed up Mac installation

2011-08-17 Thread fmder1
Forgot to include a link : https://github.com/mxcl/homebrew
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Windows service in production?

2011-08-17 Thread Tim Golden

On 16/08/2011 15:46, snorble wrote:

Interesting. Normally I would use py2exe then do "myapp.exe -install"
to install the app as a service. How do you handle installing the
service? Also what does the service show under the properties, for the
executable? "python.exe script.py" or something else?


To install, I simply invoke the Command-line handler which comes with 
the pywin32 service utils:


if __name__ == '__main__':
  win32serviceutil.HandleCommandLine (Service)

(I imagine that's what py2exe's doing for you behind the scenes).

The executable shows as pythonservice.exe. The short and long
display names can of course be whatever you like.

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


Re: testing if a list contains a sublist

2011-08-17 Thread Nobody
On Tue, 16 Aug 2011 09:57:57 -0400, John Posner wrote:

> How about using Python's core support for "==" on list objects:

> for i in range(alist_sz - slist_sz + 1):
> if slist == alist[i:i+slist_sz]:
> return True

This is bound to be asymptotically O(alist_sz * slist_sz), even if the
constant factor is reduced by use of ==. Boyer-Moore and regexps are
asymptotically O(alist_sz). However, the setup costs are much higher, so
you might need alist_sz to be very large before they win out.

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


Re: How to package a gui with py2exe

2011-08-17 Thread Vlastimil Brom
2011/8/17 Benji Ara. :
> Hello
> I wonder how you package a Tkinter gui with py2exe?
> Thanks
> Benji
>
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>

Hi,
check the necessary steps on the py2exe homepage
http://www.py2exe.org/index.cgi/Tutorial

in your setup script, you have to use something like the following for
a gui app:

setup(windows=["gui_hello.py"])

instead of console in the sample code
setup(console=['hello.py'])

For more details there are some dedicated pages on the project wiki:
http://www.py2exe.org/index.cgi/FrontPage

hth,
   vbr
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CGI: Assign FieldStorage values to variables

2011-08-17 Thread Nobody
On Wed, 17 Aug 2011 02:06:31 -0700, Gnarlodious wrote:

> I get a construct like this:
> 
> form=FieldStorage(None, None, [MiniFieldStorage('name1', 'Val1'),
> MiniFieldStorage('name2', 'Val2'), MiniFieldStorage('name3', 'Val3')])
> 
> Now how would I assign every variable name* its value?

Don't do this. It will allow the user to set any variable they wish,
not just the ones you want them to, which is a major security flaw. PHP
had this as a language feature (controlled by the register_globals
directive), and it was rightly decried as a major security flaw.

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


Re: How to install easy_install on windows ?

2011-08-17 Thread Duncan Booth
aspineux  wrote:

> in a command prompt run
> C:\Your Python Directory\python.exe  C:\Your Download directory
> \ez_setup.py
> 
> Then use
> 
> C:\Your Python Directory\python.exe C:\Your Python Directory\I dont
> know where the easy_install script will be installed\easy_install.py
> install module_name

Or even just use:

C:\Your Python Directory\scripts\easy_install install module_name

as easy_install will also add a .exe to your Python's 'scripts' folder.


-- 
Duncan Booth http://kupuguy.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wait for a keypress before continuing?

2011-08-17 Thread Ethan Furman

Welcome to my killfile.

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


RE: Why no warnings when re-assigning builtin names?

2011-08-17 Thread Gerrat Rickert
> On 8/16/2011 7:29 PM, Terry Reedy wrote:
> 
> On 8/16/2011 1:15 PM, Gerrat Rickert wrote:
> 
> > I think that best practices would suggest that one shouldn't use
> > variable
> > names that shadow builtins (except in specific, special
> circumstances),
> > so I don't really think this would be an annoyance at all.  The
> number
> > of
> > *unwanted* warnings they'd get would be pretty close to zero.  OTOH,
> in
> > response to a question I asked on StackOverflow, someone posted a
> large
> > list of times where this isn't followed in the std lib, so there
> seems
> > to be a precedent for just using the builtin names for anything
> > one feels like at the time.
> 
> If you run across that again and email me the link, I will take a look
> and see if I think the issue should be raised on pydev. Of course, some
> modules *intentionally* define an open function, intended to be
> accessed
> as 'mod.open' and not as 'from mod import *; open'. Also,
> class/instance
> attributes can also reuse builtin names. But 'open = '
> would
> be bad.
> 
> 
> --
> Terry Jan Reedy
> 

See the accepted answer to this question:
http://stackoverflow.com/questions/7079519/is-there-python-code-in-the-python-standard-library-that-uses-variable-names-that

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


Re: testing if a list contains a sublist

2011-08-17 Thread Ameretat Reith
On Se shanbe 25 Mordad 1390 01:26:54 Johannes wrote:
> hi list,
> what is the best way to check if a given list (lets call it l1) is
> totally contained in a second list (l2)?
> 
> for example:
> l1 = [1,2], l2 = [1,2,3,4,5] -> l1 is contained in l2
> l1 = [1,2,2,], l2 = [1,2,3,4,5] -> l1 is not contained in l2
> l1 = [1,2,3], l2 = [1,3,5,7] -> l1 is not contained in l2
> 
> my problem is the second example, which makes it impossible to work with
> sets insteads of lists. But something like set.issubset for lists would
> be nice.
> 
> greatz Johannes

Hope best answer is found so far. for easy answer, i prefer to use Python 
`==' operator instead of inner loop.

l=[1,2,3,4,5]
s=[1,2,2]
sc=len(s)
for c in xrange(len(l)-sc+1):
if l[c:sc+c] == s:
print ( 'found at {0}'.format(c) )
break

Since sub-lists memory will be garbage collected, there is no problem in 
memory usage, but in time needed for constructing new slice, there is.
-- 
Amir Ghassemi Nasr (Reith)
GPG ID: 371035B4 (http://46.4.214.112/~reith/reith.asc)
GPG Fingerprint: 18E6 CF11 BE80 F541 DC68  B6AF 9373 DE72 3710 35B4

signature.asc
Description: This is a digitally signed message part.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wait for a keypress before continuing?

2011-08-17 Thread Hans Mulder

On 17/08/11 10:03:00, peter wrote:

Is there an equivalent to msvcrt for Linux users?  I haven't found
one, and have resorted to some very clumsy code which turns off
keyboard excho then reads stdin. Seems such an obvious thing to want
to do I am surprised there is not a standard library module for it. Or
have I missed someting (wouldn't be the first time!)


The quick and dirty way is to invoke stty(1) using os.system:

import os

def getpassword(prompt="Password: "):
try:
os.system("stty -echo")
passwd = raw_input(prompt)
finally:
os.system("stty echo")
return passwd


Strictly speaking, os.system is deprecated and you should use
the equivalent invocation of subprocess.call:

import subprocess

def getpassword(prompt="Password: "):
try:
subprocess.call(["stty", "-echo"])
passwd = raw_input(prompt)
finally:
subprocess.call(["stty", "echo"])
return passwd


If you don't want to use an external process, use termios:

import termios, sys

def getpassword(prompt="Password: "):
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
new[3] = new[3] & ~termios.ECHO  # lflags
try:
termios.tcsetattr(fd, termios.TCSADRAIN, new)
passwd = raw_input(prompt)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
return passwd


These functions work on any Posix system (including Mac OSX),
but not on Windows.

Hope this helps,

-- HansM

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


Some warning appears when installing virtualenv, does it matters?

2011-08-17 Thread smith jack
the warning is just as follows


E:\Tools>pip install virtualenv


Downloading/unpacking virtualenv
  Downloading virtualenv-1.6.4.tar.gz (1.9Mb): 1.9Mb downloaded
  Running setup.py egg_info for package virtualenv

warning: no previously-included files matching '*.*' found under directory '
docs\_templates'
Installing collected packages: virtualenv
  Running setup.py install for virtualenv

warning: no previously-included files matching '*.*' found under directory '
docs\_templates'
Installing virtualenv-script.py script to E:\Tools\gov\tools\py_build\Script
s
Installing virtualenv.exe script to E:\Tools\gov\tools\py_build\Scripts
Installing virtualenv.exe.manifest script to E:\Tools\gov\tools\py_build\Scr
ipts
Successfully installed virtualenv
Cleaning up...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: monitor mouse coordinates in real-time

2011-08-17 Thread Jabba Laci
Hi,

Thanks, the problem got solved. The updated version can be found at
https://gist.github.com/1144708 in a comment below the original post.
Solution:

self.connect("destroy", self.quit)

def quit(self, widget):
self.mouseThread.kill()
gtk.main_quit()

It was not evident that quit() must be passed the argument "widget" too.

Thanks,

Laszlo


On Wed, Aug 17, 2011 at 16:48, MrJean1  wrote:
> Check that the app.quit method registered with atexit is called.  E.g.
> on Windows, that may not be the case.
>
> /JeAN
>
>
> On Aug 14, 9:39 am, Jabba Laci  wrote:
>> I'm trying something similar. In the thread there is a variable which
>> is modified by the parent. However, the thread doesn't quit the
>> infinite loop. If someone could provide a patch, that'd be really
>> useful.
>>
>> Thanks,
>>
>> Laszlo
>>
>>
>> On Sun, Aug 14, 2011 at 13:00, TheSaint  wrote:
>> > Jabba Laci wrote:
>>
>> >> Could you please help me out how to close the application correctly?
>>
>> > I think you should put a flag into the code, which the parent might modify
>> > it, so it will tell the child process to quit.
>> > Then the flag should need to be read periodically to know whether is time 
>> > to
>> > quit.
>>
>> > --
>> >http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to Check Write Access of a Folder on Windows

2011-08-17 Thread Tim Golden

On 16/08/2011 13:38, Ayaskant Swain wrote:

Hi Tim,

Thanks for your reply. It seems this issue is related to python bug
-http://bugs.python.org/issue2528
But the patch code looks complex to me. I want to make changes only
in my python script which will read an user given directory path&
check it's write access. What is the use of posixmodule.c file?


Well.. the changes to posixmodule.c, had they been accepted, would
have meant that a call to os.access on Windows would have done the
work to determine whether or not you truly had access. As it is,
that issue has been "demoted" to a doc-and-deprecate bug.

So you either need to do the same sequence of actions (more or
less) or to simulate its effect. Certainly you can retrieve the
ACEs in the DACL via the GetFileSecurity call, and you're then
going to have to compare the effect of all the (possibly
quite complex and inherited) ACEs on the logged-in user's ability
to view the directory.

The ACEs might refer directly to the user or (more likely)
indirectly via groups, including builtins like "Domain Users"
or "Administrators". So you'd have to work out whether your user
was in one of those groups, possibly indirectly as groups can
contain groups.

Certainly all of this is do-able but it won't be trivial. I'm
sorry I can't be more helpful but I haven't had a need for this
functionality myself (even the patch to issue2528 was in response
to someone else's need similar to yours).

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


Re: Syntactic sugar for assignment statements: one value to multiple targets?

2011-08-17 Thread Terry Reedy
The issue behind this thread is that for immutable objects, binding to n 
copies has the same effect as n bindings to one object (so one does not 
really have to know which one is doing), whereas the two are different 
for mutable objects (so one does have to know). In short, identity 
matters for mutables but not for immutables. Python programmers must 
learn both this and the fact that Python does not make copies unless asked.


Adding a special case exception to the latter to mask the former does 
not seem like a good idea.


On 8/17/2011 5:26 AM, gc wrote:


It has only one very modest function, which is to unpack

a, b, c, d, e = *dict()


*expression has already been proposed to generally mean what it does in 
function calls -- unpack the iterator in place.


funnylist = [1,2,*dict,99,100]
# == [1,2]+list(dict)+[99,100]

would interpolate the keys of the dict into the list.

There is a tracker issue for this -- it would be a follow-on to the 
addition of *traget in assignments.


In a real sense, "a,b = iterable" *already* means "a,b = *iterable". If 
*iterable had been in general use from the beginning, presume the latter 
is how we would write sequence unpacking for assignments.



a, b, c, d, e = dict(), dict(), dict(), dict(), dict()


*expression will not be changed in meaning to magically re-evaluate an 
expression some multiple number of times according to code elsewhere.



so that you have n separate objects instead of one. If you want the
same object duplicated five times, you'd best use a=b=c=d=e=dict().


Not 'duplicated', but 'bound'.


(I'd guess that 90% of the people who try the a=b=c version actually
*want* separate objects and are surprised at what they get--I made
that mistake a few times!


Guessing that 90% of people are like you is likely to be wrong.
I think this use case (for more than 2 or 3 copies) is pretty rare for 
most people.


Where many people do trip up is "array = [[0]*i]*j", expecting to get j 
copies of [0]*i rather than j bindings of one object. But then, they 
must have the same wrong idea that [0]*i makes i copies of 0. For 
immutable 0, the misunderstanding does not matter. For mutable [0]*i, it 
does. People *must* learn that sequence multiplication multiplies 
bindings, not (copies of) objects. Both multiple copy problems have the 
same solution:


array = [[0]*i for _ in range(j)]
a,b,c,d,e = [dict() for _ in range(5)]

The fact that the number of assignment sources (possibly after implicit 
unpacking) and targets have to match, unless one uses *target, and that 
both sides need to be changed if one is, is true of all assignments, not 
just this rare case.



--but changing either behavior would be a
very bad idea. This proposed syntax would be the Right Way to get
separate objects.)


It would be very Wrong as it already has a very different meaning.

--
Terry Jan Reedy

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


Re: CGI: Assign FieldStorage values to variables

2011-08-17 Thread Chris Rebert
On Wed, Aug 17, 2011 at 2:19 AM, Gnarlodious  wrote:
> I should add that this does what I want, but something a little more
> Pythonic?
>
> import cgi, os
> os.environ["QUERY_STRING"] = "name1=Val1&name2=Val2&name3=Val3"
> form=cgi.FieldStorage()
>
> form
>
> dict = {}
> for key in form.keys(): dict[ key ] = form[ key ].value
>
> dict
> locals().update(dict)
> name3

Try it within a function. It will fail epic-ly in CPython and most
other implementations.
Read the note in the locals() docs:
http://docs.python.org/library/functions.html#locals

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


Re: Wait for a keypress before continuing?

2011-08-17 Thread Steven D'Aprano
Hans Mulder wrote:

> Strictly speaking, os.system is deprecated and you should use
> the equivalent invocation of subprocess.call:

Strictly speaking, os.system is *not* deprecated in either Python 2.x or
3.x.

Latest stable documentation for Python 2.7 and 3.2:
http://docs.python.org/library/os.html#os.system
http://docs.python.org/py3k/library/os.html#os.system

And docs in development for 3.3 (unstable):
http://docs.python.org/dev/library/os.html#os.system

Deprecation means that there are active plans to remove the feature. There
are no such plans to remove os.system. What the docs say is much milder:

"The subprocess module provides more powerful facilities for spawning new
processes and retrieving their results; using that module is preferable to
using this function."

Using subprocess may be recommended, but that is not the same as saying that
os.system is deprecated. os.system will not be going away any time in the
foreseeable future.


-- 
Steven

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


Re: Wait for a keypress before continuing?

2011-08-17 Thread Seebs
On 2011-08-17, peter  wrote:
> Is there an equivalent to msvcrt for Linux users?  I haven't found
> one, and have resorted to some very clumsy code which turns off
> keyboard excho then reads stdin. Seems such an obvious thing to want
> to do I am surprised there is not a standard library module for it. Or
> have I missed someting (wouldn't be the first time!)

There's no direct equivalent to the whole of msvcrt.  The Unixy way to
do stuff like that on the command line is usually curses.  But to make
a long story short:  Unix evolved in a setting where there was often
not a user at *THE* console, and users were often on devices such that
it made sense to have all the line editing happen on the remote end, with
the remote end sending a completed line once the user was done with all
that stuff like backspaces.

Unix programs that do stuff like this for tty input do exist, of course,
but for the most part, they use an entire API designed for creating such
utilities, rather than one or two specialized functions.  (Another part
of the reason for this:  The Unix solution scales nicely to the case where
the five people using your program will be doing so on physically
different hardware terminals which don't use the same escape sequences
for cursor movement.)

Usually when people omit something obvious from a design, it's because of
other constraints or history to the design which make it less obvious.

-s
-- 
Copyright 2011, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why no warnings when re-assigning builtin names?

2011-08-17 Thread Seebs
On 2011-08-17, Chris Angelico  wrote:
> def foo(list):
>"""Foo's the list provided and returns True on success or False on
> failure."""
>
> def bar(list):
> """Counts the number of bars in the list, assuming it to be made
> of music."""
> if not foo(list): return

> You call foo() once and bar() twice. How many shadowings have there
> been? How many warnings do you get?

I'd say two, one when def foo... is parsed, one when def bar... is parsed.

> A simple implementation would give five warnings for this case - once
> for each invocation that shadows a builtin. Another simple
> implementation would give two warnings, at the time that the def
> statements are executed; this is preferred, but it's still two
> warnings, and if you have a huge set of functions that do this, that
> can easily be "lines and lines" of warnings. Or should it set a flag
> and say "I've already warned this session about shadowing 'list', so
> suppress all others"? That seems confusing.

I guess I don't object to multiple warnings if I do the same thing multiple
times.  I was just thinking in terms of a single parse-time warning for the
actual point at which something is shadowed, rather than, say, a warning
every time a name is hit during execution of statements and refers to a
shadow.

-s
-- 
Copyright 2011, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why no warnings when re-assigning builtin names?

2011-08-17 Thread Seebs
On 2011-08-17, Steven D'Aprano  wrote:
> On Wed, 17 Aug 2011 01:17 pm Seebs wrote:
> [...]
>> "Another" scope is normally a horizontal thing -- you're talking about
>> a different scope such that you are *either* in this one *or* in that
>> one.

>> Built-ins are not in a scope you are never not in.

> That's technically incorrect. Built-ins are a scope you are never in, if
> by "in" you mean "code is executed in this scope".

No, by "in" I mean "lookups from your code will reach this scope if they
don't find something sooner".

>> Hmm.  See, I've never reached that, in Python or any other language.  I
>> figure it creates a new potential for confusion, and that I would rather
>> avoid any ambiguity.  I don't *like* ambiguity in code.

> Ah, well you see the thing is, this is Python. As soon as you call any
> function you don't control, you no longer know what your environment is
> with any certainty. For all you know, the harmless-looking function is
> monkey-patching builtins like there's no tomorrow. Speaking broadly,
> perhaps too broadly, we're incredibly proud of the ability to modify nearly
> everything at runtime.

Heh.

> Fortunately, while we are proud of having that ability, actually *using* it
> is considered a mortal sin. We're not Ruby developers -- if you actually
> monkey-patch something, especially built-ins, you can expect to be taken
> outside and slapped around with a fish if you get caught.

Okay, so.

Here's what I don't get.

If it's such a bad thing, *why is it allowed*?  Why are you proud of the
ability to do something that you are never socially-allowed to do?

I have mixed feelings about Ruby's general tolerance for monkey-patching,
although I've seen it do some pretty awesome things, so I am somewhat
inclined to accept that it may be worth it.  But it's clearly a feature
which is used intentionally.

It sounds to me like Python is very proud of having a feature which no
one would ever use.  ... Why?

> Sure. But they can't have that certainty regardless of whether you shadow
> something, because how do they know whether you've shadowed it or not?

Well, they could trust me.  :)

> In theory, anything could be anything at any time, and you have no
> protection. In practice, I worry more about being eaten by
> genetically-engineered flying piranhas than about rogue monkey-patching
> code.

I do too, if I know that people don't shadow built-ins.  If I know that
people are shadowing built-ins, then some of the time, when I'm editing
other peoples' code, they HAVE effectively monkey-patched it.

-s
-- 
Copyright 2011, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Syntactic sugar for assignment statements: one value to multiple targets?

2011-08-17 Thread MRAB

On 17/08/2011 10:26, gc wrote:

On Aug 17, 3:13 am, Chris Angelico  wrote:


Minor clarification: You don't want to initialize them to the same
value, which you can do already:

a=b=c=d=e=dict()


Right. Call the proposed syntax the "instantiate separately for each
target" operator.  (It can be precisely defined as a * on the RHS of a
one-into-many assignment statement--i.e. an assignment statement with
1 object on the RHS and more than 1 on the LHS).


I think that lazy unpacking is the more important issue because we can
replace instantiation with copying:

def copies(obj, count=None):
if count is None:
while True:
yield obj.copy()
else:
for i in range(count):
yield obj.copy()

(Should it yield deep copies, or should there be a separate deep_copies
function?)


It has only one very modest function, which is to unpack

a, b, c, d, e = *dict()

to

a, b, c, d, e = dict(), dict(), dict(), dict(), dict()


This becomes:

a, b, c, d, e = copies(dict(), 5)

With lazy unpacking it would become:

a, b, c, d, e = lazy copies(dict())

(Or whatever the syntax is.)


so that you have n separate objects instead of one. If you want the
same object duplicated five times, you'd best use a=b=c=d=e=dict().
(I'd guess that 90% of the people who try the a=b=c version actually
*want* separate objects and are surprised at what they get--I made
that mistake a few times!--but changing either behavior would be a
very bad idea. This proposed syntax would be the Right Way to get
separate objects.)

Maybe this is more visibly convenient with a complex class, like

x, y, z = *SuperComplexClass(param1, param2, kwparam = "3", ...)


x, y, z = lazy copies(SuperComplexClass(param1, etc, ...))

[snip]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Wait for a keypress before continuing?

2011-08-17 Thread Terry Reedy

On 8/17/2011 12:33 PM, Seebs wrote:

On 2011-08-17, peter  wrote:

Is there an equivalent to msvcrt for Linux users?  I haven't found
one, and have resorted to some very clumsy code which turns off
keyboard excho then reads stdin. Seems such an obvious thing to want
to do I am surprised there is not a standard library module for it. Or
have I missed someting (wouldn't be the first time!)


There's no direct equivalent to the whole of msvcrt.  The Unixy way to
do stuff like that on the command line is usually curses.  But to make
a long story short:  Unix evolved in a setting where there was often
not a user at *THE* console, and users were often on devices such that
it made sense to have all the line editing happen on the remote end, with
the remote end sending a completed line once the user was done with all
that stuff like backspaces.

Unix programs that do stuff like this for tty input do exist, of course,
but for the most part, they use an entire API designed for creating such
utilities, rather than one or two specialized functions.  (Another part
of the reason for this:  The Unix solution scales nicely to the case where
the five people using your program will be doing so on physically
different hardware terminals which don't use the same escape sequences
for cursor movement.)


The difference is between "Hit  to continue" (which we can do in 
portable Python) versus "Hit any key to continue" (which we cannot, and 
which also leads to the joke about people searching for the 'any' key 
;-). The equivalent contrast for GUIs is "Click OK to continue" versus 
"Click anywhere to continue" If having to click a specific area is okay 
for GUIs, having to hit a specific key for TUIs should be also.



--
Terry Jan Reedy

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


Re: Wait for a keypress before continuing?

2011-08-17 Thread Seebs
On 2011-08-17, Steven D'Aprano  wrote:
> I shouldn't need to say this to anyone over the age of four, but being
> obnoxious to people trying to help does not encourage others to answer your
> question. You don't win points for insulting people who are trying to solve
> your problems.

The frustrating part, of course, is that the people who do this are doing
it for reasons such that the explanation seems only proof that they are even
more right than they had previously expected.

Pathological narcissism is scary.  If you ever find yourself going longer
than usual without being wrong, start checking your work more carefully.  :)

-s
-- 
Copyright 2011, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wait for a keypress before continuing?

2011-08-17 Thread Seebs
On 2011-08-17, Terry Reedy  wrote:
> The difference is between "Hit  to continue" (which we can do in 
> portable Python) versus "Hit any key to continue" (which we cannot, and 
> which also leads to the joke about people searching for the 'any' key 
> ;-).

And more importantly, frustration and confusion when people pick control
or shift.

> The equivalent contrast for GUIs is "Click OK to continue" versus 
> "Click anywhere to continue" If having to click a specific area is okay 
> for GUIs, having to hit a specific key for TUIs should be also.

In general I agree.

-s
-- 
Copyright 2011, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why no warnings when re-assigning builtin names?

2011-08-17 Thread Ethan Furman

Seebs wrote:

On 2011-08-17, Steven D'Aprano wrote:

On Wed, 17 Aug 2011 01:17 pm Seebs wrote:

Hmm.  See, I've never reached that, in Python or any other language.  I
figure it creates a new potential for confusion, and that I would rather
avoid any ambiguity.  I don't *like* ambiguity in code.



Ah, well you see the thing is, this is Python. As soon as you call any
function you don't control, you no longer know what your environment is
with any certainty. For all you know, the harmless-looking function is
monkey-patching builtins like there's no tomorrow. Speaking broadly,
perhaps too broadly, we're incredibly proud of the ability to modify nearly
everything at runtime.


Heh.


Fortunately, while we are proud of having that ability, actually *using* it
is considered a mortal sin. We're not Ruby developers -- if you actually
monkey-patch something, especially built-ins, you can expect to be taken
outside and slapped around with a fish if you get caught.


Okay, so.

Here's what I don't get.

If it's such a bad thing, *why is it allowed*?  Why are you proud of the
ability to do something that you are never socially-allowed to do?


Monkey-patching built-ins would be something along the lines of

import sys
sys.modules['__builtin__'].str = my_super_string

and is what stands you in jeopardy of being fish-slapped.  ;)

Merely shadowing a built-in, or stdlib, or whatever, isn't monkey-patching.


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


Re: Wait for a keypress before continuing?

2011-08-17 Thread Ethan Furman

Seebs wrote:

Pathological narcissism is scary.  If you ever find yourself going longer
than usual without being wrong, start checking your work more carefully.  :)



+1 QOTW
--
http://mail.python.org/mailman/listinfo/python-list


Re: Syntactic sugar for assignment statements: one value to multiple targets?

2011-08-17 Thread Chris Angelico
On Wed, Aug 17, 2011 at 5:55 PM, MRAB  wrote:
> x, y, z = lazy copies(SuperComplexClass(param1, etc, ...))
>

This assumes that you can construct it once and then copy it reliably,
which may mean that the class implement copying correctly. It also
wouldn't work with:

a, b, c, d = *random.randint(1,20)

which would roll 4d20 and get the results in separate variables. The
OP's idea of separately evaluating the expression would; but to do it
with copying would require a special "randint" object that functions
exactly as an integer but, when copied, would re-randomize.

Perhaps * is the wrong syntactic element to use. Maybe it needs a
special assignment operator:

a, b, c, d @= random.randint(1,20)

which would evaluate its left operand as a tuple of lvalues, then
evaluate its right operand once for each element in the left operand,
and assign to each element in turn. (I've no idea what form of
assignment operator would be suitable, but @= is currently illegal, so
it ought to be safe at least for discussion purposes.)

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


Re: Why no warnings when re-assigning builtin names?

2011-08-17 Thread Seebs
On 2011-08-17, Ethan Furman  wrote:
> Seebs wrote:
>> On 2011-08-17, Steven D'Aprano wrote:
>>> Ah, well you see the thing is, this is Python. As soon as you call any
>>> function you don't control, you no longer know what your environment is
>>> with any certainty. For all you know, the harmless-looking function is
>>> monkey-patching builtins like there's no tomorrow. Speaking broadly,
>>> perhaps too broadly, we're incredibly proud of the ability to modify nearly
>>> everything at runtime.

>>> Fortunately, while we are proud of having that ability, actually *using* it
>>> is considered a mortal sin. We're not Ruby developers -- if you actually
>>> monkey-patch something, especially built-ins, you can expect to be taken
>>> outside and slapped around with a fish if you get caught.

>> Here's what I don't get.

>> If it's such a bad thing, *why is it allowed*?  Why are you proud of the
>> ability to do something that you are never socially-allowed to do?

> Monkey-patching built-ins would be something along the lines of

>  import sys
>  sys.modules['__builtin__'].str = my_super_string

> and is what stands you in jeopardy of being fish-slapped.  ;)

> Merely shadowing a built-in, or stdlib, or whatever, isn't monkey-patching.

Oh, I know.  I was just noticing that Steven's post is specifically talking
about how Python users are proud of having the ability to monkey-patch.

If monkey-patching like that is a mortal sin, leads to fish-slapping, and
so on..

Why is it possible?  Why not just reject such things as invalid code?

-s
-- 
Copyright 2011, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why no warnings when re-assigning builtin names?

2011-08-17 Thread Chris Angelico
On Wed, Aug 17, 2011 at 5:33 PM, Seebs  wrote:
> If it's such a bad thing, *why is it allowed*?  Why are you proud of the
> ability to do something that you are never socially-allowed to do?
>

Going back to my original three examples:

> 1) Deliberate shadowing because you want to change the behavior of the
> name. Extremely rare.
> 2) Shadowing simply by using the name of an unusual builtin (like
> 'file') in a context where you never use it. Very common.
> 3) Unintentional shadowing where you create a variable, but then
> intend to use the builtin. This is the only one that's a problem.

All three are allowed, but it's the first one that's considered
unusual. The second one is simply that Python doesn't have a million
and one reserved words. Yes, you probably don't want to use 'print' as
a variable name, but shadowing it with an exact equivalent would be
fine (eg to automatically date-stamp or log your output, without
changing your code). And as described above, using list/str/id etc is
not uncommon.

I greatly prefer this to the alternative, which is another 133
reserved words (based on Python 3.2 for Windows).

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


Re: Why no warnings when re-assigning builtin names?

2011-08-17 Thread Seebs
On 2011-08-17, Chris Angelico  wrote:
> On Wed, Aug 17, 2011 at 5:33 PM, Seebs  wrote:
>> If it's such a bad thing, *why is it allowed*? ?Why are you proud of the
>> ability to do something that you are never socially-allowed to do?

> Going back to my original three examples:

I may have been unclear about jumping topics; that comment was about
monkey-patching, not about shadowing.

> I greatly prefer this to the alternative, which is another 133
> reserved words (based on Python 3.2 for Windows).

You have a point there.

I guess I'm just used to the assumption that the confusion caused by
shadowing names outweighs the benefits of using them -- the world is rich
with plausible names.

-s
-- 
Copyright 2011, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why no warnings when re-assigning builtin names?

2011-08-17 Thread Ethan Furman

Seebs wrote:

On 2011-08-17, Ethan Furman  wrote:

Seebs wrote:

On 2011-08-17, Steven D'Aprano wrote:

Ah, well you see the thing is, this is Python. As soon as you call any
function you don't control, you no longer know what your environment is
with any certainty. For all you know, the harmless-looking function is
monkey-patching builtins like there's no tomorrow. Speaking broadly,
perhaps too broadly, we're incredibly proud of the ability to modify nearly
everything at runtime.



Fortunately, while we are proud of having that ability, actually *using* it
is considered a mortal sin. We're not Ruby developers -- if you actually
monkey-patch something, especially built-ins, you can expect to be taken
outside and slapped around with a fish if you get caught.



Here's what I don't get.



If it's such a bad thing, *why is it allowed*?  Why are you proud of the
ability to do something that you are never socially-allowed to do?



Monkey-patching built-ins would be something along the lines of



 import sys
 sys.modules['__builtin__'].str = my_super_string



and is what stands you in jeopardy of being fish-slapped.  ;)



Merely shadowing a built-in, or stdlib, or whatever, isn't monkey-patching.


Oh, I know.  I was just noticing that Steven's post is specifically talking
about how Python users are proud of having the ability to monkey-patch.

If monkey-patching like that is a mortal sin, leads to fish-slapping, and
so on..

Why is it possible?  Why not just reject such things as invalid code?


Well, the mortal sin part is a bit of an exaggeration -- it's more like 
you'd better have a really darn good reason to do it.  And it is 
absolutely one of my favorite parts about Python.  If I want to inject a 
custom Path class into builtins so it's readily available, and then 
change os.listdir to return it instead of normal strings, I can.  If my 
application is truly case-insensitive, I can make my own istr class and 
monkey-patch builtins so it's what is used.  Can this blow-up in my 
face?  Certainly.  But I would rather have the option open to me instead 
of being told "No, I'm sorry, you can't do that because I (developers in 
question) didn't imagine a good use case for it".


Part of the fun of Python is experimentation.  And how much fun is it to 
be told over and over, "No, you can't do that"?


As an example of something that could easily have been outlawed, but 
wasn't, check out http://stackoverflow.com/questions/7068340


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


Re: Why no warnings when re-assigning builtin names?

2011-08-17 Thread Chris Angelico
On Wed, Aug 17, 2011 at 6:38 PM, Seebs  wrote:
> I may have been unclear about jumping topics; that comment was about
> monkey-patching, not about shadowing.
>

Ah, apologies.

Monkey-patching is a way of using the middle of a stack of code
without using what's below it. If everything is statically linked,
then every function does exactly what it was written to do and no
more; if it accepts a file object as an argument, you could give it
some other file-like object, but that's all. However, if the function
was written to use print() and you don't want it to print to the
screen, what do you do? Obviously it's your responsibility to ensure
that your replacement is 100% equivalent in the required
functionality, but it's a great flexibility to simply change the
meaning of "print"; the alternative is to copy and paste the code,
make one change (or even no change at all, if your replacement print()
is a global), and run that.

As Ethan posted while I was typing this, you're allowed to do it, but
you just need to have a good reason for it. I like to explain/justify
myself in comments when these things crop up in my code.

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


Re: Why no warnings when re-assigning builtin names?

2011-08-17 Thread Seebs
On 2011-08-17, Ethan Furman  wrote:
> Part of the fun of Python is experimentation.  And how much fun is it to 
> be told over and over, "No, you can't do that"?

Okay, I buy that.

Actually, this sort of fits with my experience of how (sane) people do it
in Ruby.

And I'm really the wrong person to criticize people for monkey-patching:

http://www.yoctoproject.org/projects/pseudo

(In which I monkeypatch *the entire Unix filesystem API*.  On Linux and
OS X.  For C programs.)

I guess maybe my question shouldn't have been "why is it allowed", but "and
why is it bad to use it?"  It just seemed like "you should never do this,
it's horrible" and "we're proud of being able to do this" were not entirely
compatible.

-s
-- 
Copyright 2011, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


How to build python using visual studio 2005?

2011-08-17 Thread smith jack
anybody here have build it correctly?
how to make a msi file just as the official site did?
is there any detailed tutorial online?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wait for a keypress before continuing?

2011-08-17 Thread Steven D'Aprano
Terry Reedy wrote:

> The difference is between "Hit  to continue" (which we can do in
> portable Python) versus "Hit any key to continue" (which we cannot, and
> which also leads to the joke about people searching for the 'any' key
> ;-). The equivalent contrast for GUIs is "Click OK to continue" versus
> "Click anywhere to continue" If having to click a specific area is okay
> for GUIs, having to hit a specific key for TUIs should be also.

Poor analogy. A better analogy to a GUI would be comparing:


What would you like to do? Select an option and then click OK:
( ) Cancel
( ) Print
(x) Save
   [__OK__]


versus:


What would you like to do?
[__Cancel__]  [__Print__]  [__Save__]


Actually, a better analogy would be a GUI that made you do this:


What would you like to do? Type the first letter of the option 
you prefer in the text field, then click the OK button:
Options:  Cancel | Print | Save
My option: [  ][__OK__]


(ASCII art best viewed with a fixed-width font.)

Generally speaking, the second UI would be preferred.

The raw_input/input UI is well-designed for entering plain text data. It is
extremely poor as a command interface.

Bringing it back to text interfaces, it would be useful to have a text
interface such that commands can be executed using a single key press. You
might want to detect and respond to (say) the arrow keys, or ESC, or P
rather than P. Curses apps can do it, proof that even under Unix it
is desirable. (Imagine how awkward it would be to use a TUI mail client or
text editor where the only user input was from something like raw_input.)
Unfortunately curses is quite heavyweight for a simple CLI script.

I note also that even the Python interactive interpreter under Linux has an
extremely limited detect-single-keypress capability: Ctrl-C generates a
KeyboardInterrupt without needing to hit Enter, and Ctrl-D exits the
interpreter.



-- 
Steven

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


Re: Syntactic sugar for assignment statements: one value to multiple targets?

2011-08-17 Thread OKB (not okblacke)
gc wrote:

> Maybe this is more visibly convenient with a complex class, like
> 
> x, y, z = *SuperComplexClass(param1, param2, kwparam = "3", ...)
> 
> where you need three separate objects but don't want to duplicate the
> class call (for obvious copy-paste reasons) and where bundling it in a
> list comprehension:
> 
> x, y, z = [SuperComplexClass(param1, etc, ...) for _ in range(3)]
> 
> layers gunk on top of something that's already complex.

That just seems like an odd use case to me.  I rarely find myself 
wanting to make exactly N copies of the same thing and assign them to 
explicit names.  If I'm not making just one, it's usually because 
I'm making some sort of list or dict of them that will be accessed by 
index (not with names like "x", "y", and "z"), in which case a list 
comprehension is the right way to go.

-- 
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
--author unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Syntactic sugar for assignment statements: one value to multiple targets?

2011-08-17 Thread Ethan Furman

gc wrote:

Target lists using comma separation are great, but they don't work
very well for this task. What I want is something like

a,b,c,d,e = *dict()


This isn't going to happen.  From all the discussion so far I think your 
best solution is a simple helper function (not tested):


def repeat(count_, object_, *args, **kwargs):
result = []
for _ in range(count_):
result.append(object_(*args, **kwargs))
return result

a, b, c, d, e = repeat(5, dict)

These are each new objects, so depending on the function (like the 
random.rand_int example) the values may not be the same.


Oh, and I put the trailing _ on count and object to minimize possible 
conflicts with keyword arguments.


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


Re: Syntactic sugar for assignment statements: one value to multiple targets?

2011-08-17 Thread Zero Piraeus
:

Off on a tangent ...

On 16 August 2011 20:14, gc  wrote:
>
> Let me address one smell from my particular example, which may be the
> one you're noticing. If I needed fifty parallel collections I would
> not use separate variables; I've coded a ghastly defaultdefaultdict
> just for this purpose, which effectively permits what most people
> would express as defaultdict(defaultdict(list)) [not possible AFAIK
> with the existing defaultdict class].

Dunno if it's better than your ghastly defaultdefaultdict, but this works:

>>> from collections import defaultdict
>>> ddd = defaultdict(lambda: defaultdict(list))
>>> ddd["foo"]["bar"].append("something")
>>> ddd["foo"]["bar"]
['something']
>>>

 -[]z.
-- 
http://mail.python.org/mailman/listinfo/python-list


pairwise combination of two lists

2011-08-17 Thread Yingjie Lin
Hi Python users,

I have two lists: 

li1 = ['a', 'b']
li2 = ['1', '2']

and I wish to obtain a list like this

li3 = ['a1', 'a2', 'b1', 'b2']

Is there a handy and efficient function to do this, especially when li1 and li2 
are long lists.
I found zip() but it only gives [('a', '1'), ('b', '2')],  not exactly what I 
am looking for.

Thank you.


- Yingjie







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


Re: pairwise combination of two lists

2011-08-17 Thread Mel
Yingjie Lin wrote:
> I have two lists:
> 
> li1 = ['a', 'b']
> li2 = ['1', '2']
> 
> and I wish to obtain a list like this
> 
> li3 = ['a1', 'a2', 'b1', 'b2']
> 
> Is there a handy and efficient function to do this, especially when li1
> and li2 are long lists.
> I found zip() but it only gives [('a', '1'), ('b', '2')],  not exactly
> what I am looking for.

This seems to do it :

mwilson@tecumseth:~$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import itertools
>>> li1 = ['a', 'b']
>>> li2 = ['1', '2']
>>> map (lambda (x,y):x+y, list (itertools.product (li1, li2)))
['a1', 'a2', 'b1', 'b2']


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


Re: pairwise combination of two lists

2011-08-17 Thread Mel
Mel wrote:

> Yingjie Lin wrote:
>> I have two lists:
>> 
>> li1 = ['a', 'b']
>> li2 = ['1', '2']
>> 
>> and I wish to obtain a list like this
>> 
>> li3 = ['a1', 'a2', 'b1', 'b2']
[ ... ]
> This seems to do it :
> 
> mwilson@tecumseth:~$ python
> Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
> [GCC 4.4.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 import itertools
 li1 = ['a', 'b']
 li2 = ['1', '2']
 map (lambda (x,y):x+y, list (itertools.product (li1, li2)))
> ['a1', 'a2', 'b1', 'b2']


I have doubts about this in Python3, since tuple unpacking in a argument 
list isn't done there, and I don't think sum works on strings.  Some other 
function can probably be made to work.

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


Re: pairwise combination of two lists

2011-08-17 Thread Ned Deily
In article <98cc6556-11f3-4850-bd2b-30481b530...@mssm.edu>,
 Yingjie Lin  wrote:
> I have two lists: 
> 
> li1 = ['a', 'b']
> li2 = ['1', '2']
> 
> and I wish to obtain a list like this
> 
> li3 = ['a1', 'a2', 'b1', 'b2']
> 
> Is there a handy and efficient function to do this, especially when li1 and 
> li2 are long lists.
> I found zip() but it only gives [('a', '1'), ('b', '2')],  not exactly what I 
> am looking for.

>>> from itertools import product
>>> li1 = ['a', 'b']
>>> li2 = ['1', '2']
>>> li3 = list("".join(x) for x in product(li1, li2))
>>> li3
['a1', 'a2', 'b1', 'b2']

-- 
 Ned Deily,
 n...@acm.org

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


Re: pairwise combination of two lists

2011-08-17 Thread Kev Dwyer
Yingjie Lin wrote:

> Hi Python users,
> 
> I have two lists:
> 
> li1 = ['a', 'b']
> li2 = ['1', '2']
> 
> and I wish to obtain a list like this
> 
> li3 = ['a1', 'a2', 'b1', 'b2']
> 
> Is there a handy and efficient function to do this, especially when li1
> and li2 are long lists.
> I found zip() but it only gives [('a', '1'), ('b', '2')],  not exactly
> what I am looking for.
> 
> Thank you.
> 
> 
> - Yingjie

Hello Yingjie,

This isn't exactly handy, but...

>>> import itertools
>>> a = ('a', 'b')
>>> b = (1, 2)
>>> [x + str(y) for (x, y) in itertools.product(*(a, b))]
['a1', 'a2', 'b1', 'b2']


Cheers,

Kev


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


Re: pairwise combination of two lists

2011-08-17 Thread Marc Christiansen
Yingjie Lin  wrote:
> Hi Python users,
> 
> I have two lists: 
> 
> li1 = ['a', 'b']
> li2 = ['1', '2']
> 
> and I wish to obtain a list like this
> 
> li3 = ['a1', 'a2', 'b1', 'b2']
> 
> Is there a handy and efficient function to do this, especially when
> li1 and li2 are long lists.

Depending on your needs, we can offer you three solutions:

For our customers who want it all at once, but without any unneccessary
waste, the list expression:
[a + b for a, b in itertools.product(li1, li2)]

or if you don't need the whole list at once (especially interesting for
our customers with large lists), the generator expression (genexp):
(a + b for a, b in itertools.product(li1, li2))

and if you don't like the throwaway genexp and want something more
ecofriedly, we can present you a memory efficient, reusable solution, the
generator:
def combiner(li1, li2):
for a, b in itertools.product(li1, li2):
yield a + b

;)

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


Re: Wait for a keypress before continuing?

2011-08-17 Thread Chris Angelico
On Wed, Aug 17, 2011 at 7:29 PM, Steven D'Aprano
 wrote:
> The raw_input/input UI is well-designed for entering plain text data. It is
> extremely poor as a command interface.
>
> ... (Imagine how awkward it would be to use a TUI mail client or
> text editor where the only user input was from something like raw_input.)

I run a MUD and play several. MUDs by definition have only line-based
input (if you use a raw TELNET client, you have character-based input,
but most MUD clients send entire lines of text at once); yet it is
possible to implement a reasonably-viable file editor. It's not
difficult to become quite proficient with line-based editors,
especially if you rig some client-side support (which I have done on
two of the MUDs).

Line-based input is excellent as a command interface, if commands
consist of verbs and parameters. It's terrible for playing Tetris on.

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


Re: Ten rules to becoming a Python community member.

2011-08-17 Thread SigmundV
Bloody hell! This is the most persistent troll I've seen to date. He
expected to get a raging army of pythoners after him, but people are
just laughing at him. This is a mailing list, not a novel, so
colloquialisms are welcome. The language on a mailing list should be
informal and not necessarily grammatically correct.

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


Re: pairwise combination of two lists

2011-08-17 Thread Luis M . González
This is the easiest and most pythonic way (IMHO):

 l3 = [i+e for i in li1 for e in li2]
 l3
['a1', 'a2', 'b1', 'b2']

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


Re: Why no warnings when re-assigning builtin names?

2011-08-17 Thread Steven D'Aprano
Seebs wrote:

> On 2011-08-17, Steven D'Aprano 
> wrote:

>> Fortunately, while we are proud of having that ability, actually *using*
>> it is considered a mortal sin. We're not Ruby developers -- if you
>> actually monkey-patch something, especially built-ins, you can expect to
>> be taken outside and slapped around with a fish if you get caught.
> 
> Okay, so.
> 
> Here's what I don't get.
> 
> If it's such a bad thing, *why is it allowed*?  Why are you proud of the
> ability to do something that you are never socially-allowed to do?

Why does any language allow monkey-patching? Because:

(1) it is a consequence of a clean language design that doesn't special case
things unless absolutely necessary -- monkey-patching wasn't added to the
language, it just emerged given the basic language design;

(2) consequently it isn't some special technique, it is just a special name
given to ordinary, humdrum, everyday things like name-binding within a
namespace;

(3) and yet it is a powerful and useful ability that lets you extend both
the language and libraries (yours or third party) while still writing very
clean code;

(4) it's also pretty cool that you can do these things; and most importantly

(5) all of the above.


Even if we shouldn't (ab)use it in production, it is still greatly useful
for quick and dirty scripts, testing, experimentation and debugging.

And sometimes monkey-patches end up in production. For example, the standard
library site.py file adds help() and quit() commands to builtins at
startup. Or you might grab an instance of some third-party class, and
dynamically adding a method or an attribute to it. Why bother sub-classing
it?

There's a scene in James Clavell's "Shogun" which is relevant. Toranaga, the
Japanese warlord, discovers that the Englishman John Blackthorne has
betrayed his rightful ruler. Blackthorne protests that there are mitigating
circumstances. Toranaga says that there can never be any mitigating
circumstances for disloyalty to one's liege-lord.

Blackthorne replies that there is one: if you win.

The same applies for monkey-patching and other dangerous techniques. There
can be no excuse for doing something like that in production... unless it
is better than the alternatives.


[...]
> It sounds to me like Python is very proud of having a feature which no
> one would ever use.  ... Why?

Don't get me wrong, there are plenty of people who would give up Python's
extreme dynamicism is a heartbeat, if it were up to them. It does play
havoc with the ability to optimise Python code, and is one of the reasons
why CPython isn't as fast as (say) Lua. But the PyPy people are well on the
way to blunting that criticism, with a fast, effective JIT optimising
compiler that will be fast in the common case and no worse off in the rare
times that built-in functions have been shadowed or modified.

(PyPy is already about twice as fast as CPython, and in a few carefully
crafted examples faster than C code.)



-- 
Steven

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


Re: pairwise combination of two lists

2011-08-17 Thread Gary Herron

On 08/17/2011 01:22 PM, Yingjie Lin wrote:

Hi Python users,

I have two lists:

li1 = ['a', 'b']
li2 = ['1', '2']

and I wish to obtain a list like this

li3 = ['a1', 'a2', 'b1', 'b2']

Is there a handy and efficient function to do this, especially when li1 and li2 
are long lists.
I found zip() but it only gives [('a', '1'), ('b', '2')],  not exactly what I 
am looking for.

Thank you.


- Yingjie

>>> li1 = ['a', 'b']
>>> li2 = ['1', '2']
>>> print [a+b   for a in li1   for b in li2]
['a1', 'a2', 'b1', 'b2']


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


lists and for loops

2011-08-17 Thread Emily Anne Moravec
I want to add 5 to each element of a list by using a for loop.

Why doesn't this work?

numbers = [1, 2, 3, 4, 5]
for n in numbers:
 n = n + 5
print numbers


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


Re: How to use python environment created using virtualenv?

2011-08-17 Thread alex23
On Aug 16, 3:15 pm, smith jack  wrote:
> I have created a python environment using virtualenv, but when i want
> to import such environment to PyDev, error just appears,
> it tells there should be a Libs dir, but there is no Libs DIr in the
> virtual envronment created using virtualenv, what should i do if
> i want to use this virtual environment?

It would help if you showed us _exactly_ what commands you're using
for creating & activing your virtualenv, as well as how you're trying
to use it in PyDev. Basically, you should be able to do this:

X:\>virtualenv foo
New python executable in foo\Scripts\python.exe
Installing setuptoolsdone.
Installing pip...done.
X:\>cd foo
X:\foo>Scripts\activate.bat
(foo) X:\foo>


If this doesn't work for you, please paste exactly what you tried and
the results you got.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Failed to create virtual environment when using --relocatable option, what's wrong?

2011-08-17 Thread alex23
On Aug 17, 12:23 am, smith jack  wrote:
> The environment doesn't have a file 
> f:\PythonEnv\djangoEnv2\Scripts\activate_thi
> s.py -- please re-run virtualenv on this environment to update it

Although the docs aren't very clear, --relocatable should be run on
_existing_ virtualenvs. Don't think of it as an option for creating an
environment, but rather one for preparing an existing environment for
moving.

More importantly, it _must_ be re-run in order to remain relocatable
after any modules are installed.

But most important of all, from the documentation: "Also this does not
currently work on Windows."




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


Re: lists and for loops

2011-08-17 Thread Jack Trades
>
> I want to add 5 to each element of a list by using a for loop.
>
> Why doesn't this work?
>
> numbers = [1, 2, 3, 4, 5]
> for n in numbers:
> n = n + 5
> print numbers
>
>
The n variable in the for loop refers to each value in the list, not the
reference to the slot that value is stored in.

To update the numbers list you would want something like this:

numbers = [1, 2, 3, 4, 5]
for n in range(len(numbers)):
  numbers[n] += 5
print numbers

Alternatively if you didn't need to update the numbers list you could make a
new list like this:

[n+5 for n in numbers]

-- 
Jack Trades 
Pointless Programming Blog 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lists and for loops

2011-08-17 Thread alex23
On Aug 18, 1:08 pm, Emily Anne Moravec  wrote:
> I want to add 5 to each element of a list by using a for loop.
>
> Why doesn't this work?
>
> numbers = [1, 2, 3, 4, 5]
> for n in numbers:
>      n = n + 5
> print numbers

As the for loop steps through numbers, it assigns each integer value
to the label n. What n holds is a number, _not_ a reference to the
number in the list. So when you reassign n to hold n+5, you're
pointing n at a new number, not modifying the original number being
referred to.

So what you need is a reference to the position of the number in the
list, so you can reassign the value that's held there. The common
pattern is to use enumerate, which lets you step through a list giving
you both an reference (index) & a value:

numbers = [1, 2, 3, 4, 5]
for i, n in enumerate(numbers):
numbers[i] = n + 5

Here you're reassigning each list element to hold its old value plus
5.

Hope this helps.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CGI: Assign FieldStorage values to variables

2011-08-17 Thread Gnarlodious
On Aug 17, 3:25 am, Chris Angelico wrote:
> You do NOT
> want end users having the power to set variables.
Thanks for the warning, I can see I will need to quarantine the form
input. And update() is out of the question.

-- Gnarlie
http://Gnarlodious.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


MailingLogger 3.4.0 Released!

2011-08-17 Thread Chris Withers

I'm pleased to announce a new release of Mailinglogger.

Mailinglogger provides two handlers for the standard python
logging framework that enable log entries to be emailed either as the
entries are logged or as a summary at the end of the running process.

The handlers have the following features:

- customisable and dynamic subject lines for emails sent

- emails sent with a configurable headers for easy filtering

- flood protection to ensure the number of emails sent is not excessive

- support for SMTP servers that require authentication

- fully documented and tested

This release has no functional changes but finally ships with a full new 
set of Sphinx docs:


http://packages.python.org/mailinglogger/

For more information, please see:
http://www.simplistix.co.uk/software/python/mailinglogger
or
http://pypi.python.org/pypi/mailinglogger

cheers,

Chris

--
Simplistix - Content Management, Zope & Python Consulting
   - http://www.simplistix.co.uk



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