Re: [Tutor] plotting pixels

2010-09-19 Thread Bill Allen
On Sun, Sep 19, 2010 at 2:40 AM, Lie Ryan  wrote:

>
> More slowly and takes huge amount of memory. A single Tk canvas object
> takes at least 14 words (= 114 bytes in 64-bit OS = 56 bytes in 32-bit
> OS) + the amount of data is needed to store the `kind of object`. That's
> much larger than the ideal 3 bytes per pixel (or 4 bytes with alpha).
>
> Tkinter's Canvas intentionally doesn't provide create_pixel() because
> unlike most other Canvas implementations, Tkinter's Canvas holds a
> stateful canvas objects instead of a simple drawing surface. Providing a
> create_pixel() will be too tempting for abuse, which would make the
> canvas unbearably slow and memory consuming. In short, Canvas is not
> designed for pixel drawing.
>
> > Digging a little deeper it seems the idiomatic way to do this in Python
> > is to use PIL the Python Imaging Library to create a GIF or bitmap
> > image and then insert that into Tkinters cancvas as an image object.
> >
> > The Pil ImageDraw class has a point() ethod
>
> If you need to plot pixels, do use pygame, PIL, or at least the
> PhotoImage trick.
>
> Thanks for the feedback!   That does make a lot a sense as to why a
pixel_plot() type function would not be directly implemented in Canvas.  As
this is still largely a learning exercise for me, I may try more than one
approach.  I think first I will try the PhotoImage approach, which might be
the most efficient method.  However, I will definitely give Pygame a try.  I
have seen several programs that were written in Pygame and I am really
impressed!  It is obviously designed to task.

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


Re: [Tutor] plotting pixels

2010-09-19 Thread Steven D'Aprano
Hello Ken,

On Sun, 19 Sep 2010 04:18:06 am Ken Oliver wrote:
> 
> body{font-size:10pt;font-family:arial,sans-serif;background-co
>lor:#ff;color:black;}p{margin:0px;}
> 
> 
> http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What are "singletons" good for?

2010-09-19 Thread Steven D'Aprano
On Mon, 20 Sep 2010 02:09:37 am Alan Gauld wrote:
> "Steven D'Aprano"  wrote
>
> > < much sense about singleton v global>
> >
> > and think this makes their code "better". (I blame the Go4 for
> > making a
> > religion out of design patterns which exist only to work around
> > Java's
> > limitations.)
>
> In fact the original design patterns were based around Smalltalk's
> limitations since most of the Go4 were/are Smalltalk hackers. And
> thus the Singleton - because Smalltalk has no concept of global
> variables.
>
> The book was registered in 1994 and released in 1995, a full year
> before the first Java JDK was made publicly available.

Fair enough, I stand corrected. Thank you.

Nevertheless, the design pattern book has been picked up by the Java 
crowd and elevated almost to the status of a religion, rather than a 
set of useful tools. Especially the Singleton pattern, probably because 
it's the only one which most programmers can understand *wink*



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


Re: [Tutor] FW: Can this be done easly

2010-09-19 Thread Roelof Wobben




> From: andreeng...@gmail.com
> Date: Sun, 19 Sep 2010 20:54:01 +0200
> Subject: Re: [Tutor] FW: Can this be done easly
> To: rwob...@hotmail.com
> CC: tutor@python.org
>
> On Sun, Sep 19, 2010 at 8:33 PM, Roelof Wobben wrote:
>
>> Hello,
>>
>> I changed the programm to this :
>>
>> import unittest
>> class Point:
>> def __init__(self, x=0, y=0):
>> self.x = x
>> self.y = y
>>
>> class Rectangle(object):
>> def __init__(self, base_point, width=0, length=0):
>> self.base_point = base_point
>> self.width = width
>> self.length = length
>>
>> def moverect(roelof, dx, dy):
>> roelof.base_point.y += dy
>> roelof.base_point.x +=dx
>> return roelof
>>
>> r = Rectangle(Point(3, 4), 20, 30)
>> moverect(r, 10, 11)
>> assert r.base_point.x == 13, "wrong x position %d" % r.base_point.x
>> assert r.base_point.y == 15, "wrong y position %d" % r.base_point.y
>>
>> But no output at all
>
> Which output had you expected, and why?
>
>
> --
> André Engels, andreeng...@gmail.com
 
Hello, 
 
Oke, I see it now. There is only output when it's not right.
 
Roelof

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


Re: [Tutor] FW: Can this be done easly

2010-09-19 Thread Andre Engels
On Sun, Sep 19, 2010 at 8:33 PM, Roelof Wobben  wrote:

> Hello,
>
> I changed the programm to this :
>
> import unittest
> class Point:
>    def __init__(self, x=0, y=0):
>        self.x = x
>        self.y = y
>
> class Rectangle(object):
>    def __init__(self, base_point, width=0, length=0):
>        self.base_point = base_point
>        self.width = width
>        self.length = length
>
> def moverect(roelof, dx, dy):
>    roelof.base_point.y += dy
>    roelof.base_point.x +=dx
>    return roelof
>
> r = Rectangle(Point(3, 4), 20, 30)
> moverect(r, 10, 11)
> assert r.base_point.x == 13, "wrong x position %d" % r.base_point.x
> assert r.base_point.y == 15, "wrong y position %d" % r.base_point.y
>
> But no output at all

Which output had you expected, and why?


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] FW: Can this be done easly

2010-09-19 Thread Roelof Wobben




> To: tutor@python.org
> From: __pete...@web.de
> Date: Sun, 19 Sep 2010 20:07:05 +0200
> Subject: Re: [Tutor] FW: Can this be done easly
>
> Roelof Wobben wrote:
>
>> For this exercise :
>>
>> 3.Write a function named move_rect that takes a Rectangle and two
>> parameters named dx and dy. It should change the location of the rectangle
>> by adding dx to the x coordinate of corner and adding dy to the y
>> coordinate of corner.
>>
>> Is this one of the possible solutions :
>>
>> class Point:
>> def __init__(self, x=0, y=0):
>> self.x = x
>> self.y = y
>>
>> class Rectangle(object):
>> def __init__(self, base_point, width=0, length=0):
>> self.base_point = base_point
>> self.width = width
>> self.length = length
>>
>> def moverect(rectangle, dx, dy):
>> rechthoek.base_point.y += dy
>> rechthoek.base_point.x +=dx
>> return rechthoek
>>
>> punt = Point(3,4)
>> rechthoek = Rectangle (punt,20,30)
>> test = moverect (Rectangle, 4,3)
>> print rechthoek.base_point.x
>
> At first glance I'd say so. At second glance I see that you pass the class
> and not an instance to the moverect() routine. Your program only seems to
> work because you are not using the parameter rectangle but the global
> rechthoek variable and as soon as you are trying to move rectangles with a
> different variable name everything will break.
> If I were to run your program I might even find more errors or problematic
> behaviours.
>
> In the long run it's not a sustainable model to verify the correctness of
> your programs by asking someone on the internet who is just as likely to be
> wrong as you or might even fool you.
>
> Instead add some tests. For example, you could precalculate the expected
> position and then check if the new position meets your expectation:
>
> r = Rectangle(Point(3, 4), 20, 30)
>
> moverect(r, 10, 11)
>
> if r.base_point.x == 13 and r.base_point.y == 15:
> print "looks good"
> else:
> print "needs work"
>
> Because tests are needed very often there are libraries accompanying the
> interpreter (unittest, doctest) to formalize them and for simple runtime
> checks there is the assert statement. Instead of the if...else you could
> write
>
> assert r.base_point.x == 13, "wrong x position %d" % r.base_point.x
> assert r.base_point.y == 15, "wrong y position %d" % r.base_point.y
>
> Peter
>
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
 
Hello, 
 
I changed the programm to this :
 
import unittest
class Point:
def __init__(self, x=0, y=0): 
self.x = x
self.y = y
 
class Rectangle(object):
def __init__(self, base_point, width=0, length=0):
self.base_point = base_point
self.width = width
self.length = length

def moverect(roelof, dx, dy):
roelof.base_point.y += dy
roelof.base_point.x +=dx
return roelof

r = Rectangle(Point(3, 4), 20, 30) 
moverect(r, 10, 11)
assert r.base_point.x == 13, "wrong x position %d" % r.base_point.x
assert r.base_point.y == 15, "wrong y position %d" % r.base_point.y
 
But no output at all
 
Roelof

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


Re: [Tutor] FW: Can this be done easly

2010-09-19 Thread Andre Engels
On Sun, Sep 19, 2010 at 7:02 PM, Roelof Wobben  wrote:
>
>
>
> 
>> From: rwob...@hotmail.com
>> To: __pete...@web.de
>> Subject: RE: [Tutor] Can this be done easly
>> Date: Sun, 19 Sep 2010 17:01:22 +
>>
>>
>>
>>
>> 
>>> To: tutor@python.org
>>> From: __pete...@web.de
>>> Date: Sun, 19 Sep 2010 18:27:54 +0200
>>> Subject: Re: [Tutor] Can this be done easly
>>>
>>> Roelof Wobben wrote:
>>>
> Hint: why does this work:
>
>> def __init__(self, x=0, y=0):
>
> ...while this doesnt:
>
>> def _init_(self, base_point, width=0, length=0):
>
> Peter
>>>
 Maybe because base_point has no value ?
>>>
>>> No. One __init__ has two underscores (correct) on each side, the other
>>> _init_ only one (wrong).
>>>
>>> ___
>>> Tutor maillist - Tutor@python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
> Hello,
>
> Everybody thanks.
>
> For this exercise :
>
> 3.Write a function named move_rect that takes a Rectangle and two parameters 
> named dx and dy. It should change the location of the rectangle by adding dx 
> to the x coordinate of corner and adding dy to the y coordinate of corner.
>
> Is this one of the possible solutions :
>
>
> class Point:
>    def __init__(self, x=0, y=0):
>        self.x = x
>        self.y = y
>
> class Rectangle(object):
>    def __init__(self, base_point, width=0, length=0):
>        self.base_point = base_point
>        self.width = width
>        self.length = length
>
> def moverect(rectangle, dx, dy):
>    rechthoek.base_point.y += dy
>    rechthoek.base_point.x +=dx
>    return rechthoek
>
> punt = Point(3,4)
> rechthoek = Rectangle (punt,20,30)
> test = moverect (Rectangle, 4,3)
> print rechthoek.base_point.x


This test happens to work, but your program is incorrect.

In moverect, you should work with the local variable (rectangle), not
with the global one (rechthoek), because it should be possible to call
it for any Rectangle, not just with the Rectangle that happens to be
called rechthoek. Then, when you call it, you should specify the
Rectangle that you call it for, so

test = moverect (Rectangle, 4, 3)

should be

test = moverect(rechthoek, 4, 3)

Furthermore, you do not use test (which will be null anyway), so you
can shorten this to

moverect(rechthoek, 4, 3)

-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] FW: Can this be done easly

2010-09-19 Thread Peter Otten
Roelof Wobben wrote:

> For this exercise :
> 
> 3.Write a function named move_rect that takes a Rectangle and two
> parameters named dx and dy. It should change the location of the rectangle
> by adding dx to the x coordinate of corner and adding dy to the y
> coordinate of corner.
> 
> Is this one of the possible solutions :
> 
> class Point:
> def __init__(self, x=0, y=0):
> self.x = x
> self.y = y
>  
> class Rectangle(object):
> def __init__(self, base_point, width=0, length=0):
> self.base_point = base_point
> self.width = width
> self.length = length
> 
> def moverect(rectangle, dx, dy):
> rechthoek.base_point.y += dy
> rechthoek.base_point.x +=dx
> return rechthoek
> 
> punt = Point(3,4)
> rechthoek = Rectangle (punt,20,30)
> test = moverect (Rectangle, 4,3)
> print rechthoek.base_point.x

At first glance I'd say so. At second glance I see that you pass the class 
and not an instance to the moverect() routine. Your program only seems to 
work because you are not using the parameter rectangle but the global 
rechthoek variable and as soon as you are trying to move rectangles with a 
different variable name everything will break.
If I were to run your program I might even find more errors or problematic 
behaviours.

In the long run it's not a sustainable model to verify the correctness of 
your programs by asking someone on the internet who is just as likely to be 
wrong as you or might even fool you.

Instead add some tests. For example, you could precalculate the expected 
position and then check if the new position meets your expectation:

r = Rectangle(Point(3, 4), 20, 30)

moverect(r, 10, 11)

if r.base_point.x == 13 and r.base_point.y == 15:
print "looks good"
else:
print "needs work"

Because tests are needed very often there are libraries accompanying the 
interpreter (unittest, doctest) to formalize them and for simple runtime 
checks there is the assert statement. Instead of the if...else you could 
write

assert r.base_point.x == 13, "wrong x position %d" % r.base_point.x
assert r.base_point.y == 15, "wrong y position %d" % r.base_point.y

Peter

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


[Tutor] FW: Can this be done easly

2010-09-19 Thread Roelof Wobben




> From: rwob...@hotmail.com
> To: __pete...@web.de
> Subject: RE: [Tutor] Can this be done easly
> Date: Sun, 19 Sep 2010 17:01:22 +
>
>
>
>
> 
>> To: tutor@python.org
>> From: __pete...@web.de
>> Date: Sun, 19 Sep 2010 18:27:54 +0200
>> Subject: Re: [Tutor] Can this be done easly
>>
>> Roelof Wobben wrote:
>>
 Hint: why does this work:

> def __init__(self, x=0, y=0):

 ...while this doesnt:

> def _init_(self, base_point, width=0, length=0):

 Peter
>>
>>> Maybe because base_point has no value ?
>>
>> No. One __init__ has two underscores (correct) on each side, the other
>> _init_ only one (wrong).
>>
>> ___
>> Tutor maillist - Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
>

Hello,

Everybody thanks.

For this exercise :

3.Write a function named move_rect that takes a Rectangle and two parameters 
named dx and dy. It should change the location of the rectangle by adding dx to 
the x coordinate of corner and adding dy to the y coordinate of corner.

Is this one of the possible solutions :


class Point:
def __init__(self, x=0, y=0): 
self.x = x
self.y = y
 
class Rectangle(object):
def __init__(self, base_point, width=0, length=0):
self.base_point = base_point
self.width = width
self.length = length

def moverect(rectangle, dx, dy):
rechthoek.base_point.y += dy
rechthoek.base_point.x +=dx
return rechthoek

punt = Point(3,4)
rechthoek = Rectangle (punt,20,30)
test = moverect (Rectangle, 4,3) 
print rechthoek.base_point.x

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


Re: [Tutor] Can this be done easly

2010-09-19 Thread Peter Otten
Roelof Wobben wrote:

>> Hint: why does this work:
>>
>>> def __init__(self, x=0, y=0):
>>
>> ...while this doesnt:
>>
>>> def _init_(self, base_point, width=0, length=0):
>>
>> Peter

> Maybe because base_point has no value ?

No. One __init__ has two underscores (correct) on each side, the other 
_init_ only one (wrong).

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


Re: [Tutor] Can this be done easly

2010-09-19 Thread Alan Gauld


"Roelof Wobben"  wrote


When I change everything to this :

class Rectangle(object):
   def _init_(self, base_point, width=0, length=0):
   self.base_point = base_point
   self.width = width
   self.length = length

punt = Point(3,4)
rechthoek = Rectangle (punt,20,30)

I get this message :

Traceback (most recent call last):
 File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 13, 
in 

   rechthoek = Rectangle (punt,20,30)
TypeError: object.__new__() takes no parameters


Very odd, but are you using IDLE or a similar IDE?
Have you remembered to reload the module? Just a thought...

Alan G.


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


Re: [Tutor] What are "singletons" good for?

2010-09-19 Thread Alan Gauld



"Steven D'Aprano"  wrote



< much sense about singleton v global>


and think this makes their code "better". (I blame the Go4 for 
making a
religion out of design patterns which exist only to work around 
Java's

limitations.)


In fact the original design patterns were based around Smalltalk's
limitations since most of the Go4 were/are Smalltalk hackers. And
thus the Singleton - because Smalltalk has no concept of global
variables.

The book was registered in 1994 and released in 1995, a full year
before the first Java JDK was made publicly available.

Alan G. 



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


Re: [Tutor] Can this be done easly

2010-09-19 Thread Roelof Wobben




> To: tutor@python.org
> From: __pete...@web.de
> Date: Sun, 19 Sep 2010 18:04:25 +0200
> Subject: Re: [Tutor] Can this be done easly
>
> Roelof Wobben wrote:
>
>> When I change everything to this :
>
>> I get this message :
>>
>> Traceback (most recent call last):
>> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 13, in
>> 
>> rechthoek = Rectangle (punt,20,30)
>> TypeError: object.__new__() takes no parameters
>
> Hint: why does this work:
>
>> def __init__(self, x=0, y=0):
>
> ...while this doesnt:
>
>> def _init_(self, base_point, width=0, length=0):
>
> Peter
>
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

Hoi, 
 
Maybe because base_point has no value ?

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


Re: [Tutor] Can this be done easly

2010-09-19 Thread Peter Otten
Roelof Wobben wrote:

> When I change everything to this :

> I get this message :
>  
> Traceback (most recent call last):
>   File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 13, in
>   
> rechthoek = Rectangle (punt,20,30)
> TypeError: object.__new__() takes no parameters

Hint: why does this work:
  
>  def __init__(self, x=0, y=0):

...while this doesnt:

> def _init_(self, base_point, width=0, length=0):

Peter

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


Re: [Tutor] Can this be done easly

2010-09-19 Thread Roelof Wobben




> Date: Sun, 19 Sep 2010 14:19:46 +0200
> From: knack...@googlemail.com
> To: tutor@python.org
> Subject: Re: [Tutor] Can this be done easly
>
> Am 19.09.2010 10:49, schrieb Roelof Wobben:
>>
>>
>> Hello,
>>
>> I have this programm :
>>
>> class Point:
>> def __init__(self, x=0, y=0):
>> self.x = x
>> self.y = y
>>
>> class Rectangle(Point):
>> def _init_(self, width=0, length=0):
>> self.width = width
>> self.length = length
> You're inheriting the Point Class, but you don't initialise it.
> For some detailled description of inheritance in Python I rather suggest
> to check out some tutorials instead of trying to explain it. Also,
> others on this list can do this probably better. Here's one reference:
> http://diveintopython.org/object_oriented_framework/index.html
>
> But now some remarks regarding your problem:
>
> First, I would not consider a Rectangle as a special Point. It's not a
> relation like a Sportscar is a Car (is-a-relationship). It's more a
> relation a Rectangle has 4 Points (has-a-relationship), or 1 Point and a
> width and length. So, it's probably better to express your Rectangle
> class like this:
>
> class Rectangle(object):
> def __init__(self, base_point, width=0, length=0):
> self.base_point = base_point
> self.width = width
> self.length = length
>
> then you go (with German names ;-)):
>
> punkt = Point(3,4)
> rechteck = Rectangle(punkt,20,30)
>
> In your Rectangle class, the __init__ method takes only two arguments
> (not counting the instance: self), but you're passing three arguments.
>
> At the beginning, the error messages are a bit confusing, because they
> count the instance as one of the arguments. So it tells you, that you
> have given 4 arguments, but you might wonder "Hey, I gave you 3".
>
> HTH,
>
> Jan
>
>>
>> punt = Point(3,4)
>> rechthoek = Rectangle (punt,20,30)
>>
>> Now I wonder how I can change this to rechthoek = rectangle (punt,20,20)
>> This one gives as error message :
>>
>> Traceback (most recent call last):
>> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 12, in
>> rechthoek = Rectangle (punt,20,30)
>> TypeError: __init__() takes at most 3 arguments (4 given)
>>
>> Roelof
>>
>> ___
>> 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

Hello, 
 
When I change everything to this :
 
class Point:
 def __init__(self, x=0, y=0): 
 self.x = x
 self.y = y
 
class Rectangle(object):
def _init_(self, base_point, width=0, length=0):
self.base_point = base_point
self.width = width
self.length = length

punt = Point(3,4)
rechthoek = Rectangle (punt,20,30)
 
I get this message :
 
Traceback (most recent call last):
  File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 13, in 
rechthoek = Rectangle (punt,20,30)
TypeError: object.__new__() takes no parameters
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What are "singletons" good for?

2010-09-19 Thread Steven D'Aprano
On Sun, 19 Sep 2010 02:50:42 am Knacktus wrote:
> Hey all,
>
> the usual explanation for the usage of a Singleton goes like this:
>
> "Use a singleton if you want to make sure, that only one instance of
> a class exists."
>
> But now I ask myself: Why should I call the constructor of a class
> more than once if I only want one instance?

Why does int("spam") raise an exception that you can catch, instead of 
dumping core and crashing the machine? After all, if you don't want to 
crash the machine, just make sure you never call int() with something 
that isn't an integer.

Right?

No. We all know that no matter how much you intend to only call int() on 
strings which actually do represent integers, bugs do happen, so we 
have the language protect us from our mistakes. Likewise, you might 
intend to only call the constructor of a class once, and in a 200 line 
script you might even be confident of that fact, but in a 200,000 line 
program how confident will you be?

You might say "do a search of the source code, and if you see the 
constructor called twice, you know it's wrong" but of course there 
might be a legitimate reason to call the constructor from different 
places in the code, so long as only one of them is actually executed.


> After all, I decide in my code when to create an instance or when to
> pass an existing instance around.

Why should you have to decide? Why bother to track that yourself, when 
the class could track it for you?

Depending on your needs or philosophy, one tactic is to have the class 
explicitly tell you when you're trying to initialise a second instance, 
by raising an exception. Python does that with some singletons:

>>> type(None)()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: cannot create 'NoneType' instances

And the same for NotImplemented. Personally, I don't understand that 
tactic. I prefer the tactic used by the pair of singletons True and 
False:

>>> bool() is False
True

No matter how many times you call bool(), it will always return one of 
the two singleton instances True or False. Imported modules are the 
same -- every time you import a module, Python gives you the same 
module instance. So if you need singleton behaviour, a module gives you 
that for free.


> Example in pseudocode:
>
> class Session(object):
>  """Hold a dictionary of ident_to_data_objects"""
>
>  def __init__(self, ident_to_data):
>  self.ident_to_data = ident_to_data
>
> Now, that would be a typical "singleton" use case. I want one 
> instance of this class application-wide. For example in a View class:
>
> class View(object):
>  """Create fancy views"""
>
>  def __init__(self, session):
>  self.session = session

If there's only ever one session, can't possibly be a second, then why 
make it an attribute of the view instance? You might have 30 views, so 
why pretend that they could have 30 different sessions?

Better to inject the session into the View class itself, as a class 
attribute:

class View(object):
"""Create fancy views"""
session = None
def __init__(self, session=None):
if self.session is None:
self.__class__.session = session
elif session is not None:
raise ValueError('cannot use two sessions')

But why pretend that you might have multiple View-like classes, with 
different sessions? Since you have the invariant that there can only 
ever be one session, you can't allow this:

class MyView(View):
session = another_session()

Since that's prohibited, don't pretend it's allowed. You might as well 
make session a global variable, and stop pretending to be more virtuous 
than you actually are.

And that's the problem -- singletons are often (not always, but often) 
just a sop to the idea that global variables are bad. They are, but 
disguising them as a singleton object doesn't make them less bad. It's 
better to think really hard about *why* you want only one instance of a 
class, whether it's really necessary, and if so, whether an alternative 
such as the Borg pattern would be better.

http://code.activestate.com/recipes/66531/


> In my code I use these classes like this:
>
> class MainApp(object):
>  """Do some stuff with the data_objects"""
>
>  def __init__(self):
>  self.session = Session()
>  self.view = View(self.session)

Since every MainApp instance creates it's own independent session 
object, no, there's no singleton. It's not a singleton if you merely 
*happen* to only create one instance. It's only a singleton if you 
*can* only create one instance (or at least, one instance with each 
specific value).

E.g. you can create multiple lists with the same value but different 
identity:

>>> a = [1, 2]
>>> b = [1, 2]
>>> a is b
False

so lists are not singletons. But you can't create multiple module 
objects with the same value and different identity:

>>> import math
>>> import math as another_math
>>> math is another_math
True

So

Re: [Tutor] Can this be done easly

2010-09-19 Thread Knacktus

Am 19.09.2010 10:49, schrieb Roelof Wobben:



Hello,

I have this programm :

class Point:
  def __init__(self, x=0, y=0):
  self.x = x
  self.y = y

class Rectangle(Point):
 def _init_(self, width=0, length=0):
 self.width = width
 self.length = length

You're inheriting the Point Class, but you don't initialise it.
For some detailled description of inheritance in Python I rather suggest 
to check out some tutorials instead of trying to explain it. Also, 
others on this list can do this probably better. Here's one reference:

http://diveintopython.org/object_oriented_framework/index.html

But now some remarks regarding your problem:

First, I would not consider a Rectangle as a special Point. It's not a 
relation like a Sportscar is a Car (is-a-relationship). It's more a 
relation a Rectangle has 4 Points (has-a-relationship), or 1 Point and a 
width and length. So, it's probably better to express your Rectangle 
class like this:


class Rectangle(object):
def __init__(self, base_point, width=0, length=0):
self.base_point = base_point
self.width = width
self.length = length

then you go (with German names ;-)):

punkt = Point(3,4)
rechteck = Rectangle(punkt,20,30)

In your Rectangle class, the __init__ method takes only two arguments 
(not counting the instance: self), but you're passing three arguments.


At the beginning, the error messages are a bit confusing, because they 
count the instance as one of the arguments. So it tells you, that you 
have given 4 arguments, but you might wonder "Hey, I gave you 3".


HTH,

Jan



punt = Point(3,4)
rechthoek = Rectangle (punt,20,30)

Now I wonder how I can change this to rechthoek = rectangle (punt,20,20)
This one gives as error message  :

Traceback (most recent call last):
   File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 12, in
 rechthoek = Rectangle (punt,20,30)
TypeError: __init__() takes at most 3 arguments (4 given)

Roelof

___
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] Remove a dictionary entry

2010-09-19 Thread Peter Otten
Steven D'Aprano wrote:

> On Sat, 18 Sep 2010 07:13:13 pm Peter Otten wrote:
> 
>> You should never iterate over a list or dictionary and add or remove
>> items to it at the same time. That is a recipe for disaster even if
>> it doesn't fail explicitly.
> 
> That's a bit strong. It's quite possible to modify lists safely and
> correctly while iterating over them with a little bit of care.

You're of course not the intended audience of my advice.
 
> You know, for decades people were able to program in languages like C
> and Pascal and assembly, often on machines with tiny amounts of memory.
> When your machine has 64K of memory, and the OS and application uses
> half of it, you don't have the luxury of making a copy of a 20K list
> before modifying it. Back when I was a lad, we learned how to modify
> lists in place. It isn't hard. *wink*

When you do that you are usually operating on an abstraction level below 
Python.
 
> Even in Python, it is sometimes necessary to modify lists and even dicts
> in place while iterating over them. 98% of the time, making a copy is
> faster, simpler and more efficient, but learning how to safely modify
> data structures in place is a valuable skill to have.

If you have a huge list that you can only modify in place you may have 
chosen the wrong data structure.

> But I'm just talking about general principles here. In most cases, stick
> to Peter's advice to make a copy.

Hey, I can agree with that ;)

Peter

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


Re: [Tutor] Remove a dictionary entry

2010-09-19 Thread Peter Otten
M. 427 wrote:

> Version 4 : (2 steps)
> 
> # step 1 : list keys of unwanted rows
> sck=[] # list of single children keys in dictionary
> for k in d.keys() :
> if len(d[k]) < 2 :
> sck.append(k)
> # step 2 : delete all d rows whose key is listed in sck
> while len(sck) > 0 :
> del d[sck.pop()]
> 
> This works.
> Is this the optimal pythonic way of doing it?

Ceterum censeo: the pythonic way is to make a copy:

d = dict((k, v) for k, v in d.iteritems() if len(v) > 1)

As an optimization, if the dictionary is huge and there are relatively few 
items to be deleted you may fall back to the 2-step approach. I would write 
it

delenda = [k for k, v in d.iteritems() if len(v) < 2]
for k in delenda:
del d[k]

Peter

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


[Tutor] Can this be done easly

2010-09-19 Thread Roelof Wobben


Hello, 
 
I have this programm :
 
class Point:
 def __init__(self, x=0, y=0): 
 self.x = x
 self.y = y
 
class Rectangle(Point):
def _init_(self, width=0, length=0):
self.width = width
self.length = length

punt = Point(3,4)
rechthoek = Rectangle (punt,20,30)
 
Now I wonder how I can change this to rechthoek = rectangle (punt,20,20)
This one gives as error message  : 
 
Traceback (most recent call last):
  File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 12, in 
rechthoek = Rectangle (punt,20,30)
TypeError: __init__() takes at most 3 arguments (4 given)
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] plotting pixels

2010-09-19 Thread Lie Ryan
On 09/19/10 09:39, ALAN GAULD wrote:
>> It appears that the Tk canvas widget does not support simply plotting
> a pixel. 
> 
> Correct, and I agree it seems odd, but in practice drawing either lines or
> ovals of one-pixel do the equivalent job - albeit a little more slowly.

More slowly and takes huge amount of memory. A single Tk canvas object
takes at least 14 words (= 114 bytes in 64-bit OS = 56 bytes in 32-bit
OS) + the amount of data is needed to store the `kind of object`. That's
much larger than the ideal 3 bytes per pixel (or 4 bytes with alpha).

Tkinter's Canvas intentionally doesn't provide create_pixel() because
unlike most other Canvas implementations, Tkinter's Canvas holds a
stateful canvas objects instead of a simple drawing surface. Providing a
create_pixel() will be too tempting for abuse, which would make the
canvas unbearably slow and memory consuming. In short, Canvas is not
designed for pixel drawing.

> Digging a little deeper it seems the idiomatic way to do this in Python
> is to use PIL the Python Imaging Library to create a GIF or bitmap
> image and then insert that into Tkinters cancvas as an image object.
> 
> The Pil ImageDraw class has a point() ethod

If you need to plot pixels, do use pygame, PIL, or at least the
PhotoImage trick.

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


Re: [Tutor] Remove a dictionary entry

2010-09-19 Thread M. 427
Version 4 : (2 steps)

# step 1 : list keys of unwanted rows
sck=[] # list of single children keys in dictionary
for k in d.keys() :
if len(d[k]) < 2 :
sck.append(k)
# step 2 : delete all d rows whose key is listed in sck
while len(sck) > 0 :
del d[sck.pop()]

This works.
Is this the optimal pythonic way of doing it?

Mr. 427


Le vendredi 17 septembre 2010 à 21:36 -0400, bob gailer a écrit :
> On 9/17/2010 9:21 PM, M. 427 wrote:
> > Thank you,
> > After reading the following documentations
> > http://docs.python.org/tutorial/datastructures.html#looping-techniques
> > http://docs.python.org/tutorial/controlflow.html#for-statements
> > I ended up with this :
> >
> > Version 3 :
> > for i,row in d[:].iteritems() : # BUG : TypeError: unhashable type
> >  if len(row)<  2 :
> >  del d[i]
> >
> > Still buggy... Any lead for this error message? Is a slice unhashable?
> > Am I looking in the right direction for this task?
> Where did you see [:] after a dict? [:] is slicing, and applies to a 
> sequence not a mapping.
> 
> Also note the warning "Using iteritems()  while adding or deleting 
> entries in the dictionary may raise a RuntimeError  or fail to iterate 
> over all entries."
> 
> You should get a list rather than an iterator of all key-value pairs 
> then iterate over that list.
> 


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