Re: [Tutor] design questions: pythonic approach to ostriches

2005-04-24 Thread Alan Gauld
> I do remain a bit surprised that there seems to be no way to
implement
> what I naively thought would be the obvious solution -- to remove an
> inherited method from the instance's dictionary.

You can, as Kent said, override the method to do nothing. Some
languages,
like Eifell offer better support for that than others.

But there is a danger in removing methods too. By doing so you break
one of the fundamental principles of inheritence:
that everywhere that you use the superclass you can use the sub class.

If you remove the fly() method from your subclass of birds code like
this will break:

birds = [ aSwallow, anOstrich, anEmu, anEagle]

for bird in birds:
   bird.fly()

Whereas if you simply make fly a null method you can still call it
but nothing happens - a lot safer...

But conceptually the problem (and it is common) is that bird has a
fly() method when not all birds can fly - the object model is broken
at a high level of abstraction.

HTH,

Alan G.


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Does Python have anything like Perls format output?

2005-04-24 Thread Alan Gauld
> Good evening!  Does Python have a print function similar to Perl
> format output (example below)?
>format STDOUT =
>@< @ @<<< [EMAIL PROTECTED] [EMAIL PROTECTED]
>$code, $date,$descript,$amt,   $balance

This should be in a FAQ somewhere because it comes up a lot!

There is no direct equivalent but very similar effects are achieved 
using triple quoted format strings with named parameters:

format = '''
%-5(code)s %4(date)s %-20(descript)s $%9.2(amt)f $%9.2(balance)f'''

Then when you print the string provide the builtin local variables 
dictionary as the feeder for the variable substitution.

PS. 
The above string may not be exactly the same as your example 
- my Perl memory is fading fast...

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Bandwidth Tester

2005-04-24 Thread Danny Yoo


On Sun, 24 Apr 2005, Ali Polatel wrote:

> How can i write a simple bandwidth tester with Python?

Hi Ali,

A really rough sketch would be:


## Really rough pseudocode
def bandwidthTest():
Record the current time (use time.time())
Choose some resource that you can download, and download it
Record the current time again.
##

By this time, you should have some file that has been downloaded, and
you'll know how long it took you to get that file: this is enough
information to get a rough bandwidth calculation.


To make it robust, you'll probably want to do this on several resources on
the web, and on ones that are reliably fast, and then average the results.
You might also have to take into account things like bad connections, or
perhaps servers going down.  So the real world makes things a little
messy.


If you'd like a real example of one that's in production use, see:

http://mozmonkey.com/bandwidthtest/

It's the bandwidth tester used by the Firefox project.  The source code is
in Javascript, and can be extracted by using 'jar' to unpack the .XPI
file.

The source code in 'chrome/tester.js' doesn't look too particularly
daunting: the basic idea is the one sketched up above, with some special
cases to make sure silly things like Divide-by-zero don't happen.  And
it's slightly ugly because the interface / status-report code is mixed in
with the algorithm, but oh well.  *grin*

Best of wishes!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re Help with this script

2005-04-24 Thread John Carmona
Thanks for the help Kent, Noel and Alan. Here is my final script (it seems 
to be working ok but sometimes if I select "quit the programme", I need to 
enter that option 2 or 3 times before it works, is this a bug (I am running 
Win XP), please feel free to comment if you thing that something could be 
improved. Time to do the next exercise.
JC


#By J Carmona
#Programme that compute volumes or surfaces
##First menu is for the calculation of area
##Second menu is for the calculation of volume
##First ask the user what he wants to do
running = True
def area_rect():
   length = input("Length: ")
   width = input ("Width: ")
   print "The area is: ",length*width
def area_circ():
   radius = input("What is the radius?: ")
   print "The area is approximately: ", 3.14159*(radius**2)
def area_squ():
   side = input ("What is the length of one side?: ")
   print "The area is: ", side*side
def area_tgle():
   base = input ("What is the base of the triangle?: ")
   heigth = input ("What is the heigth of the triangle?: ")
   print "The area is: ",base*heigth/2
def vol_sph():
   radius = input("What is the radius?: ")
   print "The volume is: ", (4*3.14159*radius**3)/3
def vol_cube():
   side = input("Side: ")
   print "The volume is: ",side**3
def vol_box():
   width = input ("What is the width of the box?: ")
   length = input ("What is the length of the box?: ")
   depth = input ("What is the depth of the box?: ")
   print "The volume is: ", width*length*depth
def vol_cone():
   radius = input ("What is the radiux of the base of the cone?: ")
   heigth = input ("What is the heigth of the cone?: ")
   print "The volume is: ", 0.*3.144159*(radius**2)*heigth
def task_options():
   print "---"
   print "Options:"
   print "a. Print options: "
   print "b. Do you want to calculate areas?: "
   print "c. Do you want to calculate volumes?: "
   print "d. Quit the programme"
   print "---"
   choice = raw_input("Choose an option: ")
   if choice == 'a':
   print task_options()
   elif choice == 'b':
   print print_options()
   elif choice == 'c':
   print print_options_2()
   elif choice == 'd':
   running = False
def print_options():
   print_options
   print "--"
   print "Options:"
   print "a. print options"
   print "b. calculate circle area"
   print "c. calculate square area"
   print "d. calculate rectangle area"
   print "e. calculate triangle area"
   print "f. quit the programme"
   print "--"
   while 1:
   choice = raw_input("Choose an option: ")
   if choice == 'a':
   print_options()
   elif choice == 'b':
   area_circ()
   elif choice == 'c':
   area_squ()
   elif choice == 'd':
   area_rect()
   elif choice == 'e':
   area_tgle()
   if choice == 'f': break
def print_options_2():
   print "--"
   print "Options:"
   print "a. print options"
   print "b. calculate the volume of a sphere"
   print "c. calculate the volume of a cube"
   print "d. calculate the volume of a box"
   print "e. calculate the volume of a cone"
   print "f. quit the programme"
   print "--"
   while 1:
   choice = raw_input("Choose an option: ")
   if choice == 'a':
   print_options()
   elif choice == 'b':
   vol_sph()
   elif choice == 'c':
   vol_cube()
   elif choice == 'd':
   vol_box()
   elif choice == 'e':
   vol_cone()
   elif choice == 'e':
   print_options()
   if choice == 'f': break
#Call starting menu
task_options()

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] variable scope in nested functions

2005-04-24 Thread Logesh Pillay
Hello list
I am having trouble with a variable to act as a counter in a nested 
recursive function which will only occasionally find an answer.  
Something like a static variable in C.

Why does this sort of thing not work?
def foo (n):
   counter = 0
   def choose (i):
  if (solution found):
 counter += 1
 print counter, (solution)
  else choose (i+1)
   choose (1)
I get an error message that counter is referenced before being declared.
Declaring counter as global does not help either
Incidentally how does one nest comments in python.  I want to comment 
out part of a line.  Is it just Kate my editor which won't allow it

Thanks
Logesh

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] design questions: pythonic approach to ostriches

2005-04-24 Thread Kent Johnson
Brian van den Broek wrote:
I do remain a bit surprised that there seems to be no way to implement 
what I naively thought would be the obvious solution -- to remove an 
inherited method from the instance's dictionary.
The thing is, the inherited method is never *in* the instance's dictionary. It's not in the 
instance's class's dictionary either. It only lives one place, in the base class's dictionary. So it 
is not possible to remove it from the derived class - it is not there.

 >>> class Base(object):
 ...   def p(self):
 ... print 'Base.p()'
 ...
dir() shows attributes of Base and also of its base classes:
 >>> dir(Base)
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', 
'__module__', '__new__', '__reduce__', '__reduce_ex__'
, '__repr__', '__setattr__', '__str__', '__weakref__', 'p']

Not all of these items are in Base.__dict__, some are inherited from object. For example 
__getattribute__ is an attribute of object:
 >>> print Base.__dict__
{'__dict__': , 'p': , 
'__module__': '__main__', '__weakref__': 
__' of 'Base' objects>, '__doc__': None}

If we derive from Base, we can see more of the same:
 >>> class Derived(Base):
 ...   def q(self):
 ... print 'Derived.q()'
 ...
 >>> dir(Derived)
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', 
'__module__', '__new__', '__reduce__', '__reduce_ex__'
, '__repr__', '__setattr__', '__str__', '__weakref__', 'p', 'q']

 >>> print Derived.__dict__
{'q': , '__module__': '__main__', '__doc__': None}
There is no 'p' in Derived.__dict__.
So to 'remove' a method from Derived, you can't actually delete it from anywhere, you have to make 
it look like it is deleted.

One way to do this I have already suggested - make the Derived method raise AttributeError. This is 
the same exception you would get if it hadn't been defined and I think it will give a pretty 
convincing simulation.

Another way to do this would be to override Derived.__getattribute__() to watch for access to the 
derived method and raise AttributeError there.

Either one of these approaches should give a pretty good simulation of removing the attribute, 
though it still shows up if you dir(Derived). There doesn't seem to be a way to change that - I 
looked at the implementation of dir() (merge_class_dict() in object.c is the important part) and it 
doesn't have any hooks to customize it that I can see.

Whether you actually should do any of this is another question, I'll let my previous answer stand on 
that.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Name spaces again

2005-04-24 Thread David Driver
I have read the essay at
 and I am still having
problems understanding what I need to do. Here is the structure that I
am looking at:

Root folder
StartHere.py
Common folder
__init__.py
sobj.py
exceptions.py
validators.py
View folder (keeps cheetah and sxl templates)
Search folder (will be namespace for lookup operations)
Maintain folder (for creating and altering base domain objects)
Transact folder (namespace for creating transaction operations)
AR folder
__init__.py
sobj.py
exceptions.py
validators.py
View folder 
Search folder 
Maintain folder
Transact folder
AP folder
__init__.py
sobj.py
exceptions.py
validators.py
View folder 
Search folder 
Maintain folder
Transact folder
GL folder
__init__.py
sobj.py
exceptions.py
validators.py
View folder 
Search folder 
Maintain folder
Transact folder

StartHere.py contains:
import Common
import AR
import AP

Each subpackage __init__.py contains:
import exceptions
import validators
import sobjs
import Maintain
import Transact
import Search
import View


In AR.sobjs I have a class that is inherited from
Common.sobjs.baseDomObj. When I run StartHere.py Common imports just
fine. It starts to import AR and AR. __init__.py imports AR.sobjs.py
and it throws the following error:

Traceback (most recent call last):
  File "C:\foo\doinit\starthere.py", line 3, in ?
import AR
  File "C:\foo\doinit\AR\__init__.py", line 3, in ?
import sobjs
  File "C:\foo\doinit\AR\sobjs.py", line 1, in ?
class custAddress(Common.address):
NameError: name 'Common' is not defined

Do I need to import Common in each sub package to have access to it?
Does it consume more memory? What about Sub Sub packages? shouldn't
you be able to Import DateTime in StartHere and have all sub
modules/packages that are imported into StartHere.py use it? Am I
making a big deal out of nothing?

This entire project is more or less of a mock up of a project. I am
just trying to learn more about python and I am basing it on the VB
based accounting package I currently maintain. It isn't that I would
normally organize an app this way if I were building a new one.

-- 

***
See there, that wasn't so bad.
***
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Bandwidth Tester

2005-04-24 Thread Alan Gauld
>How can i write a simple bandwidth tester with Python?

It's very simple in concept: just download a fixed quantity 
of data and measure how long it took. Unfortunately, like 
many concepts measuring true Bandwidth is much more complex 
than that!

The simple approach only works if:
1) You are the only user of the link
2) You are the only user of the server at the other end
3) The remote server has 'infinite' capacity to deliver data.
4) The receiving computer has infinite capacity to receive data.
5) The data you receive is much bigger than the network 
   protocol overhead
6) The data you receive is all delivered in a single packet

If you can meet all of the above (or get near enough) then 
a simple approach will work. Otherwise you need to take 
account of queuing effects, both in the link and in the 
server, packet delays and network overheads. One way of 
achieveing resonable results is to repeat the process 
several times and take an average. Another thing to 
consider is taking a few ping samples and subtracting 
the ping time (multiplied by the number of packets) 
from the total.

However, many people when they refer to Bandwidth really 
mean the available data throughput which is much easier 
to measure. The simple approach combined with averaging is
usually adequate for that (but still beware of factor 2 
in the list above).

Finally, these techniques will only give a figure for the 
throughput of the end to end link, not the bandwidth of 
your ISP connection. To achieve that you need to ensure 
you download the data from a server on the same LAN as 
your network server! If you try using a remote server the 
congestion on a link between the USA and Europe, say, 
could easily become a dominant factor for the duration 
of your measures but on another occasion be non affecting. 
To get round that you need to take your samples at 
widely different times of day and day of week/month

HTH

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] "saving"?

2005-04-24 Thread Gavin Bauer
I've decided it would be cool to make a flashcard program. You would
start by entering all of the cards and their answers, then it would
ask you them in random order, with ones you get right coming up less
often, and ones you consistantly get wrong coming up more often.
However, I don't want to start this project unless I  could actually
make it useful. This means one thing: saving. I would need some way of
saving a "set" of flash cards such as "english vocab test" or "french
irregular verbs". The main purpose of this program (other than
learning more python) would be to actually help me study for a test,
so I would need to be able to save the information somehow. Any ideas?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "saving"?

2005-04-24 Thread Max Noel
On Apr 24, 2005, at 18:04, Gavin Bauer wrote:
I've decided it would be cool to make a flashcard program. You would
start by entering all of the cards and their answers, then it would
ask you them in random order, with ones you get right coming up less
often, and ones you consistantly get wrong coming up more often.
However, I don't want to start this project unless I  could actually
make it useful. This means one thing: saving. I would need some way of
saving a "set" of flash cards such as "english vocab test" or "french
irregular verbs". The main purpose of this program (other than
learning more python) would be to actually help me study for a test,
so I would need to be able to save the information somehow. Any ideas?
The shelve module seems to be what you're looking for.
-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "saving"?

2005-04-24 Thread Kent Johnson
Max Noel wrote:
On Apr 24, 2005, at 18:04, Gavin Bauer wrote:
make it useful. This means one thing: saving. I would need some way of
saving a "set" of flash cards such as "english vocab test" or "french
irregular verbs". The main purpose of this program (other than
learning more python) would be to actually help me study for a test,
so I would need to be able to save the information somehow. Any ideas?

The shelve module seems to be what you're looking for.
Or the pickle module.
Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] variable scope in nested functions

2005-04-24 Thread Kent Johnson
Logesh Pillay wrote:
Hello list
I am having trouble with a variable to act as a counter in a nested 
recursive function which will only occasionally find an answer.  
Something like a static variable in C.

Why does this sort of thing not work?
def foo (n):
   counter = 0
   def choose (i):
  if (solution found):
 counter += 1
 print counter, (solution)
  else choose (i+1)
   choose (1)
I get an error message that counter is referenced before being declared.
This is a limitation of Python's nested scopes. You can't assign to a variable in an enclosing 
scope. One way to work around this is to use a mutable value like a list in the enclosing scope:
def foo (n):
   counter = [0]
   def choose (i):
  if (solution found):
 counter[0] += 1
 print counter[0], (solution)
  else choose (i+1)
   choose (1)

You could also write a counter class:
class foo:
   def __init__ (n):
  self.counter = 0
   def choose (self, i):
  if (solution found):
 self.counter += 1
 print self.counter, (solution)
  else self.choose (i+1)
foo().choose (1)
I would suggest separating the counter from the solution checking though.
Declaring counter as global does not help either
No, then it just looks for counter in the global (module) namespace so it 
still doesn't find it.
Incidentally how does one nest comments in python.  I want to comment 
out part of a line.  Is it just Kate my editor which won't allow it
Use # to comment out to the end of a line. There is no way to comment out the middle of a line (like 
you could do in C or Java with /* stuff */)

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re Help with this script

2005-04-24 Thread Kent Johnson
John Carmona wrote:
Thanks for the help Kent, Noel and Alan. Here is my final script (it 
seems to be working ok but sometimes if I select "quit the programme", I 
need to enter that option 2 or 3 times before it works, is this a bug
Try this program. Choose option a a few times, then choose f enough times to exit. See if you can 
figure out what is going on.

def print_options():
   print "--"
   print "Options:"
   print "a. print options"
   print "f. quit the programme"
   print "--"
   while 1:
   choice = raw_input("Choose an option: ")
   if choice == 'a':
   print 'About to call print_options'
   print_options()
   print 'Finished calling print_options'
   if choice == 'f': break
print_options()
Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Name spaces again

2005-04-24 Thread Kent Johnson
David Driver wrote:
I have read the essay at
 and I am still having
problems understanding what I need to do. 

In AR.sobjs I have a class that is inherited from
Common.sobjs.baseDomObj. When I run StartHere.py Common imports just
fine. It starts to import AR and AR. __init__.py imports AR.sobjs.py
and it throws the following error:
Traceback (most recent call last):
  File "C:\foo\doinit\starthere.py", line 3, in ?
import AR
  File "C:\foo\doinit\AR\__init__.py", line 3, in ?
import sobjs
  File "C:\foo\doinit\AR\sobjs.py", line 1, in ?
class custAddress(Common.address):
NameError: name 'Common' is not defined
Do I need to import Common in each sub package to have access to it?
Yes, you have to import Common in any module that references Common.
Does it consume more memory?
No, not a significant amount. The module itself is only loaded once; each client module keeps a 
reference to the loaded module, so it is just the cost of a name.

 What about Sub Sub packages? shouldn't
you be able to Import DateTime in StartHere and have all sub
modules/packages that are imported into StartHere.py use it?
No, that's not the way it works. There is no truly global namespace in Python, you have to import 
the names you need into the modules that need them. (OK, there is one global namespace but you 
generally shouldn't change it.)

 Am I
making a big deal out of nothing?
Maybe - are you making a big deal out of it? :-)
Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] py2exe

2005-04-24 Thread Jeff Peery
I am using python 2.3.4. thanks.
 
JeffGreg Hasseler <[EMAIL PROTECTED]> wrote:
Hi Jeff. I can't tell if you sent the last email to just me or me andthe list, but make sure to send it to the list (don't just hit reply).Also, what version of wxPython are you using?On 4/21/05, Jeff Peery <[EMAIL PROTECTED]>wrote:> > OK, thanks again. I attached my code. I if anyone has an idea as to why the> executable fails after running py2exe please let me know. thanks for the> help! > > Jeff> > Greg Hasseler <[EMAIL PROTECTED]>wrote: > If the application was named test.exe, I find that they are typically> named test.exe.log then or similar.> > On 4/19/05, Jeff Peery wrote:> > Ok, thanks again Greg. Although I didn't see a log file, where would it> > appear and what would the name be... just in case I missed it. thanks. > > > &!
 gt;
 Jeff> > > > Greg Hasseler wrote: > > I meant to send my first reply the list..oops. If it doesn't leave any> > log file then I would suggest maybe sending the program source code> > itself to the list so that others can review it for potential error.> > > > > > On 4/18/05, Jeff Peery wrote:> > > Hi Greg, thanks for the help. the program does not launch, it crashes> > > immediately, and I did not see a log file. I also ran py2exe several> times> > > over and always the same result. the program runs great in regular> python> > > mode. any ideas? thanks. > > > > > > Jeff> > > > > > Greg Hasseler wrote: > > > Does the application launch at all or does it just immediately crash?> > > Look and see if there are any logs available. You may also consider> !
 > >
 running py2exe again.> > > > > > On 4/15/05, Jeff Peery wrote:> > > > > > > ! > hello, I am using py2exe. for most of my applications it has been> > great.> > > > although this last one I built and when I try to execute it I get an> > > error: > > > > > > > > RunTime Error: this application has requested the runtime to terminate> > in> > > an> > > > unusual way. please contact the applications support team for more> info.> > > > > > > > does anyone know what this means? thanks. > > > > > > > > Jeff > > > > > > > > > > > > ___> > > > Tutor maillist - Tutor@python.org> > > > http://mail.python.org/mailman/listinfo/tutor!
 >
 > > > > > > > > > > >> > >> > > > ___> > Tutor maillist - Tutor@python.org> > http://mail.python.org/mailman/listinfo/tutor> > > > > >> >___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor