Re: [Tutor] Need Explanation...

2011-12-10 Thread Asokan Pichai
On Sat, Dec 10, 2011 at 1:11 PM, sunil tech  wrote:
> hi,
>
> Consider a list: a = [1,2,3]
>
> & a simple function, which when called it will append 100 to the list.
>
> def app(x):
>      return x.append(100)
>
> p = app(a)
>
> now list holds appended value [1,2,3,100]
> but p is empty... why it is?
>
> please teach.
>
append() Method is a mutator; it modifies the list.

DOES NOT return the modified list; returns None
to be exact

HTH

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


Re: [Tutor] Need Explanation...

2011-12-10 Thread Alan Gauld

On 10/12/11 07:41, sunil tech wrote:


/def app(x):/
/ return x.append(100)/
/
/p = app(a)/
/
/now list holds appended value [1,2,3,100]/
/but p is empty... why it is?/


Because app() returns the result of append().
But append() returns None, since it modifies the list in place.

This is one of the few features of Python I dislike. It would not have 
been difficult to make these modifier methods return the thing modified. 
This style would then allow chained methods.


We do it with strings:

"foobar is a string".rstrip('ing').upper()

because strings are immutable. But we could have done it with other 
sequence types too. Sadly we didn't and history/tradition leaves us with 
these counterintuitive modifiers that return None. It catches everybody 
out at some point...



--
Alan G
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] Help with update_wrapper

2011-12-10 Thread Peter Otten
Emeka wrote:

> Could someone explain " functools.update_wrapper" with simple examples?

Since this is not for the absolute beginner I'm assuming you are already 
familiar with decorators. In their most common form these are functions that 
take a function and wrap that function into another function.

@deco
def f(...):
...

is only syntactic sugar for

def f(...):
...
f = deco(f)

i. e. you can get a decorated version of f on the fly with deco(f).

Suppose you have a function add() that adds two arguments and a decorator 
log_call() that prints the name of the called function before calling it:

>>> import pydoc
>>> pydoc.pager = pydoc.plainpager # this lets you see the output of help()
>>> from functools import update_wrapper
>>> def add(x, y):
... "calculate x+y"
... return x + y
...
>>> def log_call(f):
... def g(*args, **kw):
... print "calling", f.__name__
... return f(*args, **kw)
... return g
...
>>> add(1, 2)
3
>>> log_call(add)(3, 4)
calling add
7

It works, but if you want to learn more about the decorated function

>>> help(log_call(add))
Help on function g in module __main__:

g(*args, **kw)

you get the name, the signature and docstring of the wrapping function g(), 
i. e. by decorating it you lose valuable information about add(). If you 
decorate a mul() function

>>> @log_call
... def mul(x, y):
... "multiply x and y"
... return x * y
...
>>> help(mul)
Help on function g in module __main__:

g(*args, **kw)

the help will be exactly the same. 
functools.update_wrapper() is a partial fix for the problem:

>>> add2 = update_wrapper(log_call(add), add)
>>> add2(5, 6)
calling add
11
>>> help(add2)
Help on function add in module __main__:

add(*args, **kw)
calculate x+y

It copies name and docstring (but not the function signature).
However, I don't think I will ever use it directly, I'd prefer using 
functools.wraps:

>>> def log_call2(f):
... @wraps(f)
... def g(*args, **kw):
... print "calling", f.__name__
... return f(*args, **kw)
... return g
...
>>> @log_call2
... def add(x, y):
... "yadda"
... return x + y
...
>>> add(1, 2)
calling add
3
>>> help(add)
Help on function add in module __main__:

add(*args, **kw)
yadda

If you are seriously interested in this you should also have a look at 
Michele Simionato's decorator module (http://pypi.python.org/pypi/decorator) 
that also fixes the signature:

>>> import decorator
>>> @decorator.decorator
... def log_call(f, *args, **kw):
... print "calling", f.__name__
... return f(*args, **kw)
...
>>> @log_call
... def add(x, y):
... "calculate x+y"
... return x + y
...
>>> add(1, 2)
calling add
3
>>> help(add)
Help on function add in module __main__:

add(x, y)
calculate x+y





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


Re: [Tutor] how to handle big numbers

2011-12-10 Thread Peter Otten
surya k wrote:

> Finding factorial of 8 or 9 isn't big. If I would like to find factorial
> of 32327, how can I ?

gmpy is a library designed for working with large numbers. Compare:

>>> import time
>>> def bench(f, *args):
... start = time.time()
... try:
... return f(*args)
... finally:
... print time.time() - start
...
>>> def fac(n):
... f = 1
... for i in xrange(1, n+1):
... f *= i
... return f
...
>>> x = bench(fac, 1000)
0.00276589393616
>>> x = bench(fac, 1)
0.247038125992
>>> x = bench(fac, 3)
1.40305805206
>>> import gmpy
>>> x = bench(gmpy.fac, 3)
0.0243360996246
>>> x = bench(gmpy.fac, 10**6)
0.8047311306
>>> x.numdigits()
5565709

http://pypi.python.org/pypi/gmpy

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


[Tutor] Pysces Problem

2011-12-10 Thread Mateusz Koryciński

Hi,

Does any of you use Pysces? I need to run some simulations and 
unfortunately I cannot create plot. After importing Pysces it claims 
that Matplotlib is not available, but it's installed for sure since I 
can import  matplotlib. When I try to do plot after simulation:


---
AttributeErrorTraceback (most recent call last)
/home/mateusz/Pysces/ in ()
> 1 mod.doSimPlot()

/usr/lib/python2.7/site-packages/pysces/PyscesModel.pyc in 
doSimPlot(self, end, points, plot, fmt, filename)

   5584 self.sim_points = points
   5585 self.Simulate()
-> 5586 self.SimPlot(plot=plot, format=fmt, filename=filename)
   5587
   5588 def doSimPerturb(self,pl,end):

/usr/lib/python2.7/site-packages/pysces/PyscesModel.pyc in SimPlot(self, 
plot, filename, title, log, format)
   6955 data, labels = self.data_sim.getSimData(*plot, 
**kwargs)

   6956 del allowedplots
-> 6957 plt.plotLines(data, 0, range(1, data.shape[1]), 
titles=labels, formats=[format])
   6958 # set the x-axis range so that it is original range + 
0.2*sim_end


   6959 # this is a sceintifcally dtermned amount of space that 
is needed for the title at the



AttributeError: 'NoneType' object has no attribute 'plotLines'

I've already exported matplotlib localization in ipython by: 
sys.path.append("/usr/lib/python2.7/site-packages/")


Thank you in advance for any help!

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


Re: [Tutor] how to handle big numbers

2011-12-10 Thread lina
On Sat, Dec 10, 2011 at 6:09 PM, Peter Otten <__pete...@web.de> wrote:
> surya k wrote:
>
>> Finding factorial of 8 or 9 isn't big. If I would like to find factorial
>> of 32327, how can I ?
>
> gmpy is a library designed for working with large numbers. Compare:
>
 import time
 def bench(f, *args):
> ...     start = time.time()
> ...     try:
> ...             return f(*args)
> ...     finally:
> ...             print time.time() - start
> ...
 def fac(n):
> ...     f = 1
> ...     for i in xrange(1, n+1):
> ...             f *= i
> ...     return f
> ...

sorry to interrupt, I tried your example,

$ cat time_func.py
#!/usr/bin/python3

import time

def bench(f, *args):
start = time.time()
try:
return f(*args)
finally:
print(time.time() - start)

def fac(n):
f = 1
for i in range(1,n+1):
f *= i
return f

on idle3

>>> import time_func
>>> time_func.bench(time_func.fac,1000)
0.0015549659729003906
4023872600770937735437024339230039857193748642107146325437999104299385123986290205920442084869694048004799886101971960586316668729948085589013238296699445909974245040870737599188236277271887325197795059509952761208749754624970436014182780946464962910563938874378864873371191810458257836478499770124766328898359557354325131853239584630755574091142624174743493475534286465766116677973966688202912073791438537195882498081268678383745597317461360853795345242215865932019280908782973084313928444032812315586110369768013573042161687476096758713483120254785893207671691324484262361314125087802080002616831510273418279777047846358681701643650241536913982812648102130927612448963599287051149649754199093422215668325720808213331861168115536158365469840467089756029009505376164758477284218896796462449451607653534081989013854424879849599533191017233660213945039973628075013783761530712776192684903435262520001588853514733161170210396817592151090778801939317811419454525722386554146106289218796022383897147608850627686296714667469756291123408243920816015378088989396451826324367161676217916890977991190375403127462228998800519514282012187361745992642956581746628302955570299024324153181617210465832036786906117260158783520751516284225540265170483304226143974286933061690897968482590125458327168226458066526769958652682272807075781391858178889652208164348344825993266043367660176999612831860788386150279465955131156552036093988180612138558600301435694527224206344631797460594682573103790084024432438465657245014402821885252470935190620929023136493273497565513958720559654228749774011413346962715422845862377387538230483865688976461927383814900140767310446640259899490217659043399018860185665264850617997023561938970178600408118897299183110211712298459016419210688843871218556461249607987229085192968193723886426148396573822911231250241866493531439701374285319266498753372189406942814341185201580141233448280150513996942901534830776445690990731524332782882698646027898643211390835062170950025973898635542771967428222487575867657523442202075736305694988250879689281627538488633969099598262809561214509948717012445164612603790293091208890869420285106401821543994571568059418727489980942547421735824010636774045957417851608292301353580818400969963725242305608559037006242712434169090041536901059339838357779394109700277534720

>>> time_func.bench(time_func.fac,100)
2.193450927734375e-05
9332621544394415268169923885626670049071596826438162146859296389521753229915608941463976156518286253697920827223758251185210916864

why the output so long,

Thanks,

 x = bench(fac, 1000)
> 0.00276589393616
 x = bench(fac, 1)
> 0.247038125992
 x = bench(fac, 3)
> 1.40305805206
 import gmpy
 x = bench(gmpy.fac, 3)
> 0.0243360996246
 x = bench(gmpy.fac, 10**6)
> 0.8047311306
 x.numdigits()
> 5565709
>
> http://pypi.python.org/pypi/gmpy
>
> ___
> 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] how to handle big numbers

2011-12-10 Thread Peter Otten
lina wrote:

> On Sat, Dec 10, 2011 at 6:09 PM, Peter Otten <__pete...@web.de> wrote:
>> surya k wrote:
>>
>>> Finding factorial of 8 or 9 isn't big. If I would like to find factorial
>>> of 32327, how can I ?
>>
>> gmpy is a library designed for working with large numbers. Compare:
>>
> import time
> def bench(f, *args):
>> ... start = time.time()
>> ... try:
>> ... return f(*args)
>> ... finally:
>> ... print time.time() - start
>> ...
> def fac(n):
>> ... f = 1
>> ... for i in xrange(1, n+1):
>> ... f *= i
>> ... return f
>> ...
> 
> sorry to interrupt, I tried your example,
> 
> $ cat time_func.py
> #!/usr/bin/python3
> 
> import time
> 
> def bench(f, *args):
> start = time.time()
> try:
> return f(*args)
> finally:
> print(time.time() - start)
> 
> def fac(n):
> f = 1
> for i in range(1,n+1):
> f *= i
> return f
> 
> on idle3
> 
 import time_func
 time_func.bench(time_func.fac,1000)
> 0.0015549659729003906
> 402...[snip many digits]...000
> 
> why the output so long,

bench() calls the function passed as its first argument with the arguments 
that follow, prints the time this function takes and returns the result of 
the function call. In the case of

bench(fac, 1000)

that result is fac(1000), or 1*2*3*4*...*997*998*999*1000 -- a number with
2568 digits. To avoid printing out these huge numbers I assigned them to x

> x = bench(fac, 1000)
>> 0.00276589393616

Therfore you only see the time in seconds which is printed rather than 
returned by bench().

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


Re: [Tutor] What style do you call Python programming?

2011-12-10 Thread Andreas Perstinger

On 2011-12-09 20:46, Alan Gauld wrote:

On 09/12/11 19:24, Alan Gauld wrote:


 In February 1991, after just over a year of development, I decided to
 post to USENET. The rest is in the Misc/HISTORY file.

 =

 Hopefully that clarifies rather than condfusing! :-)
 The HISTORY file gives more detail still.


Hmm, I just went to check the HISTORY file and I can't find it.
It used to come with the source tarball, but I haven't downloaded
the source for years!...


http://hg.python.org/cpython/file/e37a7dc8944e/Misc/HISTORY


Where has the online source code repository gone?


http://hg.python.org/cpython/branches

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


Re: [Tutor] Need Explanation...

2011-12-10 Thread Steven D'Aprano

Alan Gauld wrote:
[...]

Because app() returns the result of append().
But append() returns None, since it modifies the list in place.

This is one of the few features of Python I dislike. It would not have 
been difficult to make these modifier methods return the thing modified. 
This style would then allow chained methods.


Very true. It would be useful to be able to write:

a = [1, 2, 3]
a.append(4).insert(0, 0)

But...


We do it with strings:

"foobar is a string".rstrip('ing').upper()

because strings are immutable. But we could have done it with other 
sequence types too. Sadly we didn't and history/tradition leaves us with 
these counterintuitive modifiers that return None. It catches everybody 
out at some point...


...the alternative would also have caught out everybody at some point. 
Consider a hypothetical Python where mutator methods returned a result:


a = [1, 2, 3]
b = a.append(4)

Does this mean...?

* append 4 to a, then return a (and therefore a and b are
  alternative names for the same list)

* append 4 to a, then return a copy of a (and therefore a
  and b are different lists that merely have the same
  content)

* make a copy of a, then return the copy with 4 appended
  (and therefore a keeps its old value and b gets the new
  value)


Since each of the behaviours are reasonable and useful under some 
circumstances, regardless of which behaviour was choosen for append, it would 
catch out some people some time.


append() returning None is probably the least worst decision, since the error 
is obvious and so will likely be discovered as close as possible to the source 
of the error, rather than being subtle and so likely to cause hard-to-diagnose 
bugs.


A better alternative would be for Python to have procedures as well as 
functions/methods, so that:


b = a.append(4)

would raise an exception immediately. This would require the language to 
distinguish between "returning None" and "doesn't return anything", which I 
believe would be a good thing.



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


[Tutor] how to return an object generated during a python threading code

2011-12-10 Thread Massimo Di Stefano
Hi All,

i'm tring to learn how to use threads in python to save a list of object. i'm 
starting from this code :

#
import threading
import urllib
from tempfile import NamedTemporaryFile

singlelock = threading.Lock() 

class download(threading.Thread):
def __init__(self, sitecode, lista):
threading.Thread.__init__(self)
self.sitecode = sitecode
self.status = -1

def run(self):
url = 
"http://waterdata.usgs.gov/nwis/monthly?referred_module=sw&site_no=";
url += self.sitecode 
url += 
"&PARAmeter_cd=00060&partial_periods=on&format=rdb&submitted_form=parameter_selection_list"
tmp = NamedTemporaryFile(delete=False)
urllib.urlretrieve(url, tmp.name)
print "loaded Monthly data for sitecode : ",  self.sitecode 
lista.append(tmp.name)
print lista

sitecodelist = ["01046500", "01018500", "01010500", "01034500", "01059000", 
"01066000", "0110"]
lista = []


for k in sitecodelist:
get_data = download(k,lista)
get_data.start()

#

it just print out the list generated during the thread execution, while i'm 
tring to return it. 

Trying to read the documentation, i'm looking on how to use " threading.Lock() 
" and its methods "acquire() and release()" that seems to be the solution to my 
issue 

... but i'm really far to understand how to implement it in my example code.

thanks so much for any hints!___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to return an object generated during a python threading code

2011-12-10 Thread Emile van Sebille

On 12/10/2011 8:46 AM Massimo Di Stefano said...

Hi All,

i'm tring to learn how to use threads in python to save a list of
object. i'm starting from this code :



Moving lista into the instance seems to do it...

Emile




#


import threading
import urllib
from tempfile import NamedTemporaryFile


singlelock = threading.Lock()


class download(threading.Thread):
def __init__(self, sitecode, lista):
threading.Thread.__init__(self)
self.sitecode = sitecode
self.status = -1
self.lista = lista
def run(self):
url = 
"http://waterdata.usgs.gov/nwis/monthly?referred_module=sw&site_no=";

url += self.sitecode
url += 
"&PARAmeter_cd=00060&partial_periods=on&format=rdb&submitted_form=parameter_selection_list"

tmp = NamedTemporaryFile(delete=False)
urllib.urlretrieve(url, tmp.name)
print "loaded Monthly data for sitecode : ",  self.sitecode
self.lista.append(tmp.name)
print lista


sitecodelist = ["01046500", "01018500", "01010500", "01034500", 
"01059000", "01066000", "0110"]

lista = []


for k in sitecodelist:
get_data = download(k,lista)
get_data.start()




#

it just print out the list generated during the thread execution, while
i'm tring to return it.

Trying to read the documentation, i'm looking on how to use "
threading.Lock() " and its methods "acquire() and release()" that seems
to be the solution to my issue

... but i'm really far to understand how to implement it in my example code.

thanks so much for any hints!



___
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] Need Explanation...

2011-12-10 Thread Alan Gauld

On 10/12/11 16:46, Steven D'Aprano wrote:


...the alternative would also have caught out everybody at some point.
Consider a hypothetical Python where mutator methods returned a result:

a = [1, 2, 3]
b = a.append(4)

Does this mean...?

* append 4 to a, then return a (and therefore a and b are
alternative names for the same list)


This is what I'd expect.
I'm thinking about the Smalltalk model where  the default return
value from a method is self...

I'm particularly sensitive to this just now because I'm playing
with Squeak (again) and the elegance and consistency of
Smalltalk's mechanism  stands in stark contrast to the mixed
model in Python. (OTOH Smalltalk overall is a frustrating
experience for me, I would like to love it but never quite
get there... :-)


circumstances, regardless of which behaviour was choosen for append, it
would catch out some people some time.


Probably, although if returning 'self' were the default (which
of course only makes sense in a pure OO world like Smalltalk) people 
would get used to the semantics. Consistency is all in these kinds of 
situations. Sadly its one of the few areas where Python is slightly 
inconsistent.



A better alternative would be for Python to have procedures as well as
functions/methods, so that:

b = a.append(4)

would raise an exception immediately.


Better than silently returning None for sure.

--
Alan G
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] how to return an object generated during a python threading code

2011-12-10 Thread Steven D'Aprano

Massimo Di Stefano wrote:
[...]
it just print out the list generated during the thread execution, while i'm tring to return it. 


Since lista is a mutable global variable, you don't need to return it. Just 
look at lista once the threads have completed its work and you will find the 
content you expect.




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


Re: [Tutor] What style do you call Python programming?

2011-12-10 Thread Alan Gauld

On 10/12/11 16:29, Andreas Perstinger wrote:


Hmm, I just went to check the HISTORY file and I can't find it.
It used to come with the source tarball, but I haven't downloaded
the source for years!...


http://hg.python.org/cpython/file/e37a7dc8944e/Misc/HISTORY



Thanks Andreas. Now, how was I supposed to find that? Is it linked in 
any way from the main Python.org website? I couldn't find it (or the 
code) anywhere.


--
Alan G
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] What style do you call Python programming?

2011-12-10 Thread Andreas Perstinger

On 2011-12-10 18:12, Alan Gauld wrote:

On 10/12/11 16:29, Andreas Perstinger wrote:


 Hmm, I just went to check the HISTORY file and I can't find it.
 It used to come with the source tarball, but I haven't downloaded
 the source for years!...


 http://hg.python.org/cpython/file/e37a7dc8944e/Misc/HISTORY



Thanks Andreas. Now, how was I supposed to find that? Is it linked in
any way from the main Python.org website? I couldn't find it (or the
code) anywhere.



On www.python.org there is on the left sidebar a link to the "Core 
Development". This gets you to the "Developer's Guide" where you'll find 
in the QuickStart-Section the link to the Mercurial-Repository.


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


[Tutor] TypeError in class destructor

2011-12-10 Thread Mark Lybrand
I am working on the Files chapter of Dive into Python 3, and have
implemented the example script at the end of this message.  The first input
prints to the terminal as expected, the second value prints to the file as
expected.  Then the script tries to destroy in the class instance and bombs
with:

TypeError: __exit__() takes exactly 1 positional argument (4 given)
Exception ValueError: 'I/O operation on closed file.' in <_io.TextIOWrapper
name
='out.log' mode='w' encoding='utf-8'> ignored

and the final input is, naturally, never printed.

Is the example wrong, or is this something to do with how Windows handles
stdout that is causing this not to work as designed?  I am using Python 3.2
on Windows Vista Home Premium.

import sys

class RedirectStdoutTo:
  def __init__(self, out_new):
self.out_new = out_new

  def __enter__(self):
self.out_old = sys.stdout
sys.stdout = self.out_new

  def __exit__(self):
sys.stdout = self.out_old


print('A')
with open('out.log', mode='w', encoding='utf-8') as a_file,
RedirectStdoutTo(a_file):
  print('B')
print('C')



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


Re: [Tutor] TypeError in class destructor

2011-12-10 Thread Walter Prins
Hi Mark,

On 10 December 2011 17:54, Mark Lybrand  wrote:
>
> I am working on the Files chapter of Dive into Python 3, and have implemented 
> the example script at the end of this message.  The first input prints to the 
> terminal as expected, the second value prints to the file as expected.  Then 
> the script tries to destroy in the class instance and bombs with:
>
> TypeError: __exit__() takes exactly 1 positional argument (4 given)
> Exception ValueError: 'I/O operation on closed file.' in <_io.TextIOWrapper 
> name
> ='out.log' mode='w' encoding='utf-8'> ignored
>
> and the final input is, naturally, never printed.
>
> Is the example wrong, or is this something to do with how Windows handles 
> stdout that is causing this not to work as designed?  I am using Python 3.2 
> on Windows Vista Home Premium.


It seems the example may be wrong -- the __exit__ method, as stated by
the error, is being given 4 parameters whereas the one defined in the
code only expects one.  I've looked an this is correct on Python 3.2
that I have on Windows as well.   Perhaps the implementation of
__exit__ has been changed somewhere and had the paramters added and
the book is just out of date?  In any case, changing the def __exit__
line to:

def __exit__(self, type, value, traceback):

... will fix the problem.

Cheers

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


Re: [Tutor] TypeError in class destructor

2011-12-10 Thread Andreas Perstinger

On 2011-12-10 20:22, Walter Prins wrote:

Is the example wrong, or is this something to do with how Windows
handles stdout that is causing this not to work as designed?  I am
using Python 3.2 on Windows Vista Home Premium.


It seems the example may be wrong -- the __exit__ method, as stated
by the error, is being given 4 parameters whereas the one defined in
the code only expects one.  I've looked an this is correct on Python
3.2 that I have on Windows as well.   Perhaps the implementation of
__exit__ has been changed somewhere and had the paramters added and
the book is just out of date?  In any case, changing the def
__exit__ line to:

def __exit__(self, type, value, traceback):

... will fix the problem.


Perhaps a typo in the book, because the online-version 
(http://www.diveintopython3.net/examples/stdout.py) works:


def __exit__(self, *args):
sys.stdout = self.out_old

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


Re: [Tutor] Need Explanation...

2011-12-10 Thread Max gmail

On Dec 10, 2011, at 12:04 PM, Alan Gauld wrote:

> On 10/12/11 16:46, Steven D'Aprano wrote:
> 
>> ...the alternative would also have caught out everybody at some point.
>> Consider a hypothetical Python where mutator methods returned a result:
>> 
>> a = [1, 2, 3]
>> b = a.append(4)
>> 
>> Does this mean...?
>> 
>> * append 4 to a, then return a (and therefore a and b are
>> alternative names for the same list)
> 
> This is what I'd expect.
> I'm thinking about the Smalltalk model where  the default return
> value from a method is self...
> 
> I'm particularly sensitive to this just now because I'm playing
> with Squeak (again) and the elegance and consistency of
> Smalltalk's mechanism  stands in stark contrast to the mixed
> model in Python. (OTOH Smalltalk overall is a frustrating
> experience for me, I would like to love it but never quite
> get there... :-)

Personally, I found that returning a copy of a seemed more logical- after all, 
if you return 4 to b, then adding 2 to b wouldn't make 4 equal 6.
> 
>> circumstances, regardless of which behaviour was choosen for append, it
>> would catch out some people some time.
> 
> Probably, although if returning 'self' were the default (which
> of course only makes sense in a pure OO world like Smalltalk) people would 
> get used to the semantics. Consistency is all in these kinds of situations. 
> Sadly its one of the few areas where Python is slightly inconsistent.
> 
>> A better alternative would be for Python to have procedures as well as
>> functions/methods, so that:
>> 
>> b = a.append(4)
>> 
>> would raise an exception immediately.
> 
> Better than silently returning None for sure.

Of course, by silently returning None, you can just go on with your daily life 
and be happily ignorant of any return value; in other more strongly typed 
languages, the void functions/methods tend to alter other variables and 
situations more than, for example, ints.  I feel myself that it is no more 
trouble to simply type 'a.append(4); b = a'.
> 
> -- 
> Alan G
> 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

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


Re: [Tutor] TypeError in class destructor

2011-12-10 Thread Mark Lybrand
def __exit__(self, *args):


Thanks guys. This is the solution I implemented and it works great.

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


Re: [Tutor] Need Explanation...

2011-12-10 Thread ALAN GAULD

>> Smalltalk's mechanism  stands in stark contrast to the mixed
>> model in Python. (OTOH Smalltalk overall is a frustrating
>> experience for me, I would like to love it but never quite
>> get there... :-)
>
>Personally, I found that returning a copy of a seemed more logical- after all, 
>if you return 4 to b, then adding 2 to b wouldn't make 4 equal 6.
>
>But the object is modified in both cases. 
But returning a copy loses the biggest advantage of returning self, 
namely, that you can chain methods.

As it is you have to do:

a.append(42)
a.sort()
b = a[3]

With self returns you can write

b = a.append(42).sort().[3]

The best we can do in Python is two lines:

a.append(42)
b = sorted(a)[3]

Being able to chain methods is a very powerful idiom.
Just look at how often people do it with strings.

aList = myFile.read().strip().split()

is a particularly common pattern that relies on string modifier 
operations returning the modified string.

> Better than silently returning None for sure.
>
>Of course, by silently returning None, you can just go on with your daily life 
>and be happily ignorant of any return value; As you can with any default 
>return value.
After all printf() in C returns the number of characters printed, but 
when was the last time you saw code that did anything with the 
return value from printf()?
Similarly with None, most Pythonistas just ignore it. The same applies to self, 
you would just ignore it if you didn't need it.


in other more strongly typed languages, the void functions/methods tend 
>to alter other variables and situations more than, for example, ints.  Sorry I 
>don't get that bit. a void function doesn't alter anything. 
At least no more than an int function can.


I feel myself that it is no more trouble to simply type 'a.append(4); b = 
a'.But that's not chaining methods that's setting two variables to refer to the 
same object.
Not particularly useful most of the time.

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


Re: [Tutor] What style do you call Python programming?

2011-12-10 Thread Lie Ryan

On 12/10/2011 03:52 AM, Sarma Tangirala wrote:


Well, what I meant was the way you write things like list comprehension.
I agree, that comment gave a completely incorrect picture. Sorry about that.


list comprehension originated from Haskell, which is a language with a 
very strong functional paradigm. Functions/procedures comes from 
procedural paradigm. for-loop, while-loop, and if-conditional comes from 
structured programming. Classes comes from object-oriented programming.


Although I've said such, the terms are not actually that clear cut. Most 
object-oriented languages also have a for-loop, while-loop, and 
if-conditional of a structured programming. And not all object-oriented 
languages have classes (e.g. javascript).


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


Re: [Tutor] Need Explanation...

2011-12-10 Thread Lie Ryan

On 12/11/2011 04:04 AM, Alan Gauld wrote:

On 10/12/11 16:46, Steven D'Aprano wrote:

circumstances, regardless of which behaviour was choosen for append, it
would catch out some people some time.


Probably, although if returning 'self' were the default (which
of course only makes sense in a pure OO world like Smalltalk) people
would get used to the semantics. Consistency is all in these kinds of
situations. Sadly its one of the few areas where Python is slightly
inconsistent.


If returning 'self' is the default expected behavior, it would cause 
inconsistencies with respect to immutable types. For example, `5 
.__add__(2)`, one could expect it to return 5 instead of 7.


While I liked the attraction of "fluent interface" of being able to 
easily chain function calls, it is inherently more inconsistent than 
what Python are doing.


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


Re: [Tutor] What style do you call Python programming?

2011-12-10 Thread Steven D'Aprano

Lie Ryan wrote:

Although I've said such, the terms are not actually that clear cut. Most 
object-oriented languages also have a for-loop, while-loop, and 
if-conditional of a structured programming. And not all object-oriented 
languages have classes (e.g. javascript).


There is a lot of overlap in programming paradigms.

Javascript is an example of prototype-based object-oriented programming. Other 
examples include Lua and Flash.


http://c2.com/cgi/wiki?PrototypeBasedProgramming
http://en.wikipedia.org/wiki/Prototype-based_programming

Class-based object-oriented programming and prototype-based ("classless") 
object-oriented programming are both sub-types of OOP. There's no reason you 
can't have both: Javascript has now introduced classes, and Python can support 
prototypes:


http://lists.canonical.org/pipermail/kragen-hacks/2000-September/000264.html


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