Re: [Tutor] Python best practices

2009-11-30 Thread Albert-Jan Roskam
I'm currently reading the book "Code Complete" (I don't know the author name), 
which gives a lot of useful best practices. It's not specifically about one 
programming language. The author stresses that the majority of those practices 
are a matter of consensus/consistency and not a matter of religion. There is no 
one best way to do it.
 
Re: functions, the author recommends that they have one purpose and one purpose 
only, and that a function returns only one result.

Cheers!!
Albert-Jan

~~
In the face of ambiguity, refuse the temptation to guess.
~~

--- On Mon, 11/30/09, Alan Gauld  wrote:


From: Alan Gauld 
Subject: Re: [Tutor] Python best practices
To: tutor@python.org
Date: Monday, November 30, 2009, 1:57 AM


"spir"  wrote

>> > - functions should return one value (im not 100% of this one)
>> 
>> I 100% disagree or with this one.
> 
> Could you explain this bit, Lie? I'm very interested.
> I use multiple-value result myself, for it's so practicle in given cases.

My take on this is that in Python its OK to return multiple values if it
is as a tuple - because a tuple is really a single value. Its like returning
a record in Pascal or a struct in C or a List in Lisp...

> But it makes me uneasy; also have the impression (why?) it
> reveals wrong design.

Its better than

> a function both to have an effect (eg assignment outside the func scope) and
> return a value.

Side effects in functions are nearly always bad news and are always
avoidable if you can return multiple values (or pass arguments by reference).

> "Command-Query Separation Principle" (Eiffel) & Pascal "procedure vs 
> function".

You can have Command/Query separation without having side-effects.
A Query is a procedure or function that doesn't change anything but just
returns a result. A Command changes something, but it can be the thing
passed to it - or if a method of a class the internal data of the class.
Again a command can be a function or a procedure. Those are separate
concepts. (I very rarely write procedures in real programs - there is nearly
always something useful you can return - and in an object that's usually
a minimum of self! (Returning self is the default idiom in Smalltalk - it
allows chaining of methods)

HTH,

Alan G. 

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python best practices

2009-11-30 Thread ALAN GAULD
Code Complete by Steve McConnell is an excellent book
and I agree with almost everything in it. Including 
the advice about functions.

But as I said earlier the concept of multiple return 
values in Python is similar to returning a struct in C.
The key thing is that the function has a single purpose 
so if returning multiple values or a struct the values 
within that group should be related to the single purpose

In other words don't write a function called

def getLengthOrContent(dataStream, flag)
data = readData(dataAStream)  
if flag:
   return len(data)
else: 
   return data

Thats what I think is meant by bad practice in returning 
multiple values. The function returns two completely different 
things depending on some input flag.
 Alan Gauld
Author of the Learn To Program website
http://www.alan-g.me.uk/






From: Albert-Jan Roskam 
To: tutor@python.org; Alan Gauld 
Sent: Monday, 30 November, 2009 9:58:21
Subject: Re: [Tutor] Python best practices


I'm currently reading the book "Code Complete" (I don't know the author name), 
which gives a lot of useful best practices. It's not specifically about one 
programming language. The author stresses that the majority of those practices 
are a matter of consensus/consistency and not a matter of religion. There is no 
one best way to do it.
 
Re: functions, the author recommends that they have one purpose and one purpose 
only, and that a function returns only one result.

Cheers!!
Albert-Jan

~~
In the face of ambiguity, refuse the temptation to guess.
~~

--- On Mon, 11/30/09, Alan Gauld  wrote:


>From: Alan Gauld 
>Subject: Re: [Tutor] Python best practices
>To: tutor@python.org
>Date: Monday, November 30, 2009, 1:57 AM
>
>
>"spir"  wrote
>
>>> > - functions should return one value (im not 100% of this one)
>>> 
>>> I 100% disagree or with this one.
>> 
>> Could you explain this bit, Lie? I'm very interested.
>> I use multiple-value result myself, for it's so practicle in given cases.
>
>My take on this is that in Python its OK to return multiple values if it
>is as a tuple - because a tuple is really a single value. Its like returning
>a record in Pascal or a struct in C or a List in Lisp...
>
>> But it makes me uneasy; also have the impression (why?) it
>> reveals wrong design.
>
>Its better than
>
>> a function both to have an effect (eg assignment outside the func scope) and
>> return a value.
>
>Side effects in functions are
> nearly always bad news and are always
>avoidable if you can return multiple values (or pass arguments by reference).
>
>> "Command-Query Separation Principle" (Eiffel) & Pascal "procedure vs 
>> function".
>
>You can have Command/Query separation without having side-effects.
>A Query is a procedure or function that doesn't change anything but just
>returns a result. A Command changes something, but it can be the thing
>passed to it - or if a method of a class the internal data of the class.
>Again a command can be a function or a procedure. Those are separate
>concepts. (I very rarely write procedures in real programs - there is nearly
>always something useful you can return - and in an object that's usually
>a minimum of self! (Returning self is the default idiom in Smalltalk - it
>allows chaining of methods)
>
>HTH,
>
>Alan G. 
>
>___
>Tutor maillist  - 
> Tutor@python.org
>To unsubscribe or change subscription options:
>http://mail.python.org/mailman/listinfo/tutor
> 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] python closures

2009-11-30 Thread spir
Hello,

Below startup definitions:

x = 1

def f():
  n = 1
  def g0(a):
print (x + n + a) 
  return g0


I'm surprised the snippet below works as expected (py 2.6) without any trick:

g = f()
g(1)# --> 3

This means a (real) closure is built for g0, or what?
Thought I would need instead to use the old trick of pseudo default-parameters:

def f():
  n = 1
  def g0(a, n=n, x=x):
print (x + n + a) 
  return g0

to let the inner func g0 "remember" outer values. Why is this idiom used, then? 
Has something changed, or do I miss a relevant point?

The bit below also works:

x = 2
...
g(1)# --> 4

which seems to indicate python really embeds "symbolic references" (*) to outer 
*variables*, when creating a closure for g0. Not "pointer references" (**), 
otherwise the replacement of x would not be seen by the closure --like in the 
case of default-parameter.
Actually, I find this _Bad_. Obviously, the func's behaviour and result depend 
on arbitrary external values (referentially opaque). What do you think?

Denis

(*) by name, indirect access, second table lookup
(**) by address, direct access, no second lookup


la vita e estrany

http://spir.wikidot.com/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python closures

2009-11-30 Thread Wayne Werner
On Mon, Nov 30, 2009 at 4:24 AM, spir  wrote:

> which seems to indicate python really embeds "symbolic references" (*) to
> outer *variables*, when creating a closure for g0. Not "pointer references"
> (**), otherwise the replacement of x would not be seen by the closure --like
> in the case of default-parameter.
> Actually, I find this _Bad_. Obviously, the func's behaviour and result
> depend on arbitrary external values (referentially opaque). What do you
> think?
>

I'm not sure *why*/how this behaviour really works, other than it treats x
as a global variable... and probably treats n as something similar.

I don't know how bad I find it - you should be declaring the variables
you're planning to use in your function anyway... I'm sure there's *some*
case that it would end out problematic, but I can't think of one ATM.

-Wayne

-- 
To be considered stupid and to be told so is more painful than being called
gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness,
every vice, has found its defenders, its rhetoric, its ennoblement and
exaltation, but stupidity hasn’t. - Primo Levi
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python best practices

2009-11-30 Thread Wayne Werner
On Mon, Nov 30, 2009 at 4:06 AM, ALAN GAULD wrote:

>
> Thats what I think is meant by bad practice in returning
> multiple values. The function returns two completely different
> things depending on some input flag.
>

Now that's something I definitely agree with! I can't think of a single case
where that would make sense or be good practice. It would just create a ton
more work for the programmer/maintainer and obfuscate the code.

OTOH I can think of several reasons/times I've returned multiple related
values - for instance I was just writing a function for homework that found
the continuous subsequence with the greatest total that returned the start,
end, and total (more for my benefit than any other requirement... still, in
terms of time complexity and program complexity, it makes much more sense
than trying to break it up as "getMaxTotal" "getstart" and "getend"
functions - that would just be ridiculous!)

-Wayne


-- 
To be considered stupid and to be told so is more painful than being called
gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness,
every vice, has found its defenders, its rhetoric, its ennoblement and
exaltation, but stupidity hasn’t. - Primo Levi
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Equivalent exception of os.path.exists()

2009-11-30 Thread biboy mendz

http://pastebin.ca/1693849

This is end-of-chapter3 exercise of the book Core Python Programming.

I'm reading/searching in the book and other materials but is 
unsuccessful. There are at least 50 exceptions listed but I can't find 
anything close.


I commented out my modified script to just what *should* be applicable. 
Can you please point me to the right direction? TIA.



--
Regards,
bibs M.

Host/Kernel/OS  "cc02695" running Linux 2.6.31-5.slh.4-sidux-686 
[sidux 2009-02 Αιθήρ - kde-full - (200907141427) ]

www.sidux.com

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python closures

2009-11-30 Thread Kent Johnson
On Mon, Nov 30, 2009 at 5:24 AM, spir  wrote:
> Hello,
>
> Below startup definitions:
>
> x = 1
>
> def f():
>  n = 1
>  def g0(a):
>    print (x + n + a)
>  return g0
>
>
> I'm surprised the snippet below works as expected (py 2.6) without any trick:
>
> g = f()
> g(1)    # --> 3
>
> This means a (real) closure is built for g0, or what?

Yes, Python has had real (read-only) closures since 2.1 when nested
scopes where introduced:
http://docs.python.org/dev/whatsnew/2.1.html#pep-227-nested-scopes

Python 3 introduces the 'nonlocal' keyword which allows assignment to
names in enclosing scopes, presumably ending at last the debate about
whether Python has 'real' closures:
http://www.python.org/dev/peps/pep-3104/

> Thought I would need instead to use the old trick of pseudo 
> default-parameters:
>
> def f():
>  n = 1
>  def g0(a, n=n, x=x):
>    print (x + n + a)
>  return g0
>
> to let the inner func g0 "remember" outer values. Why is this idiom used, 
> then? Has something changed, or do I miss a relevant point?

That has not been needed since 2.1 though it is still useful when
closures are created in a loop (because closures are kind of late
bound - I'm not sure the exact technical explanation):
In [13]: def f():
   : l = []
   : for i in range(3):
   : def g():
   : print i
   : l.append(g)
   : return l

In [14]: for g in f(): g()
   :
2
2
2


But with the default argument it captures the value of i each time
through the loop:
In [15]: def f():
   : l = []
   : for i in range(3):
   : def g(i=i):
   : print i
   : l.append(g)
   : return l

In [16]: for g in f(): g()
   :
0
1
2

> The bit below also works:
>
> x = 2
> ...
> g(1)    # --> 4
>
> which seems to indicate python really embeds "symbolic references" (*) to 
> outer *variables*, when creating a closure for g0. Not "pointer references" 
> (**), otherwise the replacement of x would not be seen by the closure --like 
> in the case of default-parameter.

In your first definition of f(), x is global and not included in the
closure. This is the same behaviour you would have in older versions.
In your second definition of f(), x is bound to a default argument and
changing the global x doesn't change the result of g().

> Actually, I find this _Bad_. Obviously, the func's behaviour and result 
> depend on arbitrary external values (referentially opaque). What do you think?

That is always the case when a function accesses globals. Globals are
_Bad_, yes.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python closures

2009-11-30 Thread Stefan Behnel
spir, 30.11.2009 11:24:
> Below startup definitions:
> 
> x = 1
> 
> def f():
>   n = 1
>   def g0(a):
> print (x + n + a) 
>   return g0
> 
> I'm surprised the snippet below works as expected (py 2.6) without any trick:
> 
> g = f()
> g(1)  # --> 3
> 
> This means a (real) closure is built for g0, or what?

Yes.


> Thought I would need instead to use the old trick of pseudo 
> default-parameters:
> 
> def f():
>   n = 1
>   def g0(a, n=n, x=x):
> print (x + n + a) 
>   return g0
> 
> to let the inner func g0 "remember" outer values. Why is this idiom used, 
> then? Has something changed, or do I miss a relevant point?

Different use case. The above uses default arguments for n and x that can
be overridden by callers, but that have a value if callers do not pass
them. Values in closures can only be modified by the owner(s) of the names
that participate in the closure (i.e. the function f in this case).


> The bit below also works:
> 
> x = 2
> ...
> g(1)  # --> 4

x is not in the closure, it's a global name.


> the func's behaviour and result depend on arbitrary external values 
> (referentially opaque). What do you think?

It's a matter of how you use it. Closures make a lot of sense for many
cases, but there are certainly also cases where using them feels like a
goto - just like global variables.

Stefan

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Equivalent exception of os.path.exists()

2009-11-30 Thread Tim Golden

biboy mendz wrote:

http://pastebin.ca/1693849

This is end-of-chapter3 exercise of the book Core Python Programming.

I'm reading/searching in the book and other materials but is 
unsuccessful. There are at least 50 exceptions listed but I can't find 
anything close.


I commented out my modified script to just what *should* be applicable. 
Can you please point me to the right direction? TIA.



Ummm.. You're not actually trying to open the file.
raw_input just asks the user for a string. But it's
just a string. You could be going to use it for
anything. Try something like:

try:
 open (fname).close ()
except IOError, e:
 print "blah"


TJG
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Equivalent exception of os.path.exists()

2009-11-30 Thread Lie Ryan

On 12/1/2009 12:00 AM, biboy mendz wrote:

http://pastebin.ca/1693849

This is end-of-chapter3 exercise of the book Core Python Programming.

I'm reading/searching in the book and other materials but is
unsuccessful. There are at least 50 exceptions listed but I can't find
anything close.

I commented out my modified script to just what *should* be applicable.
Can you please point me to the right direction? TIA.


You're trying to take exception from raw_input(); raw_input() merely 
receive input from the stdin. raw_input() doesn't have anything to do 
with the file. You should expect the exception to come from the open() 
function instead.


However, on a little bit of note; open('...', 'w') will (almost) always 
work since if the file doesn't exists, python will simply create it. The 
only time it wouldn't work is if you've have file edit permission but 
not create new file permission.


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python closures

2009-11-30 Thread Hugo Arts
On Mon, Nov 30, 2009 at 11:24 AM, spir  wrote:
> Hello,
>
> Below startup definitions:
>
> x = 1
>
> def f():
>  n = 1
>  def g0(a):
>    print (x + n + a)
>  return g0
>
>
> I'm surprised the snippet below works as expected (py 2.6) without any trick:
>
> g = f()
> g(1)    # --> 3
>
> This means a (real) closure is built for g0, or what?
> Thought I would need instead to use the old trick of pseudo 
> default-parameters:
>
> def f():
>  n = 1
>  def g0(a, n=n, x=x):
>    print (x + n + a)
>  return g0
>
> to let the inner func g0 "remember" outer values. Why is this idiom used, 
> then? Has something changed, or do I miss a relevant point?

A real closure is indeed created, but you are missing something.
Consider this python session:

 >>> x = 0
 >>> def f():
x = x + 1

 >>> f()

Traceback (most recent call last):
  File "", line 1, in 
f()
  File "", line 2, in f
x = x + 1
UnboundLocalError: local variable 'x' referenced before assignment

The python docs offers some insight:

The execution of a function introduces a new symbol table used for the
local variables of the function. More precisely, all variable
assignments in a function store the value in the local symbol table;
whereas variable references first look in the local symbol table, then
in the local symbol tables of enclosing functions, then in the global
symbol table, and finally in the table of built-in names. Thus, global
variables cannot be directly assigned a value within a function
(unless named in a global statement), although they may be referenced.

( from http://docs.python.org/tutorial/controlflow.html#defining-functions )

In short, the problem is that writing "x =" will create a new
(unbound) local name for x, hiding the global one. The following
reference to x will find the local unbound variable and start
complaining.

If you wanted to create a local variable, your idiom is the fix you
want. If you want to modify the global one, use the 'global x'
statement to tell the interpreter that explicitly.

> The bit below also works:
>
> x = 2
> ...
> g(1)    # --> 4
>
> which seems to indicate python really embeds "symbolic references" (*) to 
> outer *variables*, when creating a closure for g0. Not "pointer references" 
> (**), otherwise the replacement of x would not be seen by the closure --like 
> in the case of default-parameter.
> Actually, I find this _Bad_. Obviously, the func's behaviour and result 
> depend on arbitrary external values (referentially opaque). What do you think?

I don't quite understand the point you're trying to make. The code
you're showing above seems like what is 'proper' behaviour to me. Can
you show an example demonstrating why it is bad?

Hugo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python closures

2009-11-30 Thread Hugo Arts
On Mon, Nov 30, 2009 at 4:16 PM, Kent Johnson  wrote:

> That has not been needed since 2.1 though it is still useful when
> closures are created in a loop (because closures are kind of late
> bound - I'm not sure the exact technical explanation):
> In [13]: def f():
>   :     l = []
>   :     for i in range(3):
>   :         def g():
>   :             print i
>   :         l.append(g)
>   :     return l
>
> In [14]: for g in f(): g()
>   :
> 2
> 2
> 2
>

This doesn't really have anything to do with closures specifically.
Variable lookup is done at runtime, not definition time. So when these
lookups for i are performed the value of i is indeed 2.

This wouldn't happen if closures used pointer references (as spir
called them). Then again, even with pointer references modifications
to mutable variables are still visible inside a closure.

Hugo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python best practices

2009-11-30 Thread spir
ALAN GAULD  dixit:

> But as I said earlier the concept of multiple return 
> values in Python is similar to returning a struct in C.
> The key thing is that the function has a single purpose 
> so if returning multiple values or a struct the values 
> within that group should be related to the single purpose

It's not enough I guess that returned values are "related to the [func's] 
single purpose".

The cases when I do not mind returning multiple values are precisely the ones 
when I could build the equivalent of a struct / record / (named) tuple / 
object. One that makes sense. In other words, when the set of values together 
describe *one single thing*. In some cases it's not worth building a "struct" 
if the caller will then just unpack it for further process.
Eg it can makes sense to 
   return (position, color)
instead of:
   return Point(position, color)
(provided there is a Point type defined)

But there are cases when I feel uneasy returning multiple values even if each 
one is clearly related to the (single) purpose the the func. The typical case 
for me is a match func that needs together:
1. tell about match outcome (success/failure)
2. move ahead the pointer position in source
3. return node (match result)
There are indeed numerous ways to do this, even to avoid returning more than 
one thing (have tried several). My latest method is to (1) raise exception in 
case of failure (2) have a source object that itself holds its pointer (3) then 
the node only is returned.
But these means are tricks (esp. unsing exception, which is _always_ a trick) 
to hide multiple actions and returns. 
Also note that a stuct composed of outcome+position+node does not make any 
sense (try to name it! ;-).
I guess the only proper solution is to build a real state machine (on which 
parse data is stored), but this makes parse tree construction extremely 
complicated in the general case, compared to having nodes directly returned by 
match funcs.

Denis


la vita e estrany

http://spir.wikidot.com/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] x is a global variable

2009-11-30 Thread Eike Welk
Hello Spir!

On Monday 30 November 2009, spir wrote:
> which seems to indicate python really embeds "symbolic references"
> (*) to outer *variables*, when creating a closure for g0. Not
> "pointer references" (**), otherwise the replacement of x would not
> be seen by the closure --like in the case of default-parameter.
> Actually, I find this _Bad_. Obviously, the func's behaviour and
> result depend on arbitrary external values (referentially opaque).

If I understand you right, you are proposing that the inner function 
g0 should get a separate copy of the global namespace. The copy should 
be done when the function is defined. 

When this would be implemented, inner functions (g0) would be treated 
very differently from outer functions (f), with respect to global 
variables. I would not like this different treatment. When a global 
variable is changed all functions should see the change. 

I think currently there are three 'containers' where functions can 
find variables in Python:
- local variables 
- the closure, which is empty in outer functions (f.func_closure)
- global variables, this is probably f.__module__.__dict__.

The exact semantics of closures seem to be a bit tricky. Below is some 
behavior I find surprising. I had expected that a local variable 'i' 
is created in function 'inc'. Instead the function fails with an 
error. (Producing the error is IMHO surprising, but sane behavior.):

In [25]:def clos():
  i = 0
  def inc():
i = i + 1
print i
  def pri():
print i
  return inc, pri

In [33]:inc, pri = clos()

In [34]:pri()
0

In [35]:inc()
---
UnboundLocalError Traceback (most recent call last)

/home/eike/ in ()
/home/eike/ in inc()
UnboundLocalError: local variable 'i' referenced before assignment


---
Eike.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Equivalent exception of os.path.exists()

2009-11-30 Thread spir
biboy mendz  dixit:

> http://pastebin.ca/1693849
> 
> This is end-of-chapter3 exercise of the book Core Python Programming.
> 
> I'm reading/searching in the book and other materials but is 
> unsuccessful. There are at least 50 exceptions listed but I can't find 
> anything close.
> 
> I commented out my modified script to just what *should* be applicable. 
> Can you please point me to the right direction? TIA.
> 
> 

What is your question?
If it's about the type of exception raised when os.path.exists fails, well, 
sure it's hard to find:

  print os.path.exists("foo".bar)
  ==> False

The output beeing a logical value, there is no failure.
A general method to get a type of exception matching a particuliar kind of 
error is to provoke an error of this given kind, eg:

  f = file("foo.bar")
  ==>
Traceback (most recent call last):
  File "__essai__.py", line 10, in 
f = file("foo.bar")
IOError: [Errno 2] No such file or directory: 'foo.bar'

In this case, the type is IOError.

Denis


la vita e estrany

http://spir.wikidot.com/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python closures

2009-11-30 Thread Eike Welk
On Monday 30 November 2009, Hugo Arts wrote:
> Consider this python session:
>  >>> x = 0
>  >>> def f():
>
>   x = x + 1
>
>  >>> f()
>
> Traceback (most recent call last):
>   File "", line 1, in 
> f()
>   File "", line 2, in f
> x = x + 1
> UnboundLocalError: local variable 'x' referenced before assignment
Ah... what a pity I didn't try this. I used similar code in my 
response to Spir and thought it would be somehow connected to 
closures. Sending nonsense statements to the list again... 

>
> The python docs offers some insight:
>
> The execution of a function introduces a new symbol table used for
> the local variables of the function. More precisely, all variable
> assignments in a function store the value in the local symbol
> table; whereas variable references first look in the local symbol
> table, then in the local symbol tables of enclosing functions, then
> in the global symbol table, and finally in the table of built-in
> names. Thus, global variables cannot be directly assigned a value
> within a function (unless named in a global statement), although
> they may be referenced.
>
> ( from
> http://docs.python.org/tutorial/controlflow.html#defining-functions
> )
>
> In short, the problem is that writing "x =" will create a new
> (unbound) local name for x, hiding the global one. The following
> reference to x will find the local unbound variable and start
> complaining.
I find that behavior quite counterintuitive. I expect:
1. 'x' is looked up, global variable 'x' is found; 
2. the addition is performed; 
3. a local name 'x' is created and bound to the result of the 
addition.

Producing the error is not insane. Because referencing a global 
variable and shadowing it in the same statement is bad style. 


Eike.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python closures

2009-11-30 Thread Alan Gauld


"spir"  wrote


x = 1

def f():
 n = 1
 def g0(a):
   print (x + n + a)
 return g0


I'm surprised the snippet below works as expected (py 2.6) without any 
trick:


I'm not sure how else it could work.
x is a global name so the function must reference it.
n is a local name so it musdt evaluate it (it will disappear otherwise)
a is a parameter delivered at run time.


This means a (real) closure is built for g0, or what?
Thought I would need instead to use the old trick of pseudo 
default-parameters:


def f():
 n = 1
 def g0(a, n=n, x=x):
   print (x + n + a)
 return g0


I did wonder if you would need n=n but I didn't think you would need x=x.

Its an interesting example and I confess I don't fully understand how 
Python's

naming/reference rules are working here.


to let the inner func g0 "remember" outer values.
Why is this idiom used, then? Has something changed, or do I miss
a relevant point?


I thought you might need to do it if n had been a parameter of f()... but
having tried it no, it works as above.

I look forward to the explanation.

Alan G. 



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] numerical simulation + SQLite

2009-11-30 Thread Faisal Moledina
Hey everyone,

I have a general issue that I'd like to discuss. I'm using Python to
run a numerical simulation where at each time step, I run a number of
operations and store the results before moving to the next timestep.
At first, I used a list to store a bunch of class instances, each of
which contained a bunch of data calculated at each time step. This
resulted in whopping memory usage (2.75 GB RAM, 3.75 GB VM).

So then I decided instead to use SQLite to store that information at
each timestep. This seems to work well, but it gets slow over time as
well. I've never used SQLite or Python before and I come from a
MATLAB-based engineering background rather than a programming one. I
was wondering if anyone had any tips for using SQLite efficiently.
Maybe a list of dos and don'ts.

I understand that specific help is impossible without a reduced sample
of code. Currently I'm looking for general guidelines and will come
back to this list for specific hangups. Thank you.

Faisal
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] x is a global variable

2009-11-30 Thread spir
Hello Eike!

Eike Welk  dixit:

> Hello Spir!
> 
> On Monday 30 November 2009, spir wrote:
> > which seems to indicate python really embeds "symbolic references"
> > (*) to outer *variables*, when creating a closure for g0. Not
> > "pointer references" (**), otherwise the replacement of x would not
> > be seen by the closure --like in the case of default-parameter.
> > Actually, I find this _Bad_. Obviously, the func's behaviour and
> > result depend on arbitrary external values (referentially opaque).
> 
> If I understand you right, you are proposing that the inner function 
> g0 should get a separate copy of the global namespace. The copy should 
> be done when the function is defined. 
> 
> When this would be implemented, inner functions (g0) would be treated 
> very differently from outer functions (f), with respect to global 
> variables. I would not like this different treatment. When a global 
> variable is changed all functions should see the change. 
> 
> I think currently there are three 'containers' where functions can 
> find variables in Python:
> - local variables 
> - the closure, which is empty in outer functions (f.func_closure)
> - global variables, this is probably f.__module__.__dict__.
> 
> The exact semantics of closures seem to be a bit tricky. Below is some 
> behavior I find surprising. I had expected that a local variable 'i' 
> is created in function 'inc'. Instead the function fails with an 
> error. (Producing the error is IMHO surprising, but sane behavior.):
> 
> In [25]:def clos():
>   i = 0
>   def inc():
> i = i + 1
> print i
>   def pri():
> print i
>   return inc, pri
> 
> In [33]:inc, pri = clos()
> 
> In [34]:pri()
> 0
> 
> In [35]:inc()
> ---
> UnboundLocalError Traceback (most recent call last)
> 
> /home/eike/ in ()
> /home/eike/ in inc()
> UnboundLocalError: local variable 'i' referenced before assignment

Well, this is certainly not specific to closures.

i = 0
def f():
  i = i+1
  print i
f()
==> UnboundLocalError

Imo, in this case, "i = i+1" is a kind of "paradoxal injonction" (lol! not sure 
of the exact idiom in english). You tell python both to create a local i (thus 
ignore any other scope to lookup for variables called 'i') and to use global i 
to define the local one.
If I were the victim of such a "paradoxal injonction" I would reply with a 
naughty word!

> ---
> Eike.
> 

Denis


la vita e estrany

http://spir.wikidot.com/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Equivalent exception of os.path.exists()

2009-11-30 Thread biboy mendz



spir wrote:


What is your question?
If it's about the type of exception raised when os.path.exists fails, well, 
sure it's hard to find:

  print os.path.exists("foo".bar)
  ==> False

  
My question is: i'm looking for type of exception that more or less 
equivalent to os.path.exists attribute. I know for a fact that this 
method yields true or false. The exercise in the book says use 
try-except in place of os.path.exists(). That sure is (to me) quite 
difficult task. Instead of using the available function you're are 
tasked to do the alternative.


Lie and Tim's input are true that raw_input doesnt do anything or you 
cant catch exception error from it. And i'm wrong in placing the 
try-except clause, it should be on the fobj-open line. But im still 
looking for the exception that will be raised when i input a filename 
and that file already exists. I hope you get what i mean :-)







The output beeing a logical value, there is no failure.
A general method to get a type of exception matching a particuliar kind of 
error is to provoke an error of this given kind, eg:

  f = file("foo.bar")
  ==>
Traceback (most recent call last):
  File "__essai__.py", line 10, in 
f = file("foo.bar")
IOError: [Errno 2] No such file or directory: 'foo.bar'

In this case, the type is IOError.

Denis


la vita e estrany

http://spir.wikidot.com/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

  


--
Regards,
bibs M.

Host/Kernel/OS  "cc02695" running Linux 2.6.31-5.slh.4-sidux-686 
[sidux 2009-02 Αιθήρ - kde-full - (200907141427) ]

www.sidux.com

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Equivalent exception of os.path.exists()

2009-11-30 Thread Tim Golden

biboy mendz wrote:
Lie and Tim's input are true that raw_input doesnt do anything or you 
cant catch exception error from it. And i'm wrong in placing the 
try-except clause, it should be on the fobj-open line. But im still 
looking for the exception that will be raised when i input a filename 
and that file already exists. I hope you get what i mean :-)


There isn't one. The string you input which is a filename is just
a string. There's no reason for Python to check whether it is a
valid filename, any more than to check it is a valid integer or
a valid recipe on goodrecipes.com. You have to decide what you
want to do with the string.

Then you do that (try to open it as a file; try to convert it
to a number; try to use it as a URL to goodrecipes.com) and
deal with exceptions appropriately.

TJG
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Equivalent exception of os.path.exists()

2009-11-30 Thread Dave Angel

spir wrote:

biboy mendz  dixit:

  

http://pastebin.ca/1693849

This is end-of-chapter3 exercise of the book Core Python Programming.

I'm reading/searching in the book and other materials but is 
unsuccessful. There are at least 50 exceptions listed but I can't find 
anything close.


I commented out my modified script to just what *should* be applicable. 
Can you please point me to the right direction? TIA.






What is your question?
If it's about the type of exception raised when os.path.exists fails, well, 
sure it's hard to find:

  print os.path.exists("foo".bar)
  ==> False

The output beeing a logical value, there is no failure.
A general method to get a type of exception matching a particuliar kind of 
error is to provoke an error of this given kind, eg:

  f = file("foo.bar")
  ==>
Traceback (most recent call last):
  File "__essai__.py", line 10, in 
f = file("foo.bar")
IOError: [Errno 2] No such file or directory: 'foo.bar'

In this case, the type is IOError.

Denis


la vita e estrany

http://spir.wikidot.com/


  
As others have pointed out, you need to spell out the question you're 
trying to answer.  Not all of us have a copy of that book, or have it 
handy in any case.


If you're trying to write a function that produces equivalent results to 
os.path.exists(), but uses exceptions to do so, you'll need to know 
first what that function does.  It checks if a path is valid, and refers 
to an existing file *or* *directory*.So if you decide that the path 
doesn't specify a file, then you also have to check if it specifies a 
directory.


It's not actually correct to just use open(), even for the file portion, 
because open() may fail if the file is already open exclusively by 
another program.  For a little while, the file exists, but you may not 
open it.


I think if I couldn't use any of the os.path functions, I'd resort to 
using os.walk().  Once again, I wouldn't expect any exceptions.  I'd 
just walk through the whole tree, and see if the desired file was on any 
of the returned lists.  Don't forget to use case-insensitive comparison 
on Windows.


The problem with a poorly reworded question is there are answers that 
are perhaps useless to the original problem.  If I couldn't use 
os.path.exists(), then I'd substitute os.path.isfile() and 
os.path.isdir(), checking the one if the other fails.  But this wouldn't 
raise any exceptions either, so it wouldn't be the learning experience 
the author wants.


My suspicion is that the author just wants you to try to do an open() 
(readonly), inside a try/except block, and to successfully handle the 
exception.  Among other things, this requires you to find out which 
exception type to use.


DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python closures

2009-11-30 Thread spir
Eike Welk  dixit:

> On Monday 30 November 2009, Hugo Arts wrote:
> > Consider this python session:  
> >  >>> x = 0
> >  >>> def f():  
> >
> > x = x + 1
> >  
> >  >>> f()  
> >
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > f()
> >   File "", line 2, in f
> > x = x + 1
> > UnboundLocalError: local variable 'x' referenced before assignment  
> Ah... what a pity I didn't try this. I used similar code in my 
> response to Spir and thought it would be somehow connected to 
> closures. Sending nonsense statements to the list again... 

My answer was stupid as well. Actually, guess I hadn't understood the real 
sense of Hugo's comment... until I tried to answer your post, Eike.

Denis

PS:
I just found by chance an article (actually a pair of) by Paul Graham (Lisp 
advocate) that really show how pitifully helpless python is (I'm half joking) 
compared to "Lisp/Perl/Smalltalk/Javascript".
http://www.paulgraham.com/icad.html (see end of article)
http://www.paulgraham.com/icadmore.html (search Paul Prescod's reply)

Quote:
<< I was actually surprised at how badly Python did. I had never realized, for 
example, that a Python lambda-expression  couldn't contain the same things as a 
named function, or that *variables from enclosing scopes are visible but not 
modifiable*. Neither Lisp nor Perl nor Smalltalk nor Javascript impose either 
restriction. >>
(I highlight)

Please don't take my quoting as an occasion for flamewar -- I'm just quoting to 
bring an external point of view into the thread. 

An interesting thing he points earlier is that (provided anonymous funcs were 
real funcs and changing external vars were possible) python,'s idiom for his 
example would not be:

def accum(n):
   lambda i: n += i

but instead:

def accum(n):
   return lambda i: return n += i

But actually he's wrong, I guess, it would even be:

def accum(n):
   return lambda i: n += i ; return n

(cannot return a statement) 

Denis


la vita e estrany

http://spir.wikidot.com/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Equivalent exception of os.path.exists()

2009-11-30 Thread Sander Sweers
2009/11/30 biboy mendz :
> clause, it should be on the fobj-open line. But im still looking for the
> exception that will be raised when i input a filename and that file already
> exists. I hope you get what i mean :-)

There is no exception to alert you a file already exists. Depending on
how you open the file (mode) it will either read, write or append to
the file. If the file exists and you open it in write mode it *will*
overwrite the file. See [1] for more info.

So what you need to do is check yourself if the file exists and make
the python script take appriate action. For example:

import os
fname = "C:\\testfile.txt"
if os.path.exists(fname):
do something if exists
else:
   do something else if not exists

Greets
Sander

[1] http://docs.python.org/library/functions.html#open
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Equivalent exception of os.path.exists()

2009-11-30 Thread spir
biboy mendz  dixit:

> 
> 
> spir wrote:
> >
> > What is your question?
> > If it's about the type of exception raised when os.path.exists fails, well, 
> > sure it's hard to find:
> >
> >   print os.path.exists("foo".bar)
> >   ==> False
> >
> >   
> My question is: i'm looking for type of exception that more or less 
> equivalent to os.path.exists attribute. I know for a fact that this 
> method yields true or false. The exercise in the book says use 
> try-except in place of os.path.exists(). That sure is (to me) quite 
> difficult task. Instead of using the available function you're are 
> tasked to do the alternative.
> 
> Lie and Tim's input are true that raw_input doesnt do anything or you 
> cant catch exception error from it. And i'm wrong in placing the 
> try-except clause, it should be on the fobj-open line. But im still 
> looking for the exception that will be raised when i input a filename 
> and that file already exists. I hope you get what i mean :-)

Right. So, the exercise is about replacing an explicit check by try...except. 
But unlike what you seem to think above, you won't get any error from file 
*writing*.
Think at variables: python does not make any distinction between creation or 
change, so that you you won't get any error by "writing" a variable that 
already exist, even if your intention was to create a new one (and you wrote a 
wrong name). Because there is no syntactic difference between creation and 
change. Conversely, if you create a new variable when you intended to change an 
existing one, you won't get any nice error, it will be silently processed. 
Right?
The same with files. So you cannot have such errors at file writing, if the 
file exists, it will be overwritten. So, you can only use try...except for file 
*reading*.
See my previous post.


(*) Except in the case when you try to overwrite you don't have (as user) the 
right to change, or if you try to create a file in a folder you don't have 
writing right in.

> > The output beeing a logical value, there is no failure.
> > A general method to get a type of exception matching a particuliar kind of 
> > error is to provoke an error of this given kind, eg:
> >
> >   f = file("foo.bar")
> >   ==>
> > Traceback (most recent call last):
> >   File "__essai__.py", line 10, in 
> > f = file("foo.bar")
> > IOError: [Errno 2] No such file or directory: 'foo.bar'
> >
> > In this case, the type is IOError.
> >
> > Denis





la vita e estrany

http://spir.wikidot.com/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Equivalent exception of os.path.exists()

2009-11-30 Thread christopher . henk
biboy mendz  wrote on 11/30/2009 03:04:52 PM:

> 
> 
> spir wrote:
> >
> > What is your question?
> > If it's about the type of exception raised when os.path.exists fails, 
well, sure it's hard to find:
> >
> >   print os.path.exists("foo".bar)
> >   ==> False
> >
> > 
> My question is: i'm looking for type of exception that more or less 
> equivalent to os.path.exists attribute. I know for a fact that this 
> method yields true or false. The exercise in the book says use 
> try-except in place of os.path.exists(). That sure is (to me) quite 
> difficult task. Instead of using the available function you're are 
> tasked to do the alternative.
> 

Looking at my copy of Core Python the exercise says to follow the example 
3.2 (readTextFile.py).  There he uses the try except block around the open 
function call. 

This as mentioned could raise an IOError.  It will be triggered in a 
different manner then os.path.exist since you are now trying to open a 
file to write, instead of checking if it exist.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Equivalent exception of os.path.exists()

2009-11-30 Thread Alan Gauld


"Dave Angel"  wrote

My suspicion is that the author just wants you to try to do an open() 
(readonly), inside a try/except block, and to successfully handle the 
exception.  


And the critical thing here is that it must be an open in read mode. 
As others pointed out if you use write mode it will (nearly) always 
succeed, even if that means overwriting an existing file.


Alan G.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] numerical simulation + SQLite

2009-11-30 Thread Alan Gauld
"Faisal Moledina"  wrote 
.

At first, I used a list to store a bunch of class instances, each of
which contained a bunch of data calculated at each time step. This
resulted in whopping memory usage (2.75 GB RAM, 3.75 GB VM).

So then I decided instead to use SQLite to store that information at
each timestep. This seems to work well, but it gets slow over time as
well. 


You may need to be realistic in your expectations.
A database is writing to disk which will be slower than working in 
memory. And a 3GB file takes a while to read/traverse, even with 
indexes. It depends a lot on exactly what you are doing. If its mainly 
writing it should not be much slower than writing to a flat file. If you 
are doing a lot of reading - and you have used indexes - then it 
should be a lot faster than a file.


But RAM - if you have enough - will always be fastest, by about 100 times.
The problem is when you run out, you revert to using files and that's 
usually slower than a database...


But without details of your usage pattern and database schema 
and SQL code etc it is, as you say, impossible to be specific.


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] numerical simulation + SQLite

2009-11-30 Thread Eike Welk
Hello Faisal!

Just in case you don't know it, maybe Pytables is the right solution 
for you. It is a disk storage library specially for scientific 
applications:
http://www.pytables.org/moin

The makers claim, that it is fast. It has on the fly data compression 
which allegedly makes the library faster because fewer data has to be 
written to disk. 

The lead developer gave a talk about the topic with interesting 
slides. He proposes to compress not only data that is stored on 
disks, but also data resides in RAM; because even RAM is very slow 
compared to the speed of modern processors. 
(The slides are near the top of the page.)
http://www.euroscipy.org/presentations/abstracts/abstract_alted.html


Eike.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] read in ascii and plot

2009-11-30 Thread questions anon
I would like to read in two columns of data from a *.txt file

I type

f=open("e:/testascii.txt")
import pylab
pylab.scatter(f)

and then receive an error.
How do I point it to each column and do I need to do anything about the
space gap between the two columns?
Thanks in advance.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python closures

2009-11-30 Thread Dave Angel

Alan Gauld wrote:


"spir"  wrote

I did wonder if you would need n=n but I didn't think you would need x=x.

Its an interesting example and I confess I don't fully understand how 
Python's

naming/reference rules are working here.


to let the inner func g0 "remember" outer values.
Why is this idiom used, then? Has something changed, or do I miss
a relevant point?


I thought you might need to do it if n had been a parameter of f()... but
having tried it no, it works as above.

I look forward to the explanation.

Alan G.



Maybe a more complex example might show the various linkages.

glob = 42

def outer(parm1):
   free = 12
   free3 = 19
   def inner(parm2, parm3=free3):
   print "global", glob, ", free vars", parm1, free, free3, ", 
locals", parm2, parm3

   free = 49
   free3 = 48
   return inner

newfunc = outer(10)
newfunc(45)


produces output:
  global 42 , free vars 10 49 48 , locals 45 19

So when the inner() function is actually called, glob is just a global.  
parm1, fre, and free3 hold the values they ended up with when outer() 
returned, and local parm2 is passed by top-level code, while local parm3 
gets its default value assigned when "def inner(...) was executed.


Notice that the free variables free, free3, and parm1 are referring to 
the function's ending state, not to the state when the function was 
defined.  This has an impact when you've got inner being defined in a 
loop.  And this example could be made more complex if outer() is a 
generator, in which case it may not have actually ended when inner gets 
called.


HTH
DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] x is a global variable

2009-11-30 Thread Dave Angel

spir wrote:

Hello Eike!

Eike Welk  dixit:

  


Well, this is certainly not specific to closures.

i = 0
def f():
  i = i+1
  print i
f()
==> UnboundLocalError

Imo, in this case, "i = i+1" is a kind of "paradoxal injonction" (lol! not sure 
of the exact idiom in english). You tell python both to create a local i (thus ignore any other 
scope to lookup for variables called 'i') and to use global i to define the local one.
If I were the victim of such a "paradoxal injonction" I would reply with a 
naughty word!

  


I believe the easiest model to understand the behavior is:

The compiler scans the entire function to find which variables are 
assigned (via =, as, or other syntax) anywhere in the function.  Then 
for those variables, all references are done without any dictionary 
accesses.  Thus an assignment anywhere (not just on the same line) cause 
all references to be to the (unbound) local.


DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] read in ascii and plot

2009-11-30 Thread Wayne Werner
On Mon, Nov 30, 2009 at 5:55 PM, questions anon wrote:

> I would like to read in two columns of data from a *.txt file
>
> I type
>
> f=open("e:/testascii.txt")
> import pylab
> pylab.scatter(f)
>
> and then receive an error.
> How do I point it to each column and do I need to do anything about the
> space gap between the two columns?
> Thanks in advance.
>

A sample of the data is always helpful, but I'll take a shot in the dark.

If you have data like this:

2.31 72
9823
... 
347.32

And those are x y pairs you could do something like this:

f = open('input.txt')
#List comprehension to read all the lines as [[x1, y1], [x2, y2], ... [xn,
yn]]
data = [line.split() for line in f]
# Reorient values as [(x1, x2,... xn), (y1, y2, ... yn)]
data = zip(*data)
# plot the xy vals
pylab.scatter(data[0], data[1])

That should be something along the lines of what you're looking for.
HTH,
Wayne

-- 
To be considered stupid and to be told so is more painful than being called
gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness,
every vice, has found its defenders, its rhetoric, its ennoblement and
exaltation, but stupidity hasn’t. - Primo Levi
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] numerical simulation + SQLite

2009-11-30 Thread bob gailer

Faisal Moledina wrote:

Hey everyone,

I have a general issue that I'd like to discuss. I'm using Python to
run a numerical simulation where at each time step, I run a number of
operations and store the results before moving to the next timestep.


What do you do with the results after the simulation run?

How precise do the numbers have to be?

--
Bob Gailer
Chapel Hill NC
919-636-4239
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python closures

2009-11-30 Thread Kent Johnson
On Mon, Nov 30, 2009 at 7:50 PM, Dave Angel  wrote:

> And this
> example could be made more complex if outer() is a generator, in which case
> it may not have actually ended when inner gets called.

Indeed.

In [8]: def gen():
   ...: for i in range(5):
   ...: def inner():
   ...: print i
   ...: yield inner

In [9]: g = gen()

In [10]: outer = g.next()

In [11]: outer()
0

In [12]: g.next()

In [13]: outer()
1

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] read in ascii and plot

2009-11-30 Thread Kent Johnson
On Mon, Nov 30, 2009 at 8:26 PM, Wayne Werner  wrote:

> A sample of the data is always helpful, but I'll take a shot in the dark.
> If you have data like this:
> 2.31     72
> 98        23
> ...         
> 34        7.32
> And those are x y pairs you could do something like this:
> f = open('input.txt')
> #List comprehension to read all the lines as [[x1, y1], [x2, y2], ... [xn,
> yn]]
> data = [line.split() for line in f]

You have to convert the text strings to float somewhere, for example
data = [ map(float, line.split()) for line in f ]

> # Reorient values as [(x1, x2,... xn), (y1, y2, ... yn)]
> data = zip(*data)
> # plot the xy vals
> pylab.scatter(data[0], data[1])

Or, IMO a little clearer,
x, y = zip(*data)
pylab.scatter(x, y)

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] [Errno 9] Bad file descriptor

2009-11-30 Thread Khalid Al-Ghamdi
Hi everybody,

I'm running python 2.6.1 on vista and I'm trying to use the csv module to
write to a csv file and get the average of some numbers, but I keep getting
the following error:

Traceback (most recent call last):
  File "C:\Python31\MyCSVProjectFinal.py", line 83, in 
writer.writerow(headings)
IOError: [Errno 9] Bad file descriptor

line 83 refers to the following code, specifically to the one in capital (in
the actual code it's not in capital by the way):

headings = linesInCSV[0] # e.g. ['Measured1', 'Measured2']
csvOutFileName = easygui.filesavebox(title = "Choose output file for
averages", )
if csvOutFileName is not None:
print "Saving using: "+csvOutFileName
csvOut = file(csvOutFileName, 'rb')
writer = csv.writer(csvOut)
*WRITER.WRITEROW(HEADINGS)*
for index in range(len(measured1)):
writer.writerow([measured1[index], measured2[index]])
writer.writerow([averaged1, averaged2])
else:
print "No filename for saving"


so, my problem is I don't know why it keeps giving me this error. I've
checked on the internet, but I haven't found anything to help resolve this
error.

I hope you can be of help.

PS: I've added the complete code below for reference.

thanks


import csv
import sys
import easygui

def getFileAndPath():
"Get fully-qualified path to the csv file"
# TODO argInitialFile = '*.csv'
fileAndPath = easygui.fileopenbox(title="Select .CSV file")
print "Using:",fileAndPath
return fileAndPath

def getLinesInCSVFile(fileAndPath):
"read lines in CSV file, return a list of these lines"
linesInCSV = []
reader = csv.reader(open(fileAndPath, "rb"))
for row in reader:
linesInCSV.append(row)
return linesInCSV

def justNumbers(listOfStrings):
"True if the list contains just numbers represented as strings"
# e.g. ['22.4', '23.9']
isJustNumbers = True
for item in listOfStrings:
try:
nbr = float(item)
except ValueError:
isJustNumbers = False
return isJustNumbers

def getNumbers(listOfStrings):
"Convert a list of strings-of-numbers to a list of numbers, e.g.
['22.4', '23.9'] -> [22.4, 23.9]"
numbers = []
for item in listOfStrings:
nbr = float(item)
numbers.append(nbr)
return numbers

def average(values):
"""Computes the arithmetic mean of a list of numbers"""
return sum(values, 0.0) / len(values)

if __name__ == "__main__":
# get the file-name
#fileAndPath = getFileAndPath()
# NOTE quick hack to make our test/development process quicker
fileAndPath = "c:\\testing\\measured2.csv"

# read the CSV file
linesInCSV = getLinesInCSVFile(fileAndPath)

measured1 = []
measured2 = []
for n in range(1,4):
line = linesInCSV[n]
isJustNumbers = justNumbers(line)
if not isJustNumbers:
print "ERROR!  Expected a line of numbers, instead we got:",line
sys.exit()
# we only get here if justNumbers reports that we only have numbers

# so we can extract the list of floating-point numbers
numbers = getNumbers(line)
measured1.append(numbers[0])
measured2.append(numbers[1])
averaged1 = average(measured1)
averaged2 = average(measured2)

# Show values of Measured1 in a choicebox
# We don't care about the choices, this is just for output
#easygui.choicebox(message = "Sorted values in Measured1", title =
"Measured1", choices = measured1)

headings = linesInCSV[0] # e.g. ['Measured1', 'Measured2']
csvOutFileName = easygui.filesavebox(title = "Choose output file for
averages", )
if csvOutFileName is not None:
print "Saving using: "+csvOutFileName
csvOut = file(csvOutFileName, 'rb')
writer = csv.writer(csvOut)
writer.writerow(headings)
for index in range(len(measured1)):
writer.writerow([measured1[index], measured2[index]])
writer.writerow([averaged1, averaged2])
else:
print "No filename for saving"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] does poplib have proxy support ?

2009-11-30 Thread Shashwat Anand
Does poplib/imaplib have proxy support like urllib?
I was unable to get connected to my mail.
Here is what i tried :

>>> proxies = {'http': 'http://username:passw...@proxy:8080'}
>>> host = 'pop.gmail.com'
>>> me = 'usern...@gmail.com'
>>> pass = '**'
>>> pop = poplib.POP3_SSL(host)

Traceback (most recent call last):
  File "", line 1, in 
TypeError: __init__() got an unexpected keyword argument 'proxies'
>>> pop = poplib.POP3_SSL(host)
Traceback (most recent call last):
  File "", line 1, in 
  File
"/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/poplib.py",
line 357, in __init__
raise socket.error, msg
socket.error: (60, 'Operation timed out')
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Equivalent exception of os.path.exists()

2009-11-30 Thread bibi midi
Thanks to all of you that replied. Your inputs are very helpful and
informative.


On Tue, Dec 1, 2009 at 12:14 AM, Sander Sweers wrote:

>
> There is no exception to alert you a file already exists. Depending on
> how you open the file (mode) it will either read, write or append to
> the file. If the file exists and you open it in write mode it *will*
> overwrite the file. See [1] for more info.
>
> So what you need to do is check yourself if the file exists and make
> the python script take appriate action. For example:
>
> import os
> fname = "C:\\testfile.txt"
> if os.path.exists(fname):
>do something if exists
> else:
>   do something else if not exists
>
> Greets
> Sander
>

Like i thought so, there is no exception to catch if a file already exist.
I've been browsing the many types of exceptions and cant find anything thats
close. Thank you for clarifying.

I may have misunderstood the exercise question and will have to return to it
to do another approach.

For the record below is the working copy of the script. Here i understand
how the os.path.exists() method works.

while True:
fname = raw_input('please enter filename: ')
if os.path.exists(fname):
print('ERROR: %s exists!') % fname
elif fname.isspace():
print('Space is not allowed!')
else:
print('you entered %s') % fname
break

all = []# container list to hold user input lines
print "\nPopulate your file! \n"
quit_prompt = "[to quit enter a dot '.' by itself]--> "

while True:
entry = raw_input(quit_prompt)
if entry == '.':
break
else:
all.append(entry)

confirm = raw_input('save file to disk?(y/N)')
confirm = confirm.lower()   #convert to lowercase
if confirm == 'y':
fobj = open(fname, 'w')
fobj.write('\n'.join(all))
fobj.close()
print('DONE! open %s to view your file') % fname
else:
print 'not saving to disk!'
sys.exit()

Thank you.


-- 
Best Regards,
bibimidi
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor