[Tutor] OT: just venting

2010-08-23 Thread Justin Ezequiel
when some IS/IT--Management guy asks about " Eval() or compile on fly with object"
and you try to talk him out of that bad idea,
he replies, "...it's much more easier, but that's not the way i want it"

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


Re: [Tutor] continuous running of a method

2010-08-23 Thread bob gailer

 On 8/23/2010 1:00 AM, Greg Bair wrote:
I have a method (I'll call it foo) that will either return None or an 
object depending on a random value generated.  What I want to happen 
is that if I call foo(), i.e, f = foo() and it returns None, to 
re-call it until it returns something else.  I would think this would 
be done with a while loop, but can't seem to get the details right.


Even though a while will work, you will have tied up the CPU until the 
loop terminates. This is never a good idea.


What is your higher level goal?

--
Bob Gailer
919-636-4239
Chapel Hill NC

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


[Tutor] Adding all numbers in a file or list

2010-08-23 Thread aug dawg
Is there a command or module that I can use to add all the items in a list?
Alternatively, is there one I can use to add all the numbers in a file?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Adding all numbers in a file or list

2010-08-23 Thread Sander Sweers
On 23 August 2010 17:13, aug dawg  wrote:
> Is there a command or module that I can use to add all the items in a list?
> Alternatively, is there one I can use to add all the numbers in a file?

sum() is what you are looking for [1].

Greets
Sander

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


Re: [Tutor] Elementtree and pretty printing in Python 2.7

2010-08-23 Thread Karim


Hello Jerry,

Tricky solution using minidom (standard) Not tested:

import ElementTree
import minidom

def prettyPrint(element):
   txt = ElementTree.tostring(element)
   print minidom.parseString(txt).toprettyxml()


Regards
Karim

On 08/22/2010 04:51 PM, Jerry Hill wrote:

On Fri, Aug 20, 2010 at 3:49 AM, Knacktus  wrote:
   

Hi guys,

I'm using Python 2.7 and the ElementTree standard-lib to write some xml.

My output xml has no line breaks! So, it looks like that:



instead of something like this:





I'm aware of lxml which seems to have a pretty print option, but I would
prefer to use the standard-lib ElementTree which seems not to have a feature
like this.

Do I miss something using the ElementTree-lib or is it bug?
 

Neither, as far as I know.  The XML you get is perfectly valid XML.
If you want to pretty print it, there's a recipe here:
http://effbot.org/zone/element-lib.htm#prettyprint, but I don't think
it's been included in the standard library yet.

   


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


Re: [Tutor] Adding all numbers in a file or list

2010-08-23 Thread Sander Sweers
On 23 August 2010 17:24, aug dawg  wrote:
> So it's sum(list_name) ?

Correct, but it is not limited to lists. Any itterable with
ints/floats will do, for example a tuple is also accepted.

Greets
Sander

PS: Please use reply to all so others on this list may benefit from
the questions/answers ;-)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Adding all numbers in a file or list

2010-08-23 Thread aug dawg
Oh okay, sorry about that.

Thanks for the help!


On Mon, Aug 23, 2010 at 11:33 AM, Sander Sweers wrote:

> On 23 August 2010 17:24, aug dawg  wrote:
> > So it's sum(list_name) ?
>
> Correct, but it is not limited to lists. Any itterable with
> ints/floats will do, for example a tuple is also accepted.
>
> Greets
> Sander
>
> PS: Please use reply to all so others on this list may benefit from
> the questions/answers ;-)
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] design of Point class

2010-08-23 Thread Gregory, Matthew
Bob Gailer wrote:
> class PointND(list):
>def __init__(self, *a_list):
>  super(PointND, self).__init__(a_list)
> 
>def getSet(ix):
>  def chklen(self):
>if len(self) < ix + 1:
>  raise AttributeError
>  def get(self):
>chklen(self)
>return self[ix]
>  def set(self, value):
>chklen(self)
>self[ix] = value
>  return property(get, set)
> 
>def set(self, ix):
>  return s
> 
>x = getSet(0)
>y = getSet(1)
>z = getSet(2)
> 
[snip]

Bob and Hugo, thanks for enlightening me to class properties.  Obviously, I'm 
still on the learning curve.  Bob, I'm not seeing where the outer "def 
set(self, ix)" is used.  Am I missing something?

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


Re: [Tutor] design of Point class

2010-08-23 Thread Gregory, Matthew
Hi Steven,

Steven D'Aprano wrote:
> Every time you change the interface of inherited methods, you probably
> shouldn't.
> 
> Firstly, it probably breaks the Liskov Substitution Principle. The LSP
> says, essentially, if you subclass A to make B, you should be able to
> use a B anywhere you can use an A. (After all, instances of B are also
> instances of A.) Here's an example of what not to do:
> 
> class Vehicle:
> def start(self, key):
> ignition.insert(key)
> ignition.turn()  # raises exception if out of fuel
> def go(self, key):
> self.start(key)
> self.handbrake = 'off'
> self.gear = 'drive'
> self.accelerate()
> 
> class Truck(Vehicle):
> # add other truck-like methods
> 
> class KeylessTruck(Truck):
> # Some military vehicles are designed to not require keys.
> # When on a battlefield, there's nothing worse than being
> # unable to find the car keys!
> def go(self):
> self.start()
> self.handbrake = 'off'
> self.gear = 'drive'
> self.accelerate()
> def start(self):
> ignition.turn()  # Actually a push button, but nevermind.
> 
> Can you see the problem? If the caller is expecting a Truck, and pass a
> key to the truck.go() method, they will get an exception if you give
> them a KeylessTruck instead of a Truck. This is a Bad Thing.
> 
> Secondly, changing method interfaces is not compatible with multiple
> inheritance and super(). You can probably get away with it if you stick
> to single inheritance, but it's still a bad thing to do.

Yes, this absolutely makes sense, but I'm less clear on how to solve it.  What 
I would think is that Vehicle shouldn't be defining start and this should be 
left up to a delegate within the subclasses?  Or am I showing my ignorance?

matt

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


Re: [Tutor] design of Point class

2010-08-23 Thread bob gailer

 On 8/23/2010 1:09 PM, Gregory, Matthew wrote:

Bob Gailer wrote:

class PointND(list):
def __init__(self, *a_list):
  super(PointND, self).__init__(a_list)

def getSet(ix):
  def chklen(self):
if len(self)<  ix + 1:
  raise AttributeError
  def get(self):
chklen(self)
return self[ix]
  def set(self, value):
chklen(self)
self[ix] = value
  return property(get, set)

def set(self, ix):
  return s

x = getSet(0)
y = getSet(1)
z = getSet(2)


[snip]

Bob and Hugo, thanks for enlightening me to class properties.  Obviously, I'm still on 
the learning curve.  Bob, I'm not seeing where the outer "def set(self, ix)" is 
used.  Am I missing something?


It should not be there! An accidental leftover.

But I notice other problems in my code which I am now attempting to fix. 
Back to you seen.


--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] design of Point class

2010-08-23 Thread Gregory, Matthew
Steven D'Aprano wrote:
> It would surprise me greatly if numpy didn't already have such a class.

Yes, that is the first place I went looking, but I couldn't find such a class.  
I found one project using numpy for geometry objects (geometry-simple, 
http://code.google.com/p/geometry-simple/), but it doesn't look to be fully 
fleshed out.

> Other than using numpy, probably the simplest solution is to just
> subclass tuple and give it named properties and whatever other methods
> you want. Here's a simple version:
> 
> class Point(tuple):
> def __new__(cls, *args):
> if len(args) == 1 and isinstance(args, tuple):
> args = args[0]
> for a in args:
> try:
> a+0
> except TypeError:
> raise TypeError('ordinate %s is not a number' % a)
> return super(Point, cls).__new__(cls, args)
> @property
> def x(self):
> return self[0]
> @property
> def y(self):
> return self[1]
> @property
> def z(self):
> return self[2]
> def dist(self, other):
> if isinstance(other, Point):
> if len(self) == len(other):
> sq_diffs = sum((a-b)**2 for (a,b) in zip(self, other))
> return math.sqrt(sq_diffs)
> else:
> raise ValueError('incompatible dimensions')
> raise TypeError('not a Point')
> def __repr__(self):
> return "%s(%r)" % (self.__class__.__name__, tuple(self))
> 
> 
> class Point2D(Point):
> def __init__(self, *args):
> if len(self) != 2:
> raise ValueError('need exactly two ordinates')
> 
> class Point3D(Point):
> def __init__(self, *args):
> if len(self) != 3:
> raise ValueError('need exactly three ordinates')
> 
> These classes gives you:
> 
> * immutability;
> * the first three ordinates are named x, y and z;
> * any ordinate can be accessed by index with pt[3];
> * distance is only defined if the dimensions are the same;
> * nice string form;
> * input validation.

Thanks for this help.  I'm curious as to why immutability would be an advantage 
here (or maybe that's not what you're suggesting).  Typically, I would want to 
be able to do 'p.x = 10', so subclassing from a list (or numpy nd-array 
perhaps) would make more sense in my case?

Further, if I use setters, can I still use decorators as you've outlined or do 
I need to do use 'x = property(get, set)'.  These are all new language 
constructs that I haven't encountered yet.
  
> What it doesn't give you (yet!) is:
> 
> * distance between Points with different dimensions could easily be
>   defined just by removing the len() comparison. zip() will
>   automatically terminate at the shortest input, thus projecting the
>   higher-dimension point down to the lower-dimension point;
> * other distance methods, such as Manhattan distance;
> * a nice exception when you as for (say) pt.z from a 2-D point, instead
>   of raising IndexError;
> * point arithmetic (say, adding two points to get a third).

All good ideas, especially the different distance metrics to be defined in 
Point.  I'm working on implementing these.

> An alternative would be to have the named ordinates return 0 rather than
> raise an error. Something like this would work:
> 
> @property
> def y(self):
> try: return self[1]
> except IndexError: return 0

Is there an advantage to doing this?  Wouldn't this make one falsely assume 
that y was defined and equal to 0?

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


Re: [Tutor] design of Point class

2010-08-23 Thread bob gailer

 I am happier with this:

class PointND(list, object):

  def __init__(self, *a_list):
super(PointND, self).__init__(a_list)
self.maxIndex = len(self) - 1

  def getSet(ix, attName):
msg = "'%s' object has no attribute '%s'" % (p.__class__.__name__, 
attName)

def get(self):
  if self.maxIndex < ix:
raise AttributeError, msg
  return self[ix]
def set(self, value):
  if self.maxIndex < ix:
raise AttributeError, msg
  self[ix] = value
return property(get, set)

  x = getSet(0, 'x')
  y = getSet(1, 'y')
  z = getSet(2, 'z')

p = PointND(1,2,3)
assert (p.x, p.y, p.z) == (1, 2, 3)
p.x = 6; p.y = 9; p.z = 5
assert (p.x, p.y, p.z) == (6, 9, 5)

try:
  p = PointND(1,2)
  p.z = 3
except AttributeError:
  print 'Passed all tests'



--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] design of Point class

2010-08-23 Thread Steven
On Tue, 24 Aug 2010 04:36:31 am Gregory, Matthew wrote:

> I'm curious as to why immutability would be an
> advantage here (or maybe that's not what you're suggesting). 

Immutability is *always* an advantage for numeric types.

You can use immutable objects as keys in dicts.

You can (if you want) optimise the class so that it caches instances, 
thus saving memory.

You can be sure that invariants remain true. If an immutable instance 
has to be, say, positive, once you've checked that it is positive once 
you can be sure than no function can change it to be negative.

Look at the standard Python numeric types:

int, long, float, decimal.Decimal, fractions.Fraction 

They are all immutable. That should tell you something :)


> Typically, I would want to be able to do 'p.x = 10', so subclassing
> from a list (or numpy nd-array perhaps) would make more sense in my
> case?

Why do you want to modify points rather than create new ones as needed?

In any case, you should not subclass from list. It makes no sense to 
have pt.sort() or pt.pop() or various other list-like methods. 
Subclassing list is not the way. If you insist on mutable points, then 
something like:

class MutablePoint(object):
def __init__(self, *ordinates):
self._ordinates = list(ordinates)
def __getitem__(self, i):
return self._ordinates[i]
def __setitem__(self, i, x):
self._ordinates[i] = x


and so forth.



> Further, if I use setters, can I still use decorators as you've 
> outlined or do I need to do use 'x = property(get, set)'.  These are
> all new language constructs that I haven't encountered yet.

In Python 2.5, the only way to pass a setter and/or deleter to property 
is by using the form x = property(getter, setter, deleter). In Python 
2.6, properties gain methods that let you do this:

@property
def x(self): return self._x
@x.setter
def x(self, value): self._x = value
@x.deleter
def x(self): del self._x

Note that you MUST use the same name (x in the above example) for the 
getter, setter and deleter.

[...]
> > An alternative would be to have the named ordinates return 0 rather
> > than raise an error. Something like this would work:
> >
> > @property
> > def y(self):
> > try: return self[1]
> > except IndexError: return 0
>
> Is there an advantage to doing this?  Wouldn't this make one falsely
> assume that y was defined and equal to 0?

That's why it's an alternative.

If you decide that for your application it makes sense to treat 
coordinates on the XY plane as equivalent to coordinates in the XYZ 
space with Z=0, that's the simplest way to implement it.



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


Re: [Tutor] design of Point class

2010-08-23 Thread Alan Gauld

"Gregory, Matthew"  wrote


class Vehicle:
def start(self, key):
def go(self, key):

class Truck(Vehicle):
# add other truck-like methods

class KeylessTruck(Truck):
# Some military vehicles are designed to not require keys.


Aside: Most modern high-end cars are keyless too! ;-)


def go(self):
def start(self):

Can you see the problem? If the caller is expecting a Truck, and 
pass a
key to the truck.go() method, they will get an exception if you 
give

them a KeylessTruck instead of a Truck. This is a Bad Thing.


Yes, this absolutely makes sense, but I'm less clear on how to solve 
it.


There are several ways. Where you cannot change the original
interface - which wrongly assumed that all vehicles need keys - you
can introduce a default key parameter in which the method just ignores
the key and provides a default value(None?) if not provided.

Its messy and I'd definitely comment it to make it clear the key is
only to preserve the inherited interface but its probably the simplest 
option.



What I would think is that Vehicle shouldn't be defining start


Defining start is probably OK (I can't think of a vehicle that doesn't
start in some way or other), but requiring a key is a mistake since
many vehicles don't use keys (think rickshaw or trolley bus etc)


and this should be left up to a delegate within the subclasses?


I'm not sure a delegate would help here, especially if you want
to start a list of vehicles.


Or am I showing my ignorance?


No, just uncovering the challenges of OO design. There is no
perfect solution, all models are approximations. Experience tends
to build better approximations but never perfect ones.

And sometimes breaking the LSP and working round the consequences
(try/except...) is the best - ie most pragmatic - solution. But that
should be the least favourite choice, try to maintain interfaces if 
possible.


HTH,

--
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] box drawing characters

2010-08-23 Thread Bill Allen
On Wed, Aug 18, 2010 at 2:13 PM, Bill Allen  wrote:

>
> "Ewald Horn"  wrote in message
>> news:aanlktinmkzyxbd0t7rldyexhbanw1tnfzac5z2gee...@mail.gmail.com...
>>
>>  Hi Bill,
>>>
>>> have you given UniCurses a spin?
>>>
>>> See http://pyunicurses.sourceforge.net/ for more information.
>>>
>>>
>> This does look very interesting and the documentation seems to reflect a
> product that is quite complete.   I will definitely give it a try.
>
> Thanks,
> Bill
>
I did finally have a chance to give this a try.   Seems to work as it
should.   Users should read the installation instructions carefully,
particularly if installing on a Windows system as the additional PDCurses
library (pdcurses.dll) is also required.

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


Re: [Tutor] box drawing characters

2010-08-23 Thread M. Milanuk
On 8/23/2010 8:35 PM, Bill Allen wrote:

> I did finally have a chance to give this a try.   Seems to work as it
> should.   Users should read the installation instructions carefully,
> particularly if installing on a Windows system as the additional
> PDCurses library (pdcurses.dll) is also required.  
> 

Bill,

This is of considerable interest to me as well.  I've downloaded the
various bits and will be tinkering with them as well as time allows.  If
you get a 'curses' application up and running on Windows any time soon,
I'd love to see it (screenshot), just as a proof-of-concept and/or
motivator ;)

Thanks,

Monte

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