Re: Incorrect scope of list comprehension variables

2010-04-04 Thread Stephen Hansen

On 2010-04-03 23:30:32 -0700, Steve Howell said:


On Apr 3, 9:58 pm, Tim Roberts  wrote:

Alain Ketterlin  wrote:


I've just spent a few hours debugging code similar to this:



d = dict()
for r in [1,2,3]:
   d[r] = [r for r in [4,5,6]]
print d


Yes, this has been fixed in later revisions, but I'm curious to know what
led you to believe that a list comprehension created a new scope.  I don't
that was ever promised.


Common sense about how programming languages should work?  As
confirmed by later revisions?


Where exactly does this common sense come from? A list comprehension is 
basically syntactic sugar over a for loop, and...


Python 3.1.2 (r312:79360M, Mar 24 2010, 01:33:18) 
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin

Type "copyright", "credits" or "license()" for more information.

for x in range(10):

pass


x

9


--
--S

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

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


Re: Splitting a string

2010-04-04 Thread Steven D'Aprano
On Sat, 03 Apr 2010 20:10:20 -0700, Patrick Maupin wrote:

> On Apr 3, 10:00 pm, Steven D'Aprano  cybersource.com.au> wrote:
>> Tests which you know can't fail are called assertions, pre-conditions
>> and post-conditions. We test them because if we don't, they will fail
>> :)
> 
> Well, yes, but that can get rather tedious at times:
> 
> a = 1
> assert 0 < a < 2

Please tell me that's just an exaggerated example for illustration 
purposes, and that you don't *actually* do that!

In any case, the *right* test would be:

a = 1
assert a == 1 and a*5==5 and str(a)=='1' and [None,a,None][a] is a

*wink*



> At least, I usually ameliorate the pain a little bit by not bothering to
> print any debugging information at the assertions until one of them
> actually fails; otherwise I'd *never* get any real coding done :-)


Ditto.



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


"JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON

2010-04-04 Thread saima81
"JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in
california for british" "jobs in california los angeles" "jobs in
california usa" "california jobs" "california jobs for canadians" ON
http://jobsincalifornia-usa.blogspot.com/  "JOBS IN CALIFORNIA"
"jobs in california orange county" "jobs in california for british"
"jobs in california los angeles" "jobs in california usa" "california
jobs" "california jobs for canadians" ON 
http://jobsincalifornia-usa.blogspot.com/
"JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in
california for british" "jobs in california los angeles" "jobs in
california usa" "california jobs" "california jobs for canadians" ON
http://jobsincalifornia-usa.blogspot.com/  "JOBS IN CALIFORNIA"
"jobs in california orange county" "jobs in california for british"
"jobs in california los angeles" "jobs in california usa" "california
jobs" "california jobs for canadians" ON 
http://jobsincalifornia-usa.blogspot.com/
"JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in
california for british" "jobs in california los angeles" "jobs in
california usa" "california jobs" "california jobs for canadians" ON
http://jobsincalifornia-usa.blogspot.com/  "JOBS IN CALIFORNIA"
"jobs in california orange county" "jobs in california for british"
"jobs in california los angeles" "jobs in california usa" "california
jobs" "california jobs for canadians" ON 
http://jobsincalifornia-usa.blogspot.com/
"JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in
california for british" "jobs in california los angeles" "jobs in
california usa" "california jobs" "california jobs for canadians" ON
http://jobsincalifornia-usa.blogspot.com/  "JOBS IN CALIFORNIA"
"jobs in california orange county" "jobs in california for british"
"jobs in california los angeles" "jobs in california usa" "california
jobs" "california jobs for canadians" ON 
http://jobsincalifornia-usa.blogspot.com/
"JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in
california for british" "jobs in california los angeles" "jobs in
california usa" "california jobs" "california jobs for canadians" ON
http://jobsincalifornia-usa.blogspot.com/  "JOBS IN CALIFORNIA"
"jobs in california orange county" "jobs in california for british"
"jobs in california los angeles" "jobs in california usa" "california
jobs" "california jobs for canadians" ON 
http://jobsincalifornia-usa.blogspot.com/
"JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in
california for british" "jobs in california los angeles" "jobs in
california usa" "california jobs" "california jobs for canadians" ON
http://jobsincalifornia-usa.blogspot.com/  "JOBS IN CALIFORNIA"
"jobs in california orange county" "jobs in california for british"
"jobs in california los angeles" "jobs in california usa" "california
jobs" "california jobs for canadians" ON 
http://jobsincalifornia-usa.blogspot.com/
"JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in
california for british" "jobs in california los angeles" "jobs in
california usa" "california jobs" "california jobs for canadians" ON
http://jobsincalifornia-usa.blogspot.com/  "JOBS IN CALIFORNIA"
"jobs in california orange county" "jobs in california for british"
"jobs in california los angeles" "jobs in california usa" "california
jobs" "california jobs for canadians" ON 
http://jobsincalifornia-usa.blogspot.com/
"JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in
california for british" "jobs in california los angeles" "jobs in
california usa" "california jobs" "california jobs for canadians" ON
http://jobsincalifornia-usa.blogspot.com/  "JOBS IN CALIFORNIA"
"jobs in california orange county" "jobs in california for british"
"jobs in california los angeles" "jobs in california usa" "california
jobs" "california jobs for canadians" ON 
http://jobsincalifornia-usa.blogspot.com/
"JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in
california for british" "jobs in california los angeles" "jobs in
california usa" "california jobs" "california jobs for canadians" ON
http://jobsincalifornia-usa.blogspot.com/  "JOBS IN CALIFORNIA"
"jobs in california orange county" "jobs in california for british"
"jobs in california los angeles" "jobs in california usa" "california
jobs" "california jobs for canadians" ON 
http://jobsincalifornia-usa.blogspot.com/
"JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in
california for british" "jobs in california los angeles" "jobs in
california usa" "california jobs" "california jobs for canadians" ON
http://jobsincalifornia-usa.blogspot.com/  "JOBS IN CALIFORNIA"
"jobs in california orange county" "jobs in california for british"
"jobs in california los angeles" "jobs in california usa" "california
jobs" "california jobs for canadians" ON 
http://jobsincalifornia-usa.blogspot.com/
"JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in
california for british" "jobs in c

vars().has_key() question about how working .

2010-04-04 Thread [email protected]
Hi everyone .
My questions is "why vars().has_key('b') is False ?'
I expecting to see "True" because is a variable ...
Thanks
Please see code bellow .
>>> x=11
>>> def something():
... b=25
...
>>> vars().has_key('x')
True
>>> vars().has_key('b')
False
>>> globals().has_key('x')
True
>>> globals().has_key('b')
False
>>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: vars().has_key() question about how working .

2010-04-04 Thread Chris Rebert
On Sun, Apr 4, 2010 at 1:42 AM, [email protected]
 wrote:
> Hi everyone .
> My questions is "why vars().has_key('b') is False ?'
> I expecting to see "True" because is a variable ...

The built-in constants and functions aren't global variables, they're
in the special __builtins__ dictionary/namespace, and thus not part of
globals() or vars().

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


Re: vars().has_key() question about how working .

2010-04-04 Thread Paul McGuire
On Apr 4, 3:42 am, "[email protected]" 
wrote:
> Hi everyone .
> My questions is "why vars().has_key('b') is False ?'
> I expecting to see "True" because is a variable ...
> Thanks

Yes, 'b' is a var, but only within the scope of something().  See how
this is different:

>>> def sth():
...   b = 25
...   print 'b' in vars()
...
>>> sth()
True

(Also, has_key() is the old-style way to test for key existence in a
dict, and is kept around for compatibility with old code, but the
preferred method now is to use 'in'.)

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


Re: vars().has_key() question about how working .

2010-04-04 Thread Cata
So is not possible to testing if a variable is defined with this functions
vars(), globals(), locals() ?
Or maybe i make confusion with another issue.
Please more specific ... Thank you

2010/4/4 Chris Rebert 

> On Sun, Apr 4, 2010 at 1:42 AM, [email protected]
>  wrote:
> > Hi everyone .
> > My questions is "why vars().has_key('b') is False ?'
> > I expecting to see "True" because is a variable ...
>
> The built-in constants and functions aren't global variables, they're
> in the special __builtins__ dictionary/namespace, and thus not part of
> globals() or vars().
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: vars().has_key() question about how working .

2010-04-04 Thread Chris Rebert
> 2010/4/4 Chris Rebert 
>>
>> On Sun, Apr 4, 2010 at 1:42 AM, [email protected]
>>  wrote:
>> > Hi everyone .
>> > My questions is "why vars().has_key('b') is False ?'
>> > I expecting to see "True" because is a variable ...
>>
>> The built-in constants and functions aren't global variables, they're
>> in the special __builtins__ dictionary/namespace, and thus not part of
>> globals() or vars().

On Sun, Apr 4, 2010 at 2:02 AM, Cata  wrote:
> So is not possible to testing if a variable is defined with this functions
> vars(), globals(), locals() ?

No, you just need to add another case for __builtins__

The scopes Python consults when looking up a name are:
1. Local scope - locals()
2. Nested function scope(s) - [I don't think these vars can be listed
at runtime]
3. Global scope - globals()
4. Built-ins - __builtins__

If you want to just check whether a variable is currently
defined+accessible, a try-except is much simpler:
var_name = "foo"
try:
eval(var_name)
except NameError:
defined = False
else:
defined = True

However, wanting to test whether a variable is defined or not is
usually a sign of bad code.
Could you explain exactly why you want/need to do such testing?

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


Re: vars().has_key() question about how working .

2010-04-04 Thread Chris Rebert
Ah, (bleep). Disregard both my responses.
Darn headache.

Cheers,
Chris
--
Definitely going to bed now.
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: passing command line arguments to executable

2010-04-04 Thread Francesco Bochicchio
On 3 Apr, 19:20, mcanjo  wrote:
> On Apr 3, 11:15 am, Patrick Maupin  wrote:
>
>
>
> > On Apr 3, 11:09 am, mcanjo  wrote:
>
> > > I have an executable (I don't have access to the source code) that
> > > processes some data. I double click on the icon and a Command prompt
> > > window pops up. The program asks me for the input file, I hit enter,
> > > and then it asks me for and output filename, I hit enter a second time
> > > and it goes off and does its thing and when it is finished running the
> > > Command Prompt goes away and I have my new output file in the same
> > > directory as my executable and input file. I would like to be able to
> > > batch process a group of files. I thought about using "os.spawnv()" in
> > > a loop and at each iteration of the loop passing in the file in and
> > > out names but that didn't work. Does anyone have any ideas?
>
> > You need to look at the subprocess module, and use pipes.
>
> > Regards,
> > Pat
>
> I tried doing the following code:
>
> from subprocess import Popen
> from subprocess import PIPE, STDOUT
> exefile = Popen('pmm.exe', stdout = PIPE, stdin = PIPE, stderr =
> STDOUT)
> exefile.communicate('MarchScreen.pmm\nMarchScreen.out')[0]
>
> and the Command Prompt opened and closed, no exceptions were generated
> but the program didn't run. Am I doing something wrong?

I would try a couple of things (never done what you are trying to do,
so my suggestions may be useless ):
1. use shell=True as parameter of Popen
2. capture the output of communicate method, which returns whatever
the process emits on standard output and standard error: there could
be some message that give you hints about the solution.

Ciao
--
FB

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


Re: Splitting a string

2010-04-04 Thread Peter Otten
Steven D'Aprano wrote:

> On Sat, 03 Apr 2010 11:17:36 +0200, Peter Otten wrote:
> 
>>> 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,
>> 
>> The function is small; with a test suite covering the corner cases and
>> perhaps a comment* nothing should go wrong.
>> 
>> (*) you can certainly improve on my attempt
>> 
>>> so unless Thomas has a really long result list, he might want to just
>>> keep the list comprehension, which is (IMO) very readable.
>> 
>> Generally speaking performing tests of which you know they can't fail
>> can confuse the reader just as much as tests with unobvious
>> interdependencies.
> 
> 
> I'm not sure I agree with you.

I'm going to help you make up your mind ;)
 
> Tests which you know can't fail are called assertions, pre-conditions and
> post-conditions. We test them because if we don't, they will fail :)

Note that I said /can/ not /do/ confuse. Consider the actual context, 
removing a special value from the start/end of a list:

(1)
if parts[0] == "":
del parts[0]
if not parts: return parts
if parts[-1] == "":
del parts[-1]
return parts

(2)
return [item for item in parts if item != ""]

Now assume you have to familiarize yourself with the above code. Variant (1) 
clearly expresses that the code is meant to touch only the first and last 
item. (2) could be just removing all empty strings from a list.

Another way to look at it: it is much easier to refactor from (1) to (2) 
than from (2) to (1).

As to assertions etc: you don't perform arbitrary tests like assert 42 == 
42, you make estimates about what can go wrong if you get unexpected input 
or make an error in an algorithm that you cannot safely grasp in its 
entirety. As an example you could add

assert "" not in parts[1:-1]

as a precondition to the above snippets. The superfluous tests in the list 
comprehension are the opposite of that assertion: they could eat items == "" 
in the list that either are intended to pass through or that indicate an 
error in code above.

Personally, though, I prefer unit tests over assertions.

Peter

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


Re: How to access args as a list?

2010-04-04 Thread Francesco Bochicchio
On 4 Apr, 00:58, kj  wrote:
> Suppose I have a function with the following signature:
>
> def spam(x, y, z):
>     # etc.
>
> Is there a way to refer, within the function, to all its arguments
> as a single list?  (I.e. I'm looking for Python's equivalent of
> Perl's @_ variable.)
>
> I'm aware of locals(), but I want to preserve the order in which
> the arguments appear in the signature.
>
> My immediate aim is to set up a simple class that will allow me to
> iterate over the arguments passed to the constructor (plus let me
> refer to these individual arguments by their names using an
> instance.attribute syntax, as usual).
>
> The best I have managed looks like this:
>
> class _Spam(object):
>     def __init__(self, x, y, z):
>         self.__dict__ = OrderedDict(())
>         for p in inspect.getargspec(_Spam.__init__).args[1:]:
>             self.__dict__[p] = locals()[p]
>
>     def __iter__(self):
>         return iter(self.__dict__.values())
>
> but rolling out inspect.getargspec for this sort of thing looks to
> me like overkill.  Is there a more basic approach?
>
> P.S. this is just an example; the function I want to implement has
> more parameters in its signature, with longer, more informative
> names.

Hi, I once tried something to emulate in python the way Scala language
allows to automatically generate class attributes from constructor
parameter. I never tried in real code, but see if it fits your bill.
It uses class decorators though, so only works with python3. Here is
my code:

class FieldsDecorator:
"""It adds a generic scala-like constructor to a class.
 You can create as instance as c = MyClass(f1=3, f2=4)
 and have automatically c.f1=3, c.f2=4.
 Only parameter names listed in the decorator are allowed.
"""
def __init__(self, *names):
self.names = names

def __call__(self, cls):
def constructor(instance, **kwds):
for n,v in kwds.items():
if n in self.names:
setattr(instance, n, v)
else: raise TypeError("%s is not a valid field" % s )
setattr(cls, '__init__', constructor )
return cls


@FieldsDecorator("uno", "due")
class Prova:
pass

p = Prova(uno=12, due=9)
print (p.uno, p.due )

Ciao

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


Re: Is there any library for indexing binary data?

2010-04-04 Thread Albert van der Horst
In article ,
=?GB2312?B?zPC5zw==?=   wrote:
>Well, Database is not proper because 1. the table is very big (~10^9
>rows) 2. we should support very fast *simple* query that is to get
>value corresponding to single key (~10^7 queries / second).
>
>Currently, I have implemented a specific algorithm to deal with my
>problem. However, I want to employ some library to simplify codings,
>otherwise I have to write my own code for each big table. It is
>possible that, after using indexing library, the program cannot run as
>fast as homemade code. But if it can greatly simplify my job and can
>provide satisfied speed (eg 10^5~10^6 queries / second), the indexing
>library is still a good choice for me.

At first sight this looks to me like B-trees would be an ideal
solution. The first levels of the tree are in memory, so with some
luck you have only one or two disk accesses per search.

>
>--
>ShenLei
>

Groetjes Albert

--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
alb...@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst

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


Re: off topic but please forgive me me and answer

2010-04-04 Thread Andreas Waldenburger
On Sat, 3 Apr 2010 23:13:51 -0700 (PDT) Mensanator 
wrote:

> On Apr 3, 9:03 pm, Steven D'Aprano  cybersource.com.au> wrote:
> > On Sat, 03 Apr 2010 09:35:34 -0700, Mensanator wrote:
> > > On Apr 3, 10:17 am, Steven D'Aprano  > > cybersource.com.au> wrote:
> > >> But you're not multiplying four numbers,
> >
> > > You are if you're using Rationals.
> >
> > That is sheer unadulterated nonsense.
> 
> You obviously don't understand the workings of computers.
> 
Now this is what's wrong about internet discussions. Nobody actually
defines what they are talking about *until* it becomes a problem. And
then the retconning starts.

This discussion up to this point had not explicitly been about the
workings of computers. It had not really explicitly been about
mathematical numbers either (although to my understanding this had
been implicit, but that's personal).

Let this be a reminder that defining your terms is one of the best
ideas ever. Its the reason for the success of mathematics. I'd like it
to be a reason for the success of discussions as well.

/W

PS: Accusing someone publicly of "obviously" not understanding [some
topic] is pretty low by any standards. And especially so when the
argument for doing so is bogus: Computers by themselves have as much a
notion of Rationals as they have of Irrationals, or, for that matter,
the cuteness puppies. Software does.

-- 
INVALID? DE!

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


Re: off topic but please forgive me me and answer

2010-04-04 Thread Andreas Waldenburger
On Sun, 4 Apr 2010 13:59:57 +0200 Andreas Waldenburger
 wrote:

> Computers by themselves have as much a notion of Rationals as they
> have of Irrationals, or, for that matter, the cuteness puppies.

Strike that. Floats in computers are Rationals. So computers do know
them. However, they are still not "two numbers".

/W

-- 
INVALID? DE!

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


Re: passing command line arguments to executable

2010-04-04 Thread Simon Brunning
On 3 April 2010 18:20, mcanjo  wrote:
> I tried doing the following code:
>
> from subprocess import Popen
> from subprocess import PIPE, STDOUT
> exefile = Popen('pmm.exe', stdout = PIPE, stdin = PIPE, stderr =
> STDOUT)
> exefile.communicate('MarchScreen.pmm\nMarchScreen.out')[0]
>
> and the Command Prompt opened and closed, no exceptions were generated
> but the program didn't run. Am I doing something wrong?

Have you tried running pmm.exe from the command line? What does that
look like? Does it matter what the current working directory is at the
time?

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


Is there a standard name for this tree structure?

2010-04-04 Thread Steven D'Aprano
I have a hierarchical structure something like a directory tree or a 
nested tree structure:

Mammal
+-- Ape
:   +-- Chimpanzee
:   +-- Gorilla
:   +-- Human
+-- Carnivore
:   +-- Cat
:   +-- Tiger
Reptile
+-- Lizard
+-- Snake
+-- Cobra
+-- Python

This is a forest because each top-level element (Mammal, Reptile) is 
itself a tree. By adding a root to the (former) top-level elements, I 
turn it into a single tree.

I can implement this tree using a flat dict:

root = object()
data = {root: ['Mammal', 'Reptile'], 
'Mammal': ['Ape', 'Carnivore'],
'Ape': ['Chimpanzee', 'Gorilla', 'Human'],
'Reptile': ['Lizard', 'Snake'],
# fill in the rest yourself... 
}


Is there a particular name for this structure? I've been calling it a 
dict-based flattened tree, but I can't shake the feeling that there is 
another name for it...



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


Re: Is there a standard name for this tree structure?

2010-04-04 Thread Alf P. Steinbach

* Steven D'Aprano:
I have a hierarchical structure something like a directory tree or a 
nested tree structure:


Mammal
+-- Ape
:   +-- Chimpanzee
:   +-- Gorilla
:   +-- Human
+-- Carnivore
:   +-- Cat
:   +-- Tiger
Reptile
+-- Lizard
+-- Snake
+-- Cobra
+-- Python

This is a forest because each top-level element (Mammal, Reptile) is 
itself a tree. By adding a root to the (former) top-level elements, I 
turn it into a single tree.


I can implement this tree using a flat dict:

root = object()
data = {root: ['Mammal', 'Reptile'], 
'Mammal': ['Ape', 'Carnivore'],

'Ape': ['Chimpanzee', 'Gorilla', 'Human'],
'Reptile': ['Lizard', 'Snake'],
# fill in the rest yourself... 
}



Is there a particular name for this structure? I've been calling it a 
dict-based flattened tree, but I can't shake the feeling that there is 
another name for it...


The only difference from an ordinary tree is that you have a provided a way to 
access non-root nodes (with strings as keys) that doesn't work for the root node.


Still, all nodes can be accessed with objects as keys.

So, you have just introduced some ambiguity that allows both views: it's a tree, 
and it's a forest, depending on what point of view one chooses.


In passing, this terminology is the one used in programming and computer 
science.

Donald Knuth notes that for e.g. a binary tree, if one (impractically) adopted 
the terminology of some authors on graph theory then one would have to say 
"topological bifurcating arborescence" instead of "binary tree"...



Cheers & hth.,

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


Re: Incorrect scope of list comprehension variables

2010-04-04 Thread Ethan Furman

Steve Howell wrote:

On Apr 3, 9:58 pm, Tim Roberts  wrote:


Alain Ketterlin  wrote:



I've just spent a few hours debugging code similar to this:



d = dict()
for r in [1,2,3]:
  d[r] = [r for r in [4,5,6]]
print d


Yes, this has been fixed in later revisions, but I'm curious to know what
led you to believe that a list comprehension created a new scope.  I don't
that was ever promised.



Common sense about how programming languages should work?  As
confirmed by later revisions?


Common sense?  About *somebody else's* idea of how a programming 
language should work?


Please.  Experiment and read the manual.

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


Re: Incorrect scope of list comprehension variables

2010-04-04 Thread Alf P. Steinbach

* Ethan Furman:

Steve Howell wrote:

On Apr 3, 9:58 pm, Tim Roberts  wrote:


Alain Ketterlin  wrote:



I've just spent a few hours debugging code similar to this:



d = dict()
for r in [1,2,3]:
  d[r] = [r for r in [4,5,6]]
print d


Yes, this has been fixed in later revisions, but I'm curious to know 
what
led you to believe that a list comprehension created a new scope.  I 
don't

that was ever promised.



Common sense about how programming languages should work?  As
confirmed by later revisions?


Common sense?  About *somebody else's* idea of how a programming 
language should work?


Common sense is about practical solutions.

Since there is no practical gain from a list comprehension affecting the 
bindings of outside variables, and there correspondingly is a practical pay-off 
from list comprehensions not affecting the bindings of outside variables, common 
sense is to expect the latter.


It's in the nature of common sense that those who possess this ability often 
tend to make the same tentative assumptions when presented with the same 
problem. It doesn't mean that they're consulting each other, like your "somebody 
else's": it just means that they're applying similar common sense reasoning. So, 
there's no great conspiracy.




Please.  Experiment and read the manual.


Common sense is applied first, as a heuristic. You really wouldn't want to drill 
down into the architect's drawings in order to get office 215 in a building. 
First you apply common sense.




Cheers & hth.,

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


Re: Incorrect scope of list comprehension variables

2010-04-04 Thread D'Arcy J.M. Cain
On Sun, 04 Apr 2010 15:06:46 +0200
"Alf P. Steinbach"  wrote:
> Common sense is applied first, as a heuristic. You really wouldn't want to 
> drill 
> down into the architect's drawings in order to get office 215 in a building. 
> First you apply common sense.

Oh goodie, bad analogies.  Can I play too?

Getting to office 215 is not analogous to writing a program.  It is
analogous to using the program.  Writing the program is like building
the office tower.  You need to know about the tools and materials that
you are working with.  You don't use "common sense" to decide what
materials to use.  You study the literature and the specs.

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a standard name for this tree structure?

2010-04-04 Thread Duncan Booth
Steven D'Aprano  wrote:

> I have a hierarchical structure something like a directory tree or a 
> nested tree structure:
> 
> Mammal
> +-- Ape
>:   +-- Chimpanzee
>:   +-- Gorilla
>:   +-- Human
> +-- Carnivore
>:   +-- Cat
>:   +-- Tiger
> Reptile
> +-- Lizard
> +-- Snake
> +-- Cobra
> +-- Python
> 
...snip...
> Is there a particular name for this structure? I've been calling it a 
> dict-based flattened tree, but I can't shake the feeling that there is 
> another name for it...
> 
Do you have any carniverous apes? If so it's a directed acyclic graph.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Incorrect scope of list comprehension variables

2010-04-04 Thread Brian Blais

On Apr 4, 2010, at 3:17 , Stephen Hansen wrote:

Where exactly does this common sense come from? A list  
comprehension is

basically syntactic sugar over a for loop, and...


well, since I've been bitten by this particular wart, I was surprised  
to see that the list comp didn't have it's own scope.  If it's  
syntactic sugar for a for-loop, I figured that rather than converting


d = dict()
for r in [1,2,3]:
d[r] = [r for r in [4,5,6]]

to

d = dict()
for r in [1,2,3]:

L=[]
for r in [4,5,6]:
L.append(r)
d[r] = L

it would convert it to something like:

d = dict()
for r in [1,2,3]:

L=[]
for _r in [4,5,6]:
L.append(_r)
d[r] = L


still a for-loop, but without the surprising side-effect.  I'm glad  
they fixed this one!


surely, once you know, it's easy to overcome.  as a curiosity, I just  
went and skimmed the section:


http://docs.python.org/tutorial/datastructures.html

which describes list comps, and didn't see any mention of this  
behavior.  it's probably there, but it certainly doesn't jump out.



bb

--
Brian Blais
[email protected]
http://web.bryant.edu/~bblais
http://bblais.blogspot.com/


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


Re: off topic but please forgive me me and answer

2010-04-04 Thread rantingrick
On Apr 1, 3:44 pm, superpollo  wrote:
> how much is one half times one half?

This is amazing, how can such an off topic post based completely on
lunacy exist so long here? 54 posts and counting. I think i had this
very argument in grade school. We have SD'A, Tim Chase, MSRB, and yes
even Steve Holden again participating in the troll fest (even though
some of their arguments are true). Of course i would expect mensenator
to jump into this, but...

A while back i had wondered why Guido never posts to c.l.py anymore.
Was it because he thinks himself better than us, no, it's because of
the "low-brow-infantile-Jerry-Springer-ish-nature" that this list has
imploded into. *puke*
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Splitting a string

2010-04-04 Thread Patrick Maupin
On Apr 4, 4:58 am, Peter Otten <[email protected]> wrote:

> Personally, though, I prefer unit tests over assertions.

IMO, the primary use cases for assertions and unit tests are not the
same.

When I have a well-defined, clearly understood specification that I am
coding to and fully implementing with the aim of producing a fully
general purpose solution that I are offering to others, unit tests are
appropriate to make sure that the code matches the spec, and even to
provide usage examples.

When I am using Python in what I would call a more personal way, for
example in an exploratory fashion to extract value from some large
mass of data, or even to do something like parsing on a subset of
another language, where I have no intention, desire, or time to
implement the entire spec, assertions are perfectly appropriate to
make sure that my code complains at a convenient point about input
data that it would not handle properly.

It is often the case that a more personal project will grow up and
become more general purpose and widely used.  At this point, it is
appropriate to remove assertions, add unit tests, etc., but to
complain about not having unit tests in the first place is to avoid
acknowledging that there may be a higher cost associated with unit
tests than with assertions, especially with immature code that may be
severely refactored several times before settling on the best
solution.

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


Re: Splitting a string

2010-04-04 Thread Patrick Maupin
On Apr 4, 2:37 am, Steven D'Aprano  wrote:

> In any case, the *right* test would be:
>
> a = 1
> assert a == 1 and a*5==5 and str(a)=='1' and [None,a,None][a] is a

You're right.  I was very tired when I wrote that, and forgot the last
3 assertions...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a standard name for this tree structure?

2010-04-04 Thread Stefan Behnel

Steven D'Aprano, 04.04.2010 14:10:

I have a hierarchical structure something like a directory tree or a
nested tree structure:

Mammal
+-- Ape
:   +-- Chimpanzee
:   +-- Gorilla
:   +-- Human
+-- Carnivore
:   +-- Cat
:   +-- Tiger
Reptile
+-- Lizard
+-- Snake
 +-- Cobra
 +-- Python


Maybe not quite what you asked for, but given the names in the example 
above I would call this an ontology.


Stefan

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


Re: off topic but please forgive me me and answer

2010-04-04 Thread superpollo

rantingrick ha scritto:

On Apr 1, 3:44 pm, superpollo  wrote:

how much is one half times one half?


This is amazing, how can such an off topic post based completely on
lunacy exist so long here? 54 posts and counting. I think i had this
very argument in grade school. We have SD'A, Tim Chase, MSRB, and yes
even Steve Holden again participating in the troll fest (even though
some of their arguments are true). Of course i would expect mensenator
to jump into this, but...

A while back i had wondered why Guido never posts to c.l.py anymore.
Was it because he thinks himself better than us, no, it's because of
the "low-brow-infantile-Jerry-Springer-ish-nature" that this list has
imploded into. *puke*


relax mate.

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


Re: Is there a standard name for this tree structure?

2010-04-04 Thread Patrick Maupin
On Apr 4, 9:06 am, Duncan Booth  wrote:
> Do you have any carniverous apes? If so it's a directed acyclic graph.

Well, since he has a root node, he's really only described the *use*
of this data structure implementation for a rooted tree.

As you point out, the implementation itself is more general than a
rooted tree, and could be used for any DAG.  But you don't go far
enough.  This particular implementation could be used for any directed
graph -- there is nothing (other than the problem domain) requiring
that data in this dict be acyclic.  In fact, there are sometimes good
reasons for using this sort of structure for cyclic data.  Having a
name for each node, and always indirectly referring to the node by its
name, can sometimes greatly simplify the implementation of problems
requiring a cyclic graph (starting with the really basic problem of
wanting to dump the whole structure out in a reasonable fashion for
debugging).

The primary differences between this structure and just haphazardly
wiring up random objects into a directed graph are that (1) there may
be some performance differences (but when the garbage collector has to
figure out how to break cycles, these difference might or might not be
in the direction you expect) and (2) with this structure, every object
needs a globally unique name for indexing purposes.

Having said all that, I don't know what the proper name for this data
structure is, either :-)

However, in determining the name, I would probably focus on the data
structure being represented (in Steven's case, a tree), and the data
structure used to represent it (a Python dict), and *why/how* the
underlying structure is used.  So I would probably call it something
like an "associatively addressed tree".

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


Re: Is there a standard name for this tree structure?

2010-04-04 Thread Patrick Maupin
On Apr 4, 10:41 am, Patrick Maupin  wrote:

> The primary differences between this structure and just haphazardly
> wiring up random objects into a directed graph are that (1) there may
> be some performance differences (but when the garbage collector has to
> figure out how to break cycles, these difference might or might not be
> in the direction you expect) and (2) with this structure, every object
> needs a globally unique name for indexing purposes.

(Just wanted to point out that I realize there aren't any cycles in
Steven's example data -- point (1) this paragraph was about the more
general use of the dict structure for general directed graphs.)

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


In disGuiodoise?

2010-04-04 Thread Alf P. Steinbach

* ratingrick:


A while back i had wondered why Guido never posts to c.l.py anymore.
Was it because he thinks himself better than us, no, it's because of
the "low-brow-infantile-Jerry-Springer-ish-nature" that this list has
imploded into.



Perhaps Guido provides subtle guidance under some unrecognized nick?

"He walks among you, and you don't recognize him" - Old jungle proverb

Hm, interesting Google results for that phrase.


Cheers,

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


Re: off topic but please forgive me me and answer

2010-04-04 Thread Patrick Maupin
On Apr 4, 10:00 am, rantingrick  wrote:

> This is amazing, how can such an off topic post based completely on
> lunacy exist so long here? 54 posts and counting. I think i had this
> very argument in grade school. We have SD'A, Tim Chase, MSRB, and yes
> even Steve Holden again participating in the troll fest (even though
> some of their arguments are true). Of course i would expect mensenator
> to jump into this, but...

Excellent technique.  Pick a topic that is guaranteed in any universe
to generate a lot of posts (a short provocative question asked on
April Fool's Day), then stay above the fray, not posting until the
traffic dies down, and only then make a post expressly engineered to
try to start the traffic up again.  Rinse and repeat as necessary.

I bow at the feet of the master.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: In disGuiodoise?

2010-04-04 Thread Patrick Maupin
On Apr 4, 11:14 am, "Alf P. Steinbach"  wrote:
> "He walks among you, and you don't recognize him" - Old jungle proverb
>
> Hm, interesting Google results for that phrase.

Interesting self-promotion :-)

http://www.google.com/#q=%22He+walks+among+you,+and+you+don%27t+recognize+him%22&hl=en&safe=off&filter=0&fp=a2bb30ecf4f91972
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: In disGuiodoise?

2010-04-04 Thread Alf P. Steinbach

* Patrick Maupin:

On Apr 4, 11:14 am, "Alf P. Steinbach"  wrote:

"He walks among you, and you don't recognize him" - Old jungle proverb

Hm, interesting Google results for that phrase.


Interesting self-promotion :-)


No, I'm not Guido.


Cheers,

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


Re: In disGuiodoise?

2010-04-04 Thread MRAB

Alf P. Steinbach wrote:

* Patrick Maupin:

On Apr 4, 11:14 am, "Alf P. Steinbach"  wrote:

"He walks among you, and you don't recognize him" - Old jungle proverb

Hm, interesting Google results for that phrase.


Interesting self-promotion :-)


No, I'm not Guido.


That's exactly what the true Guido would say! :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: off topic but please forgive me me and answer

2010-04-04 Thread Lie Ryan
On 04/04/10 13:01, Patrick Maupin wrote:
> On Apr 3, 9:24 pm, Steven D'Aprano  cybersource.com.au> wrote:
>> To put it another way, even though there are an infinite number of
>> rationals, they are vanishingly rare compared to the irrationals. If you
>> could choose a random number from the real number line, it almost
>> certainly would be irrational.
> 
> Yet another correspondence between the set of numbers and the set of
> people ;-)

Not really. The set of all irrational numbers is not enumerable
(aleph-1) and thus uncountable, but the set of all irrational people is
a countable finite set (even though it may be very difficult to
enumerate them).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C-style static variables in Python?

2010-04-04 Thread John Nagle

kj wrote:

When coding C I have often found static local variables useful for
doing once-only run-time initializations. 


   If you want functions with state, use an object. That's what they're
for.  Don't muck with the internal representation of functions.

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


Re: In disGuiodoise?

2010-04-04 Thread John Nagle

Alf P. Steinbach wrote:

* ratingrick:


A while back i had wondered why Guido never posts to c.l.py anymore.
Was it because he thinks himself better than us, no, it's because of
the "low-brow-infantile-Jerry-Springer-ish-nature" that this list has
imploded into.


   Maybe Google is making him do some real work.

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


Re: In disGuiodoise?

2010-04-04 Thread Emile van Sebille

On 4/4/2010 9:14 AM Alf P. Steinbach said...

* ratingrick:


A while back i had wondered why Guido never posts to c.l.py anymore.


As I recall, about the time of the 1.6/2.0 schism (2000?) the primary 
developers split off as python had grown to the point where there was 
enough new user support, and the traffic volume was seen as too much 
noise to get meaningful work done.


Emile


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


Re: C-style static variables in Python?

2010-04-04 Thread Patrick Maupin
On Apr 4, 1:57 pm, John Nagle  wrote:
>     If you want functions with state, use an object. That's what they're
> for.  Don't muck with the internal representation of functions.
>

While "Don't muck with the internal representation of functions" is
excellent advice over 99% of the time, it is also true that it is
often possible, sometimes even encouraged, to have "functions with
state."

This is done without "mucking" and without explicitly declaring a
class or a class instance.  See, e.g. closures and generator
functions.

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


Re: Encryption source code with md5

2010-04-04 Thread Robert Kern

On 2010-04-03 20:21 , Lawrence D'Oliveiro wrote:

In message<[email protected]>, Irmen de Jong wrote:


On 28-3-2010 12:08, Lawrence D'Oliveiro wrote:


Don’t use MD5.


Also, md5 is not an encryption algorithm at all, it is a secure hashing
function.


You can use hash functions for encryption.


You can *build* an encryption algorithm out of hash functions as a primitive, 
yes. Paul Rubin's p3.py is an example of using SHA-1 to build an encryption 
algorithm:


  http://www.nightsong.com/phr/crypto/p3.py

However, a hash function is not an encryption algorithm itself. One does not 
"encrypt with md5" as the OP asked. For crypto-knowledgeable people, this may 
just be an issue of terminology (although I think an important one), but I think 
it demonstrates the ignorance of the OP and the need for Irmen's clarification.


--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Incorrect scope of list comprehension variables

2010-04-04 Thread Paul Rubin
Alain Ketterlin  writes:
> d[r] = [r for r in [4,5,6]]
> THe problem is that the "r" in d[r] somehow captures the value of the
> "r" in the list comprehension, and somehow kills the loop interator.

Yes, this is a well known design error in Python 2.x.  The 3.x series
fixes this error but introduces other errors of its own.  It is evil
enough that I almost always use this syntax instead:

d[r] = list(r for r in [4,5,6])

that works in 3.x and the later releases of 2.x.  In early 2.x (maybe up
to 2.2) it throws an error at compile time rather than at run time.
-- 
http://mail.python.org/mailman/listinfo/python-list


local variable referenced before assignment

2010-04-04 Thread johngilbrough
I cannot make sense of what's happening here ...  I'm getting the
following error:

initializing last modified time
/home/john/Dropbox/Projects/python/scripts/src 29
referencing last modified time
/home/john/Dropbox/Projects/python/scripts/src 29
referencing last modified time
Traceback (most recent call last):
  File "/home/john/Dropbox/Projects/python/scripts/src/file-watch.py",
line 42, in 
time.sleep(1)
  File "/home/john/Dropbox/Projects/python/scripts/src/file-watch.py",
line 18, in handler
if modifiedTime <> lastModifiedTime:
UnboundLocalError: local variable 'lastModifiedTime' referenced before
assignment

>From this logic:

#!/usr/bin/python
def watchFile(filePath, callback):
###
#   calls callback whenever file is changed
###
import fcntl
import os
import signal
print "initializing last modified time"
lastModifiedTime = os.path.getmtime(filePath)

def handler(signum, frame):
## this gets called twice whenever a file changes
print filePath + " " + str(signum)
modifiedTime = os.path.getmtime(filePath)
print "referencing last modified time"
if modifiedTime <> lastModifiedTime:
lastModifiedTime = modifiedTime
callback()

signal.signal(signal.SIGIO, handler)
fd = os.open(filePath,  os.O_RDONLY)
fcntl.fcntl(fd, fcntl.F_SETSIG, 0)
fcntl.fcntl(fd, fcntl.F_NOTIFY,
0
| fcntl.DN_MODIFY
| fcntl.DN_CREATE
| fcntl.DN_MULTISHOT  # what's this?
)

def doSomething ():
print "in doSomething"

import time
filePath = "/home/john/Dropbox/Projects/python/scripts/src"

watchFile (filePath, doSomething)

while True:
# needed to keep this alive - gets interrupted when a file changes
time.sleep(1)
print "*",
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: passing command line arguments to executable

2010-04-04 Thread Gabriel Genellina
On 4 abr, 06:17, Francesco Bochicchio  wrote:
> On 3 Apr, 19:20, mcanjo  wrote:
> > On Apr 3, 11:15 am, Patrick Maupin  wrote:
> > > On Apr 3, 11:09 am, mcanjo  wrote:
>
> > > > I have an executable (I don't have access to the source code) that
> > > > processes some data. I double click on the icon and a Command prompt
> > > > window pops up. The program asks me for the input file, I hit enter,
> > > > and then it asks me for and output filename, I hit enter a second time
 
^
> > > > and it goes off and does its thing and when it is finished ...
>
> > > You need to look at the subprocess module, and use pipes.
>
> > I tried doing the following code:
>
> > from subprocess import Popen
> > from subprocess import PIPE, STDOUT
> > exefile = Popen('pmm.exe', stdout = PIPE, stdin = PIPE, stderr =
> > STDOUT)
> > exefile.communicate('MarchScreen.pmm\nMarchScreen.out')[0]
>
> > and the Command Prompt opened and closed, no exceptions were generated
> > but the program didn't run. Am I doing something wrong?
>
> I would try a couple of things (never done what you are trying to do,
> so my suggestions may be useless ):
> 1. use shell=True as parameter of Popen
> 2. capture the output of communicate method, which returns whatever
> the process emits on standard output and standard error: there could
> be some message that give you hints about the solution.

To mcanjo: note that you didn't provide the second '\n'

Also, are you sure the program does not accept command line arguments?
Many do, and switch to interactive mode when no argument is provided.
I'd try with -h /h --help /help -? /?

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


Re: local variable referenced before assignment

2010-04-04 Thread Alf P. Steinbach

* johngilbrough:

I cannot make sense of what's happening here ...  I'm getting the
following error:

initializing last modified time
/home/john/Dropbox/Projects/python/scripts/src 29
referencing last modified time
/home/john/Dropbox/Projects/python/scripts/src 29
referencing last modified time
Traceback (most recent call last):
  File "/home/john/Dropbox/Projects/python/scripts/src/file-watch.py",
line 42, in 
time.sleep(1)
  File "/home/john/Dropbox/Projects/python/scripts/src/file-watch.py",
line 18, in handler
if modifiedTime <> lastModifiedTime:
UnboundLocalError: local variable 'lastModifiedTime' referenced before
assignment

From this logic:

#!/usr/bin/python
def watchFile(filePath, callback):
###
#   calls callback whenever file is changed
###
import fcntl
import os
import signal
print "initializing last modified time"
lastModifiedTime = os.path.getmtime(filePath)

def handler(signum, frame):
## this gets called twice whenever a file changes
print filePath + " " + str(signum)
modifiedTime = os.path.getmtime(filePath)
print "referencing last modified time"
if modifiedTime <> lastModifiedTime:
lastModifiedTime = modifiedTime
callback()


Since 'handler' has an assignment to 'lastModifiedTime' that name becomes the 
name of a local variable. It's not the execution of the assignment that creates 
the variable. It's the /presence/ of the assignment (this helps the compiler 
generate code that allocates all local variables on entry to the function).


There are a couple of ways around.

(1)
At least in Py3 you can declare the variable as 'global', like this:

   global lastModifiedTime

within the function.

(2)
Or, you can apply some indirection, which is nearly always a solution to any 
computer science and programming problem, and declare your variable like so:


   class Object: pass

   g = Object()
   g.lastModifiedTime = os.path.getmtime( filePath )

Then when you assign to 'g.lastModifiedTime' in 'handler' you're not creating a 
variable, because you're assigning to an attribute of an object.


(3)
Best is however to recognize that you have some state (your variable) and some 
operations on that state (your callback), and that that is what objects are all 
about. I.e. wrap your logic in a class. Then 'lastModifiedTime' becomes an 
instance attribute, and 'handler' becomes a method.


It doesn't matter that there will only ever be one object (instance) of that 
class.

Classes were meant for just this sort of thing, state + operations.


Cheers & hth.,

- Alf

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


Re: local variable referenced before assignment

2010-04-04 Thread Stephen Hansen

On 2010-04-04 15:22:48 -0700, Alf P. Steinbach said:


* johngilbrough:

I cannot make sense of what's happening here ...  I'm getting the
following error:

(1)
At least in Py3 you can declare the variable as 'global', like this:

global lastModifiedTime

within the function.


Actually, what you're looking for in py3 is the "nonlocal" keyword, 
which addresses this precise situation. Using "global" would mark the 
variable as *global* -- top-level module namespace.


nonlocal (within "handler") would make the assignment apply to the 
enclosing scope lastModifiedTime, instead.


--
--S

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

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


Re: local variable referenced before assignment

2010-04-04 Thread Alf P. Steinbach

* Stephen Hansen:

On 2010-04-04 15:22:48 -0700, Alf P. Steinbach said:


* johngilbrough:

I cannot make sense of what's happening here ...  I'm getting the
following error:

(1)
At least in Py3 you can declare the variable as 'global', like this:

global lastModifiedTime

within the function.


Actually, what you're looking for in py3 is the "nonlocal" keyword, 
which addresses this precise situation. Using "global" would mark the 
variable as *global* -- top-level module namespace.


Thanks, I didn't see that. I thought it was a global.


nonlocal (within "handler") would make the assignment apply to the 
enclosing scope lastModifiedTime, instead.



Cheers,

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


def method with variable no of parameters file.writeStuff(n, a1, a2, ...an)

2010-04-04 Thread vlad_fig
Hello all,

I would like some help with setting up a method that would allow me to change 
its number of parameters. For example:

#-
class createfile(object): 

def __init__(self,
modelName = None,
someLines = None):

self.modelName = modelName

if someLines is None:
self.someLines = []
else:
self.someLines = someLines 

def writeStuff(self,
numberParameters = None,
Parameter1 = None,... ??? )
self.someLines .append("yes, we can %s" % self.Parameter1)
#-
file = createfile('file')

file.writeStuff(2,a1,a2)
file.writeStuff(3,a1,a2,a3)

file.writeStuff(n,a1,a2,...an)

--- 
so i want a method i can call based on the number of parameters n , and that 
allows me to add these extra parameters based on n

Thank you,
Vicnic

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


Re: Getting Local MAC Address

2010-04-04 Thread Michael Torrie
On 04/02/2010 04:01 PM, Dan McLeran wrote:
> which is why my OP stated the solution was for windows:
> 
> "for windows parse 
> p.stdout.read():"

Gotcha.  Definitely missed that!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Encryption source code with md5

2010-04-04 Thread geremy condra
On Sun, Apr 4, 2010 at 6:03 PM, Robert Kern  wrote:
> On 2010-04-03 20:21 , Lawrence D'Oliveiro wrote:
>>
>> In message<[email protected]>, Irmen de Jong wrote:
>>
>>> On 28-3-2010 12:08, Lawrence D'Oliveiro wrote:
>>>
 Don’t use MD5.
>>>
>>> Also, md5 is not an encryption algorithm at all, it is a secure hashing
>>> function.
>>
>> You can use hash functions for encryption.
>
> You can *build* an encryption algorithm out of hash functions as a
> primitive, yes. Paul Rubin's p3.py is an example of using SHA-1 to build an
> encryption algorithm:
>
>  http://www.nightsong.com/phr/crypto/p3.py
>
> However, a hash function is not an encryption algorithm itself. One does not
> "encrypt with md5" as the OP asked. For crypto-knowledgeable people, this
> may just be an issue of terminology (although I think an important one), but
> I think it demonstrates the ignorance of the OP and the need for Irmen's
> clarification.
>
> --
> Robert Kern

I don't mean to disrespect Paul Rubin, but p3.py comes up in every discussion
of cryptography in python on this list and, AFAICT, has yet to come under
significant cryptanalytic scrutiny. That doesn't make it a bad example in this
case, but I would caution the OP that it probably doesn't make it a good
candidate for your encryption needs.

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


Re: def method with variable no of parameters file.writeStuff(n, a1, a2, ...an)

2010-04-04 Thread Iuri
What you need is var-args:

def func(*args):
  for arg in args: print arg

func(1,2,3,4)



On Fri, Apr 2, 2010 at 8:25 AM, vlad_fig  wrote:

> Hello all,
>
> I would like some help with setting up a method that would allow me to
> change its number of parameters. For example:
>
> #-
> class createfile(object):
>
> def __init__(self,
> modelName = None,
> someLines = None):
>
> self.modelName = modelName
>
> if someLines is None:
> self.someLines = []
> else:
> self.someLines = someLines
>
> def writeStuff(self,
> numberParameters = None,
> Parameter1 = None,... ??? )
> self.someLines .append("yes, we can %s" % self.Parameter1)
> #-
> file = createfile('file')
>
> file.writeStuff(2,a1,a2)
> file.writeStuff(3,a1,a2,a3)
> 
> file.writeStuff(n,a1,a2,...an)
>
> ---
> so i want a method i can call based on the number of parameters n , and
> that allows me to add these extra parameters based on n
>
> Thank you,
> Vicnic
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: In disGuiodoise?

2010-04-04 Thread r
On Apr 4, 11:14 am, "Alf P. Steinbach"  wrote:
>
> Perhaps Guido provides subtle guidance under some unrecognized nick?
> "He walks among you, and you don't recognize him" - Old jungle proverb

Ah yes i have often wondered who could it be? I have a few good
suspects who could be Guido's sock-puppets. Although i don't know
Guido's personality enough to pick him out of the crowd. If it were
you i would be happy! Some of the other suspects are quite annoying,
but their knowledge level and self righteousness seem to be so
overwhelming. So finding out that they are Guido would be a
disappointment. But again i don't know Guido so it would be hard for
me to say...?

""" The White Wizard is cunning. He walks here and there they say, as
an old man, hooded and cloaked... And everywhere his spies slip past
our nets!"""

However i have also considered that maybe *all* the "well knowns" are
in fact the many colorful personalities of Guido.

* When he's in the mood for fire breathing debate and cunning
undermining he fires up the SD'A account.
* When he's feeling vindictive he drops one-line poop bombs from
Alex23.
* if someone announces a new module without documenting it he fires
off troll feeds from mensenator.
* When he's feeling nice he uses Chris Rebert.
* If he feeling like spreading propaganda he fires up the George
Sakkis or Bruno Desthuilliers.
* If he wants to feel stately he masquerades as Steve Holden (although
lately we've seen the grumpy side of this personality).
* And last but not least when he feels like trolling on a grandiose
scale he posts to c.l.lisp, c.p.ruby, and c.l.python, and five other
sites as xah lee.

Heck i may be the only non-Guido "regular" here! ;-)

PS: Sorry if i left anyone out.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: def method with variable no of parameters file.writeStuff(n, a1, a2, ...an)

2010-04-04 Thread Joaquin Abian
On Apr 2, 1:25 pm, "vlad_fig"  wrote:
> Hello all,
>
> I would like some help with setting up a method that would allow me to change 
> its number of parameters. For example:
>
> #-
> class createfile(object):
>
> def __init__(self,
> modelName = None,
> someLines = None):
>
> self.modelName = modelName
>
> if someLines is None:
> self.someLines = []
> else:
> self.someLines = someLines
>
> def writeStuff(self,
> numberParameters = None,
> Parameter1 = None,... ??? )
> self.someLines .append("yes, we can %s" % self.Parameter1)
> #-
> file = createfile('file')
>
> file.writeStuff(2,a1,a2)
> file.writeStuff(3,a1,a2,a3)
> 
> file.writeStuff(n,a1,a2,...an)
>
> ---
> so i want a method i can call based on the number of parameters n , and that 
> allows me to add these extra parameters based on n
>
> Thank you,
> Vicnic

Maybe you are looking for *args:

class Test():
def meth(self, *args):
print args

inst = Test()
inst.meth(1,2,3,4,5,6,7)

#prints (1,2,3,4,5,6,7)

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


Re: def method with variable no of parameters file.writeStuff(n, a1, a2, ...an)

2010-04-04 Thread alex23
"vlad_fig"  wrote:
> file.writeStuff(2,a1,a2)
> file.writeStuff(3,a1,a2,a3)
> 
> file.writeStuff(n,a1,a2,...an)
> ---
> so i want a method i can call based on the number of parameters
> n , and that allows me to add these extra parameters based on n

It's not necessary to have to specify the number of parameters, you
can use Python's support for optional parameters[1] instead:

  def writeStuff(self, *args):
  self.someLines.append(args)

args will be a list of the values passed into writeStuff.

1: http://docs.python.org/reference/expressions.html#calls
-- 
http://mail.python.org/mailman/listinfo/python-list


reduce in loop

2010-04-04 Thread monkeys paw

Why does the following fail with the Traceback?

def add(x,y): return x+y
for rrr in range(1,20):
reduce(add, range(1, r))

Traceback (most recent call last):
  File "", line 2, in 
TypeError: reduce() of empty sequence with no initial value
--
http://mail.python.org/mailman/listinfo/python-list


Re: reduce in loop

2010-04-04 Thread Benjamin Kaplan
On Sun, Apr 4, 2010 at 7:46 PM, monkeys paw  wrote:
> Why does the following fail with the Traceback?
>
> def add(x,y): return x+y
> for rrr in range(1,20):
>        reduce(add, range(1, r))
>
> Traceback (most recent call last):
>  File "", line 2, in 
> TypeError: reduce() of empty sequence with no initial value
> --

>>> for x in range(1,1) :
...print x
...
>>>

ranges start at the first value and go up to, but not including, the
second value. So range(1,1) gives you no values. reduce doesn't know
what to do with an empty sequence, so it throws an error.

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


Irony overload [was Re: off topic but please forgive me me and answer]

2010-04-04 Thread Steven D'Aprano
On Sun, 04 Apr 2010 08:00:41 -0700, rantingrick wrote:

> A while back i had wondered why Guido never posts to c.l.py anymore. Was
> it because he thinks himself better than us, no, it's because of the
> "low-brow-infantile-Jerry-Springer-ish-nature" that this list has
> imploded into. *puke*

Complaining about the infantile nature of the list immediately before 
throwing up. Methinks "rantingrick" is projecting just a little.


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


Re: In disGuiodoise?

2010-04-04 Thread Steven D'Aprano
On Sun, 04 Apr 2010 19:06:18 +0200, Alf P. Steinbach wrote:

> * Patrick Maupin:
>> On Apr 4, 11:14 am, "Alf P. Steinbach"  wrote:
>>> "He walks among you, and you don't recognize him" - Old jungle proverb
>>>
>>> Hm, interesting Google results for that phrase.
>> 
>> Interesting self-promotion :-)
> 
> No, I'm not Guido.


I AM SPARTACUS^W GUIDO!




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


Re: (a==b) ? 'Yes' : 'No'

2010-04-04 Thread Gregory Ewing

Steven D'Aprano wrote:

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.


As I remember, the decision made on the basis of the vote
was *not* to add a conditional expression at all, because of
the fact that there was no clear winner.

It was some time later that Guido suddenly announced out of
the blue that he was accepting one of the choices that he had
earlier said he didn't like!

The ways of the BDFL are strange indeed. :-)

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


Re: reduce in loop

2010-04-04 Thread Terry Reedy

On 4/4/2010 7:46 PM, monkeys paw wrote:

Why does the following fail with the Traceback?

def add(x,y): return x+y
for rrr in range(1,20):


I presume that this was 'for r...'


reduce(add, range(1, r))


and that this was indented.


Traceback (most recent call last):
File "", line 2, in 
TypeError: reduce() of empty sequence with no initial value


Just what it says. To debug this sort of this, try printing values just 
before the line that fails. When r is 1, range(1,1) = []. So either 
start r at 2 or add the third arg to reduce(add, range(1,r), 0).


Terry Jan Reedy



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


Re: Incorrect scope of list comprehension variables

2010-04-04 Thread Steven D'Aprano
On Sun, 04 Apr 2010 05:50:01 -0700, Ethan Furman wrote:

>>>Yes, this has been fixed in later revisions, but I'm curious to know
>>>what led you to believe that a list comprehension created a new scope. 
>>>I don't that was ever promised.
>> 
>> 
>> Common sense about how programming languages should work?  As confirmed
>> by later revisions?
> 
> Common sense?  About *somebody else's* idea of how a programming
> language should work?

Nevertheless, it is a common intuition that the list comp variable should 
*not* be exposed outside of the list comp, and that the for-loop variable 
should. Perhaps it makes no sense, but it is very common -- I've never 
heard of anyone being surprised that the for-loop variable is exposed, 
but I've seen many people surprised by the fact that list-comps do expose 
their loop variable.



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


Re: Incorrect scope of list comprehension variables

2010-04-04 Thread Steven D'Aprano
On Sun, 04 Apr 2010 14:50:54 -0700, Paul Rubin wrote:

> Alain Ketterlin  writes:
>> d[r] = [r for r in [4,5,6]]
>> THe problem is that the "r" in d[r] somehow captures the value of the
>> "r" in the list comprehension, and somehow kills the loop interator.
> 
> Yes, this is a well known design error in Python 2.x.  The 3.x series
> fixes this error but introduces other errors of its own.


Oh, do tell?


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


Re: (a==b) ? 'Yes' : 'No'

2010-04-04 Thread Steven D'Aprano
On Mon, 05 Apr 2010 12:08:31 +1200, Gregory Ewing wrote:

> Steven D'Aprano wrote:
> 
>> 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.
> 
> As I remember, the decision made on the basis of the vote was *not* to
> add a conditional expression at all, because of the fact that there was
> no clear winner.
> 
> It was some time later that Guido suddenly announced out of the blue
> that he was accepting one of the choices that he had earlier said he
> didn't like!
> 
> The ways of the BDFL are strange indeed. :-)


I think what happened was the he got bitten by a subtle bug in the 
previous idiom for the ternary operator:

condition and x or y

will return (x if condition else y) *unless* x itself happens to be a 
false value. This demonstrated that the and/or idiom was not a suitable 
alternative to a short-circuiting ternary operator.



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


Re: Encryption source code with md5

2010-04-04 Thread Robert Kern

On 2010-04-04 17:44 , geremy condra wrote:

On Sun, Apr 4, 2010 at 6:03 PM, Robert Kern  wrote:

On 2010-04-03 20:21 , Lawrence D'Oliveiro wrote:


In message<[email protected]>, Irmen de Jong wrote:


On 28-3-2010 12:08, Lawrence D'Oliveiro wrote:


Don’t use MD5.


Also, md5 is not an encryption algorithm at all, it is a secure hashing
function.


You can use hash functions for encryption.


You can *build* an encryption algorithm out of hash functions as a
primitive, yes. Paul Rubin's p3.py is an example of using SHA-1 to build an
encryption algorithm:

  http://www.nightsong.com/phr/crypto/p3.py

However, a hash function is not an encryption algorithm itself. One does not
"encrypt with md5" as the OP asked. For crypto-knowledgeable people, this
may just be an issue of terminology (although I think an important one), but
I think it demonstrates the ignorance of the OP and the need for Irmen's
clarification.

--
Robert Kern


I don't mean to disrespect Paul Rubin, but p3.py comes up in every discussion
of cryptography in python on this list and, AFAICT, has yet to come under
significant cryptanalytic scrutiny. That doesn't make it a bad example in this
case, but I would caution the OP that it probably doesn't make it a good
candidate for your encryption needs.


For people looking for standardized cryptography, Google works fine to find 
PyCrypto or M2Crypto. p3 comes up so often in this group because people that 
need to ask here are looking for reasonably performant, pure-Python crypto, and 
p3 is the best-of-breed given those constraints (it happens to be mentioned here 
as an example, not a recommendation). Its security derives from its use of 
standardized, well-scrutinized components (and no, the recent attacks on SHA-1 
do not affect the security properties that p3 relies on). It will probably never 
receive the kind of attention that AES or the rest get because it will never be 
fast enough to even be considered a peer of those algorithms.


--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Incorrect scope of list comprehension variables

2010-04-04 Thread Stephen Hansen

On 2010-04-04 17:01:20 -0700, Steven D'Aprano said:


On Sun, 04 Apr 2010 05:50:01 -0700, Ethan Furman wrote:


Yes, this has been fixed in later revisions, but I'm curious to know
what led you to believe that a list comprehension created a new scope.
I don't that was ever promised.



Common sense about how programming languages should work?  As confirmed
by later revisions?


Common sense?  About *somebody else's* idea of how a programming
language should work?


Nevertheless, it is a common intuition that the list comp variable should
*not* be exposed outside of the list comp, and that the for-loop variable
should. Perhaps it makes no sense, but it is very common -- I've never
heard of anyone being surprised that the for-loop variable is exposed,
but I've seen many people surprised by the fact that list-comps do expose
their loop variable.


IMHO, the real confusion-point of the situation wasn't so much list 
comps vs for loops, but that list comps did expose it, but gen comps 
didn't. If one thinks about how each would most likely be implemented 
they wouldn't be surprised, but I'm glad the behavior was harmonized in 
3.x.


That said, I can't quite imagine how anyone could really sit down and 
write code which would be broken by list comps "leaking". The example 
code in this thread is just nutty. Even if list comps did create a new 
scope, why in the world would you intentionally shadow an enclosing 
iteration variable?


Obfuscation is not a good goal to go after :)

--
--S

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

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


Re: Incorrect scope of list comprehension variables

2010-04-04 Thread Stephen Hansen

On 2010-04-04 14:50:54 -0700, Paul Rubin said:


Alain Ketterlin  writes:

d[r] = [r for r in [4,5,6]]
THe problem is that the "r" in d[r] somehow captures the value of the
"r" in the list comprehension, and somehow kills the loop interator.


Yes, this is a well known design error in Python 2.x.  The 3.x series
fixes this error but introduces other errors of its own.  It is evil
enough that I almost always use this syntax instead:

d[r] = list(r for r in [4,5,6])

that works in 3.x and the later releases of 2.x.  In early 2.x (maybe up
to 2.2) it throws an error at compile time rather than at run time.



I have a dramatic suggestion.

Why not use this syntax:

d[r] = [something_else for something_else in [4,5,6]]

Where something_else is basically any conceivable name in the whole 
wide world which does not have meaning in the current local scope.


Just for clarity's sake, not sharing names is swell.

--
--S

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

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


unset TCL_LIBRARY and TK_LIBRARY

2010-04-04 Thread Wolfman
Hello- was hoping someone could give me a hand in permanently setting
my TCL_LIBRARY and TK_LIBRARY.

I downloaded Python2.6 to a ThinkPad that came installed with
Python2.2, and I can not run IDLE as something automatically sets
TCL_LIBRARY and TK_LIBRARY to C:\IBMTools\Python22\ each time i open a
new command line window or reboot the machine.

i have set them to the appropriate Python26 sub-directory via command
line and IDLE opens just fine and dandy, but as soon as I close the
command window or reboot computer it sets them back to the
aforementioned C:\IBMTools\Python22 subdirectory

how can i permanently SET TCL_LIBRARY and TK_LIBRARY?

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


Re: passing command line arguments to executable

2010-04-04 Thread Joshua

On 4/3/10 12:09 PM, mcanjo wrote:

I have an executable (I don't have access to the source code) that
processes some data. I double click on the icon and a Command prompt
window pops up. The program asks me for the input file, I hit enter,
and then it asks me for and output filename, I hit enter a second time
and it goes off and does its thing and when it is finished running the
Command Prompt goes away and I have my new output file in the same
directory as my executable and input file. I would like to be able to
batch process a group of files. I thought about using "os.spawnv()" in
a loop and at each iteration of the loop passing in the file in and
out names but that didn't work. Does anyone have any ideas?


I've done this a couple times on Windows. There are a few ways to do it, 
but I've found the easiest way is to use subprocess.check_call(). If you 
need to build the call with variables I find it cleaner to build the 
string before calling check_call(). Below is an example.


callString = 'program.exe -x ' + variable
returnMessage = subprocess.check_call(callString, shell=True)

This works for programs that take arguments, I don't know how it will 
work with the program you have that asks for input in an interactive 
way. Does it accept arguments when you first run it? Not sure how to do 
it otherwise.


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


Re: Encryption source code with md5

2010-04-04 Thread geremy condra
On Sun, Apr 4, 2010 at 8:42 PM, Robert Kern  wrote:
> On 2010-04-04 17:44 , geremy condra wrote:
>>
>> On Sun, Apr 4, 2010 at 6:03 PM, Robert Kern  wrote:
>>>
>>> On 2010-04-03 20:21 , Lawrence D'Oliveiro wrote:

 In message<[email protected]>, Irmen de Jong
 wrote:

> On 28-3-2010 12:08, Lawrence D'Oliveiro wrote:
>
>> Don’t use MD5.
>
> Also, md5 is not an encryption algorithm at all, it is a secure hashing
> function.

 You can use hash functions for encryption.
>>>
>>> You can *build* an encryption algorithm out of hash functions as a
>>> primitive, yes. Paul Rubin's p3.py is an example of using SHA-1 to build
>>> an
>>> encryption algorithm:
>>>
>>>  http://www.nightsong.com/phr/crypto/p3.py
>>>
>>> However, a hash function is not an encryption algorithm itself. One does
>>> not
>>> "encrypt with md5" as the OP asked. For crypto-knowledgeable people, this
>>> may just be an issue of terminology (although I think an important one),
>>> but
>>> I think it demonstrates the ignorance of the OP and the need for Irmen's
>>> clarification.
>>>
>>> --
>>> Robert Kern
>>
>> I don't mean to disrespect Paul Rubin, but p3.py comes up in every
>> discussion
>> of cryptography in python on this list and, AFAICT, has yet to come under
>> significant cryptanalytic scrutiny. That doesn't make it a bad example in
>> this
>> case, but I would caution the OP that it probably doesn't make it a good
>> candidate for your encryption needs.
>
> For people looking for standardized cryptography, Google works fine to find
> PyCrypto or M2Crypto. p3 comes up so often in this group because people that
> need to ask here are looking for reasonably performant, pure-Python crypto,
> and p3 is the best-of-breed given those constraints (it happens to be
> mentioned here as an example, not a recommendation). Its security derives
> from its use of standardized, well-scrutinized components (and no, the
> recent attacks on SHA-1 do not affect the security properties that p3 relies
> on). It will probably never receive the kind of attention that AES or the
> rest get because it will never be fast enough to even be considered a peer
> of those algorithms.
>
> --
> Robert Kern

I have no comment on why it hasn't received substantial attention; my point
is simply that it hasn't, and that without that scrutiny it probably isn't wise
to depend on its security. There are plenty of tried-and-true cryptosystems
to use; people without an extensive knowledge of what they're getting into
should be encouraged to use them. Apologies if it sounded like I was
claiming more.

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


Python/Django linux build consultant required

2010-04-04 Thread Si

Hi, we are a San Francisco based startup company and are looking for a
Python/Django person to help us roll out our recently completed. We're
looking for 5 years + Python experience with a knowledge of tools such
as pyinstall (or other build systems). Please contact me directly
interested. Rgds.
-- 
http://mail.python.org/mailman/listinfo/python-list