Re: [Tutor] code improvement for beginner ?

2005-10-08 Thread Danny Yoo


On Sat, 8 Oct 2005, lmac wrote:

> Ok. Here we go. Wanted to start my page long ago. Now is the right time.
>
> http://daderoid.freewebspace24.de/python/python1.html

Hi lmac,

I'll pick out some stuff that I see; I'm sure others will be happy to give
comments too.  I'll try to make sure that all the criticism I give is
constructive in nature, and if you have questions on any of it, please
feel free to ask about it.


I'll concentrate on the imgreg() function first.  The declaration of
'images' as a global variable looks a little weird.  I do see that
'imgreg' feeds into 'images'.  Not a major issue so far, but you might
want to see if it's possible to do without the global, and explicitly pass
in 'images' as another parameter to imgreg.  Globals just bother me on
principle.  *grin*


You may want to document what 'patt' and 'search' are meant to be.  A
comment at the top of imgreg, like:

 """imgreg searches for a pattern 'patt' within the text 'search'.  If
 a match exists, adds it to the set of images, and returns 1.  Else,
 returns 0."""

will help a lot.  Documenting the intent of a function is important,
because people are forgetful.  No programming language can prevent memory
loss:  what we should try to do is to compensate for our forgetfulness.
*grin*


Looking at pageimgs(): I'm not sure what 't' means in the open statement:

f = open(filename, "rt")

and I think that 't' might be a typo: I'm surprised that Python doesn't
complain.  Can anyone confirm this?  I think you may have tried to do "r+"
mode, but even then, you probably don't: you're just reading from the
file, and don't need to write back to it.


Looking further into pageimgs(): again, I get nervous about globals.  The
use of the 'r1' global variable is mysterious.  I had to hunt around to
figure out what it was it near the middle of the program.

If anything, I'd recommend naming your global variables with more meaning.
A name like 'image_regex_patterns' will work better than 'r1'.  Also, it
looks like pageimgs() is hardcoded to assume 'r1' has three regular
expressions in it, as it calls imgreg three times for each pattern in r1.

if imgreg(r1[0],a) == 1:
continue
if imgreg(r1[1],a) == 1:
continue
imgreg(r1[2],a)

and that looks peculiar.  Because this snippet of code is also
copy-and-pasted around line 106, it appears to be a specific kind of
conceptual task that you're doing to register images.

I think that the use of 'r1' and 'imgreg' should be intrinsically tied.
I'd recommend revising imgreg() so that when we register images, we don't
have to worry that we've called it on all the regular expressions in r1.
That is, let imgreg worry about it, not clients: have imgreg go through
r1[0:3] by itself.


If we incorporate these changes, the result might look something like
this:

###
image_regex_patterns = map(re.compile,
   [r'http://\w+.\w+.\w+/i.+.gif',
r'http://\w+.\w+.\w+/i.+.jpg',
r'http://\w+.\w+.\w+/i.+.png'])
def imgreg(search):
"""Given a search text, looks for image urls for registration.  If
a new one can be found, returns 1.  Otherwise, returns 0.

Possible bug: does not register all images in the search text, but only
the first new one it can find.
"""
for r in image_regex_patterns:
z = r.search(search)
if z != None:
x = z.group(0)
if x not in images:
images.append(x)
return 1
return 0
###

Does this make sense?

The point of this restructuring is to allow you to add more image types
without too much pain, since there's no more hardcoded array indexing
against r1.  It also simplifies to calls to imgreg from:

if imgreg(r1[0],a) == 1:
continue
if imgreg(r1[1],a) == 1:
continue
imgreg(r1[2],a)

to the simpler:

imgreg(a)


I think I'll stop there and look at the program again later.  *grin* Hope
this helps!

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


Re: [Tutor] FW: FW: Is it Posible? To Crack And HowTo [horribly OT]

2005-10-08 Thread Daniel Watkins
> Really? I was of the impression that proprietory code developers *ate*
> small children. Goes to show, can't believe everything you read on
> Slashdot. 

I heard that they write all their programs using the blood of
cute-looking puppies (though how that doesn't short-circuit anything I'd
like to know (although I can't, because it'll be proprietary))...

And, no, I really can't see any way of crow-barring this back
on-topic. :P

Dan

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


Re: [Tutor] handling of tabular data

2005-10-08 Thread Danny Yoo


On Sat, 8 Oct 2005, [ISO-8859-1] Frank Hoffs�mmer wrote:

> I often find myself writing python programs to compute averages, min,
> max, top10 etc of columns in a table of data In these programs, I always
> capture each row of the table in a tuple the table is then represented
> by a list of tuples computing averages, min, max and other
> meta-information is then done with for loops or some list comprehension.

Hi Frank,

This doesn't quite answer your question in favor of Python, but have you
already considered using something like a relational database?  It
provides support for doing those kind of operations on tabular data.

I'm not certain that applying an OOP approach on table-centric data will
be too effective for solving the kinds of problems you're doing.
However, I have seen that relational databases support operations like
extracting min, max, and average information with relative ease.


Best of wishes to you!

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


Re: [Tutor] FW: Is it Posible? To Crack And HowTo

2005-10-08 Thread Liam Clarke
>
> On a good day the fun of creating all those licenses lets me sleep with a 
> smile on my face. On a bad day, I have nightmares about all the hungry 
> children caused by my greed. ;-)

Really? I was of the impression that proprietory code developers *ate*
small children.
Goes to show, can't believe everything you read on Slashdot.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] handling of tabular data

2005-10-08 Thread Frank Hoffsümmer
Hello
I often find myself writing python programs to compute averages, min,  
max, top10 etc of columns in a table of data
In these programs, I always capture each row of the table in a tuple
the table is then represented by a list of tuples
computing averages, min, max and other meta-information is then done  
with for loops or some list comprehension.

now I wonder, whether I shouldn't be using classes instead of lists  
to capture the table rows
with the little I know about classes, I assume that then I would have  
a list of class instances as representation of my tabular data
but given such a list of class instances, i would still need for  
loops to get to e.g. the minimal value of a certain attribute in all  
classes in that list. OR?
and what would be the benefit of using classes then?

what is the best practice, can anyone shed some light on this
thanks
-frank

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


Re: [Tutor] subclass problem: __names and type-checking

2005-10-08 Thread Alan Gauld
> If B inherits from A then every context where A or an A instance appears
> should work correctly with B or a B instance.  Since the B constructor
> *requires* more arguments, it violates that ideal.  In other words, it
> would be OK to allow additional arguments.  It is not OK to require
> them.

Which is all true but it should be pointed out that *allowing* them
includes such devices as constructor overloading (in Java/C++ etc)
or using default values for the additional parameters. The latter is
obviously a possible option in Python.

> In other words sub-class should really be a different class that adapts
> or possibly acts as a proxy for the _BaseClass.

Not necessarily, it may just provide alternate construction semantics.

> I've abused inheritance in the past in an attempt to reuse code and have
> usually regretted it

But this is always trure. Inheritance for code reuse is usually a bad idea
that comes back to bite you later. Inheritance implies an 'is-a' 
relationship.
If the sub class is not really  the same kinde of thing as the superclass
then inheritance is probably the wrong solution.

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] code improvement for beginner ?

2005-10-08 Thread lmac
Ok. Here we go. Wanted to start my page long ago. Now is the right time.

http://daderoid.freewebspace24.de/python/python1.html

Thank you.



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


Re: [Tutor] AttributeError: 'str' object has no attribute 'geturl'

2005-10-08 Thread Javier Ruere
Joseph Quigley wrote:
> Well, I'm back to coding more on my comic downloader and viewer and I 
> keep getting this error:
> 
> Traceback (most recent call last):
>   File "F:\Gacor\getgarf.py", line 244, in ?
> getImg(Data.todayStrip)
>   File "F:\Gacor\getgarf.py", line 127, in getImg
> Data.f.geturl()
> AttributeError: 'str' object has no attribute 'geturl'
> 

  Class Data has a class attribute, 'f', defined as an empty string. Check if 
Data.f is initialized before calling getImg.
  Also, why initialize with an empty str? Put a None in there or don't define 
the attribute at all.
  A tip: in line 126 there is a print Data.f. This will show nothing in this 
case. When printing for debugging, error reporting or user input, always place 
quotes around values so that it is easier to spot empty strings or non 
printable characters.
  Finally, keep in mind that you can always use pdb to see what's up.

Javier

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


[Tutor] AttributeError: 'str' object has no attribute 'geturl'

2005-10-08 Thread Joseph Quigley
Well, I'm back to coding more on my comic downloader and viewer and I keep getting this error:

Traceback (most recent call last):
  File "F:\Gacor\getgarf.py", line 244, in ?
    getImg(Data.todayStrip)
  File "F:\Gacor\getgarf.py", line 127, in getImg
    Data.f.geturl()
AttributeError: 'str' object has no attribute 'geturl'

My code is attached (sorry, but it's got lot's of text)
#! /usr/bin/env python
##
#  Created by Joseph Quigley #
#  This program is under the GNU GPL Licence #
#  Either version 2 or any higher version.   #
#  Garfield and the Garfield trade mark are  #
#  Copyrighted by Paws Inc.  #
##


# Import modules
import time
import urllib2
import os
import sys
from Tkinter import *
import Image
import ImageTk
import getpass


class Data:
# Define time and date
todays_date = time.localtime(time.time())
todayDay = time.strftime("%d", todays_date)
todayMonth = time.strftime("%m", todays_date)
todayYear = time.strftime("%y", todays_date)
todayYearFull = time.strftime("%Y", todays_date)
getDate = ''
month = ''
day = ''
yearFull = ''
year = ''

# More file location junk
stripName ="http://images.ucomics.com/comics/ga/%s/"; % (yearFull)
todayStrip = "ga%s%s%s.gif" % (todayYear, todayMonth, todayDay)
otherStrip = ""
download = ""
f = ""
VERSION = '0.9.3'

try:
if sys.argv[1] == "--version":
print """\nGacor %s
A Garfield Comic Downloader and reader.

Copyright (C) 2005 Joseph Quigley

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n""" % Data.VERSION
raise SystemExit

except IndexError:
print "\n" * 100

user = getpass.getuser()
name = 'gacor'

if os.name == 'posix':
imgDir = '/home/%s/.gacor/' % user
elif os.name == 'nt':
if os.path.exists('C:\Documents and Settings'):
imgDir = "C:\\Documents and Settings\\%s\\.gacor\\" % user
if os.path.exists('D:\Documents and Settings'):
imgDir = "D:\\Documents and Settings\\%s\\.gacor\\" % user
if os.path.exists('E:\Documents and Settings'):
imgDir = "E:\\Documents and Settings\\%s\\.gacor\\" % user
if os.path.exists('F:\Documents and Settings'):
imgDir = "F:\\Documents and Settings\\%s\\.gacor\\" % user
if os.path.exists('G:\Documents and Settings'):
imgDir = "G:\\Documents and Settings\\%s\\.gacor\\" % user
if os.path.exists('H:\Documents and Settings'):
imgDir = "H:\\Documents and Settings\\%s\\.gacor\\" % user
if os.path.exists('I:\Documents and Settings'):
imgDir = "I:\\Documents and Settings\\%s\\.gacor\\" % user
if os.path.exists('J:\Documents and Settings'):
imgDir = "J:\\Documents and Settings\\%s\\.gacor\\" % user
if os.path.exists('K:\Documents and Settings'):
imgDir = "K:\\Documents and Settings\\%s\\.gacor\\" % user
else:
setImgDir = raw_input("Please specify your Documents and Settings Drive\n(eg: C:\\ not C)\n> ")
imgDir = "%sDocuments and Settings\\%s\\.gacor\\" % user

if not os.path.exists(imgDir):
os.mkdir(imgDir)


# Errors
def Connect():
urllib2_URLError = """Temporary failure in name resolution.
This means that you may not be online or the site is down.
You may want to try again later."""
print "Connecting to server..."
try:
   Data.f = urllib2.urlopen("%s%s" % (Data.stripName, Data.todayStrip))
except  urllib2.URLError:
   print urllib2_URLError
print "Connected."

def Dsp_Image(pic):
root = Tk()
root.title("GaCoR (Garfield Comic Reader)")
app = Frame(root)
app.grid()
img = Image.open(pic)
imgPrep = ImageTk.PhotoImage(img)
imgShow = Label(app, image=imgPrep).grid()
info = Label(app, text="Displaying a Garfield for %s\%s\%s." % (Data.month, Data.day, Data.year)).grid()
app.mainloop()


def getImg(pic):
print "Dowloading Image"
print Data.f
Data.f.geturl()
pict_Data = Data.f.read()
pict = file("%s%s" % (imgDir, pic), 'w')
pict.write(pict_Data)
pict.close()
print "Finished Download"

def ShowImg(pic):
Dsp_Image("%s%s" % (imgDir, pic))

def comicDate():
while True:
print "\nEnter comic date in mmdd format (eg: 09122002 "

Re: [Tutor] is there any Python code for spatial tessellation?

2005-10-08 Thread Danny Yoo


On Sat, 8 Oct 2005, Shi Mu wrote:

> is there any Python code for spatial tessellation?

Are you looking for code to generate voronoi diagrams?

http://en.wikipedia.org/wiki/Voronoi_diagram

>From initial Google searches, it appears that there is a package called
Qhull that pepole use to do Voronoi tesselations.

http://www.qhull.org/

and Chris Myers has written a module around Qhull:

http://www.tc.cornell.edu/~myers/PyXL/


Otherwise, I don't think we at Tutor can help you that much; you may want
to ask on a more math-oriented forum.  Good luck to you!


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


Re: [Tutor] code improvement for beginner ?

2005-10-08 Thread Danny Yoo


On Sat, 8 Oct 2005, lmac wrote:

> i wonder if i could post some of my scripts and anyone can tell me if
> there is a better way for coding the problem. In the way of some
> teaching class. ;-)


Sure, that's perfectly fine.  If the script is very large, you may want to
post it on the web and send the mailing list a URL instead.  If there's
anything in particular that you want us to look at, point it out.

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


[Tutor] code improvement for beginner ?

2005-10-08 Thread lmac
Hi there,
i wonder if i could post some of my scripts and anyone can tell me if
there is a better way for coding the problem. In the way of some
teaching class. ;-)

Or is this mailing-list only for specific questions ?

Thanks.

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


Re: [Tutor] Opening files, finding their location

2005-10-08 Thread Scott Oertel




Christopher Arndt wrote:

  Scott Oertel schrieb:
  
  
I'm looking for an easy way to find the current directory location of my 
program so I can include the config.ini file correctly without having to 
pass command line args.

  
  
So, do you want to find out, where your script is living, or the directory from
which it was called (the "working directory")?

The former can be found out like this:

Assuming cron calls your script with the full path name (which should be the
case because it uses the shell to execute your script):

  
  

  
import os, sys
mydir = os.path.dirname(sys.argv[0])

  

  
  
When you want the current working directory:

  
  

  
import os
mydir = os.getcwd()

  

  
  
Then to get the path to your config file, either:

config_path = os.path.join(mydir, 'config.ini')

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



  

It was this one: 
mydir = os.path.dirname(sys.argv[0])

thanks man, it was starting to drive me nuts :)

-Scott Oertel
-Gawr.com!



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


[Tutor] Listing all of an instances variables

2005-10-08 Thread Python
   def report(self):
for i in dir(self):
# use the getattr function
print getattr(self, i)

-- 
Lloyd Kvam
Venix Corp

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


[Tutor] subclass problem: __names and type-checking

2005-10-08 Thread Python
Traceback (most recent call last):
   File "C:/Python24/foofoofoo.py", line 26, in -toplevel-
 s2 = Sub2()
   File "C:/Python24/foofoofoo.py", line 22, in __init__
 super(Sub2, self).__init__()
   File "C:/Python24/foofoofoo.py", line 10, in __init__
 if type(self) == __TwoUnderBase:  # What to write here
NameError: global name '_TwoUnderBase__TwoUnderBase' is not defined

Within a class, __ prefixes mangle the name to include the class name as
part of the name.  However, it appears that within a class statement,
the __ prefix is not mangled.  This is good for you because otherwise
the inheritance would not work.  However, it appears to make it
impossible to directly reference the class name from within the class.
You may want to rethink the idea of using __ prefixes in the class name.
Normally __ is used to "privatize" attributes within a class.

-- 
Lloyd Kvam
Venix Corp

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


[Tutor] subclass problem: __names and type-checking

2005-10-08 Thread Python
I think that a sub-class *needs* to support the same programming
interface as the parent class.  Bertrand Meyer has written about
programming by contract and the implications for object oriented design.
http://archive.eiffel.com/doc/oosc/
http://se.ethz.ch/~meyer/

If B inherits from A then every context where A or an A instance appears
should work correctly with B or a B instance.  Since the B constructor
*requires* more arguments, it violates that ideal.  In other words, it
would be OK to allow additional arguments.  It is not OK to require
them.

In other words sub-class should really be a different class that adapts
or possibly acts as a proxy for the _BaseClass.  Obviously you have
picked names that presuppose inheritance.

I've abused inheritance in the past in an attempt to reuse code and have
usually regretted it.  An alternative is to create a new class that
"fronts" for the class with the code we want to reuse.  The __getattr__
method provides a real simple way to redirect references from our new
class to the original class.

class Base:
def __init__(self, arg1,arg2):
...
class Adapt:
def __init__(self,arg1,arg2,arg3,arg4):
self._base = Base(arg1,arg2)
...
# this provides reuse of those Base methods that can be reused directly
def __getattr__(self,attrname):
return getattr(self._base, attrname)

Without knowing more about what you are doing, I could be sending you
off in the wrong direction, but hopefully this is relevant.

-- 
Lloyd Kvam
Venix Corp

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


Re: [Tutor] Listing all of an instances variables

2005-10-08 Thread Karl Pflästerer
On  8 Okt 2005, [EMAIL PROTECTED] wrote:

> Class SomeClass:
>def __init__(self,a,b):
>   self.a = a
>   self.b = b
>
>def report(self):
>   for i in dir(self):
>   print self.i
>
> 
>
>
> This is where I run into problems: How do I return all of the variables
> in an instance?

You can use the `__dict__' method.

>>> class Someclass (object):
def __init__(self,a,b):
self.a = a
self.b = b
def report(self):
for k, v in self.__dict__.items():
print "Variable %s -> %s" % (k, v)

... ... ... ... ... ... ... >>> 
>>> c = Someclass(1,2)
>>> c.report()
Variable a -> 1
Variable b -> 2
>>> c.c = 3
>>> c.report()
Variable a -> 1
Variable c -> 3
Variable b -> 2
>>> 

   Karl
-- 
Please do *not* send copies of replies to me.
I read the list
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subclass problem: __names and type-checking

2005-10-08 Thread Brian van den Broek
Kent Johnson said unto the world upon 2005-10-08 07:08:
> Brian van den Broek wrote:




>>
>>Here's a sketch of where I'm at:



>>class _BaseClass(object):
>>
>> def __init__(self, arg1, arg2):
>> self.arg1 = arg1
>> self.arg2 = arg2
>> if type(self) == _BaseClass:
>> self._validate_args()
>>
>> def _validate_args(self):
>> if not type(self.arg1) in (int, long):
>> raise TypeError
>>
>>class SubClass(_BaseClass):
>>
>> def __init__(self, arg1, arg2, arg3, arg4):
>> super(SubClass, self).__init__(arg1, arg2)
>> self.arg3 = arg3
>> self.arg4 = arg4
>> if type(self) == SubClass:
>> self._validate_args()
>>
>> def _validate_args(self):
>> super(SubClass, self)._validate_args()
>> if not isinstance(self.arg3, basestring):
>> raise TypeError
 >>
>>
>>This works as desired, but leaves two problems:
>>
>>1) I suspect there may be a better way, as a) this doesn't feel quite 
>>right and b) in general with Python, it seems that if you are tempted 
>>to type test, you should rethink, and


Thanks for the reply, Kent.

> I can think of two alternatives: 



> - Have two validate functions in each class - the shared
_validate_args() and a class-specific _validate_SubClassArgs(). Call
the class-specific version from __init__() and the shared one from
other clients. Then you would have
> 
> class _BaseClass(object):
>   def __init__(self):
> ...
> self._validate_BaseClass()
> 
>   def _validate_args(self):
> super(_BaseClass, self)._validate_args()
> self._validate_BaseClass()
> 
> and similar code in SubClass.

I think I see the idea. But I take it you didn't mean to have:

 >   def _validate_args(self):
 > super(_BaseClass, self)._validate_args()

within a method of _BaseClass (a subclass of object), as that will 
produce:
AttributeError: 'super' object has no attribute '_validate_args'


>>2) I originally had __BaseClass rather than _BaseClass. But, with that 
>>naming, cannot figure out how to write the line
>>
>> if type(self) == __BaseClass:
>>
>>so as to make it work. I know about the name mangling with __somename 
>>names, but I don't know how to manage it in this case.
>>
>>The attempt of 4 lines up produces:
>>
>>NameError: global name '_BaseClass__BaseClass' is not defined
>>
>>This confuses me. I don't see why the error msg prepends '_BaseClass' 
>>as that name appears nowhere. That confusion aside, I've no idea how 
>>to effect what I want.
> 
> 
> The __ name only gets mangled inside the class definition. The
> class name itself is not getting mangled. From the language
> reference:
> 
> Private name mangling: When an identifier that textually occurs in
> a class definition begins with two or more underscore characters
> and does not end in two or more underscores, it is considered a
> private name of that class. Private names are transformed to a
> longer form before code is generated for them.


OK, thanks. But I'm still not quite there.

Consider this example code:

class _OneUnderBase(object):
 def __init__(self):
 if type(self) == _OneUnderBase:
 print "From _OneUnderBase"
 else:
 print "From subclass",

class __TwoUnderBase(object):
 def __init__(self):
 if type(self) == __TwoUnderBase:  # What to write here
 print "From __TwoUnderBase"
 else:
 print "From subclass",

class Sub1(_OneUnderBase):
 def __init__(self):
 super(Sub1, self).__init__()
 print "Sub1"

class Sub2(__TwoUnderBase):
 def __init__(self):
 super(Sub2, self).__init__()
 print "Sub2"

s1 = Sub1()
s2 = Sub2()


When run, this gives:

 From subclass Sub1

Traceback (most recent call last):
   File "C:/Python24/foofoofoo.py", line 26, in -toplevel-
 s2 = Sub2()
   File "C:/Python24/foofoofoo.py", line 22, in __init__
 super(Sub2, self).__init__()
   File "C:/Python24/foofoofoo.py", line 10, in __init__
 if type(self) == __TwoUnderBase:  # What to write here
NameError: global name '_TwoUnderBase__TwoUnderBase' is not defined
 >>>

What should I write in the if test of __TwoUnderBase.__init__() to 
make it work? (Nevermind the desired behaviour here could be obtained 
without the type test. How to work that test is the point I'm 
interested in.)

Thanks,

Brian vdB


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


Re: [Tutor] Opening files, finding their location

2005-10-08 Thread Christopher Arndt
Scott Oertel schrieb:
> I'm looking for an easy way to find the current directory location of my 
> program so I can include the config.ini file correctly without having to 
> pass command line args.

So, do you want to find out, where your script is living, or the directory from
which it was called (the "working directory")?

The former can be found out like this:

Assuming cron calls your script with the full path name (which should be the
case because it uses the shell to execute your script):

>>> import os, sys
>>> mydir = os.path.dirname(sys.argv[0])

When you want the current working directory:

>>> import os
>>> mydir = os.getcwd()

Then to get the path to your config file, either:

config_path = os.path.join(mydir, 'config.ini')

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


[Tutor] Listing all of an instances variables

2005-10-08 Thread Matt Williams
Dear List,

I'm stuck on trying to write a generic 'report' function:

Class SomeClass:
   def __init__(self,a,b):
self.a = a
self.b = b

   def report(self):
for i in dir(self):
print self.i




This is where I run into problems: How do I return all of the variables
in an instance?

I'm sure I'm not the first person to ask, but I couldn't find an answer
anywhere else...

Thanks,

Matt
-- 
Dr. M. Williams MRCP(UK)
Clinical Research Fellow
Cancer Research UK
+44 (0)207 269 2953
+44 (0)7384 899570

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


Re: [Tutor] Did anyone get the Kamaelia "Conversing" chapter 5 to work?

2005-10-08 Thread R. Alan Monroe
> On Friday 07 October 2005 03:04, R. Alan Monroe wrote:
> That's great to hear - not the oversight part but the fact you were talking
> about your work. Out of interest, how did you find the tutorial/exercises and
> what level of experience would you say you have?

Around 2-3 years with Python. But I had never used generators (was
aware of them but never had a need) so that was the primary chunk of
the learning curve.

Alan

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


[Tutor] Opening files, finding their location

2005-10-08 Thread Scott Oertel
I have a small problem with one of my scripts currently, I'm using the 
config parser to open a config.ini file, but this program is going to be 
designed to be used as a cron job, currently i made a work around.. 
./program.py config.ini is how you run it from the command line

I'm looking for an easy way to find the current directory location of my 
program so I can include the config.ini file correctly without having to 
pass command line args.

here is my work around,

try:
  config.readfp(open(argv[1]))
except (IndexError, IOError):
  print "Config.ini file not found."
  exit()



thanks!


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


Re: [Tutor] subclass problem: __names and type-checking

2005-10-08 Thread Kent Johnson
Brian van den Broek wrote:
> I have a class which I want to subclass. The subclass adds some
> additional arguments to __init__. I want both classes to run a sanity
> check on their arguments before leaving their respective __init__
> methods. I need both to do so, as the _BaseClass may be directly
> instantiated. I need to ask permission for the arguments on instance
> creation rather than for forgiveness later, as bad arguments passed to
> __init__ could take many cpu cycles of other code before they
> manifested themselves.
> 
> Here's a sketch of where I'm at:
> 
> class _BaseClass(object):
> 
>  def __init__(self, arg1, arg2):
>  self.arg1 = arg1
>  self.arg2 = arg2
>  if type(self) == _BaseClass:
>  # Problem (2) mentioned below shows up here.
>  #
>  # type test needed otherwise Subclass._validate_args
>  # will be called before all subclass args processed by
>  # SubClass.__init__, causing AttriuteError
>  self._validate_args()
> 
>  def _validate_args(self):
>  '''Performs sanity check on arguments'''
>  if not type(self.arg1) in (int, long):
>  raise TypeError
>  # etc
> 
> class SubClass(_BaseClass):
> 
>  def __init__(self, arg1, arg2, arg3, arg4):
>  super(SubClass, self).__init__(arg1, arg2)
>  self.arg3 = arg3
>  self.arg4 = arg4
>  if type(self) == SubClass:
>  # same reasoning as before -- leaving room for further
>  # subclassing.
>  self._validate_args()
> 
>  def _validate_args(self):
>  super(SubClass, self)._validate_args()
>  if not isinstance(self.arg3, basestring):
>  raise TypeError
>  # etc
> 
> 
> This works as desired, but leaves two problems:
> 
> 1) I suspect there may be a better way, as a) this doesn't feel quite 
> right and b) in general with Python, it seems that if you are tempted 
> to type test, you should rethink, and

I can think of two alternatives:
- If you don't need to call _validate_args() outside of __init__(), just put 
the code inline in __init__(). Not as clean a class structure but it's a simple 
solution to the problem.

- Have two validate functions in each class - the shared _validate_args() and a 
class-specific _validate_SubClassArgs(). Call the class-specific version from 
__init__() and the shared one from other clients. Then you would have

class _BaseClass(object):
  def __init__(self):
...
self._validate_BaseClass()

  def _validate_args(self):
super(_BaseClass, self)._validate_args()
self._validate_BaseClass()

and similar code in SubClass.

> 
> 2) I originally had __BaseClass rather than _BaseClass. But, with that 
> naming, cannot figure out how to write the line
> 
>  if type(self) == __BaseClass:
> 
> so as to make it work. I know about the name mangling with __somename 
> names, but I don't know how to manage it in this case.
> 
> The attempt of 4 lines up produces:
> 
> NameError: global name '_BaseClass__BaseClass' is not defined
> 
> This confuses me. I don't see why the error msg prepends '_BaseClass' 
> as that name appears nowhere. That confusion aside, I've no idea how 
> to effect what I want.

The __ name only gets mangled inside the class definition. The class name 
itself is not getting mangled. From the language reference:

Private name mangling: When an identifier that textually occurs in a class 
definition begins with two or more underscore characters and does not end in 
two or more underscores, it is considered a private name of that class. Private 
names are transformed to a longer form before code is generated for them. 

Kent
> 
> I think I won't want __BaseClass in the end, as I do expect it is 
> possible that it will be instantiated directly, so the '__' seems 
> inappropriate. But, the issue of how to do it remains.
> 
> So, details of '_' vs '__' aside, is my approach sound? And, how to 
> deal with __BaseClass?
> 
> 
> Best to all,
> 
> Brian vdB
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

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


Re: [Tutor] [Fwd: Re: Consistant Overhead Byte Stuffing (COBS)algorithm help]

2005-10-08 Thread Kent Johnson
Michael Cotherman wrote:
> The c code seems to be walking through the list moving
> bytes from src to dst, but the python code below seems
> to take one byte from src, start counitng up to the
> value from 1 and appending each and every value along
> the way to dst, no?

Ah, right you are. You are commenting on Alan's code and I am replying thinking 
you are commenting on my code. Doh! Sorry about that!

Alan was just trying to sketch out the Python equivalent to the C code and his 
translation has a bug - the line
  dst.append(i)
should be
  dst.append(src[i])

But...I posted complete, working code that duplicates your results. Did you see 
it? Does it work for you?

In my code instead of the loop to copy the fragment from src to dst I just copy 
the complete chunk in one go:
   dst.append(src[current+1:current+count])

I'll repeat my original reply below in case you lost it.

Kent

Michael Cotherman wrote:

> I am a noob to converting pointers in C++ to arrays in
> python, although the first time I see it done, I will
> have no problem. Can you help converting the below
> (what I think is the 'decoder' section) to python?


OK I'll bite. Your code is copying from a src buffer to a dst buffer. The src 
buffer has a count byte followed by count-1 bytes of data. If the count is less 
that 0xFF, a zero byte has to be inserted into the dst. So the decode loop gets 
a count, copies that many bytes to the dst buffer, then optionally appends a 0.

Python doesn't have a direct equivalent to this sort of manipulation of memory 
pointers and raw memory buffers. They are commonly replaced by strings or 
lists. My function takes a string as an input argument, builds the output as 
string fragments in a list, then builds a string to return.

Note that Python strings include an implicit length so there is no need to pass 
and return a length argument.

I included a test case with the data from your previous email. Your data is 
evidently hex-encoded as well as COBS encoded - in other words your strings are 
hex values where each two chars represent a single byte. I have converted to 
and from byte strings to feed this to the decoder.

Kent

def unstuff(src):
   # src is a COBS compressed string
   current = 0 # index into src
   dst = []# a list that will build the result

   while current < len(src):
   # Get the count and convert it to an integer
   count = ord(src[current])

   # Append count-1 chars from src to dst
   dst.append(src[current+1:current+count])

   # Do we need to add a zero byte?
   if count < 0xFF:
   dst.append('\x00')

   # Bump the counter and continue
   if count>0:
   current += count
   else:
   current += 1

   # dst is a list of string fragments; this converts it to a single string
   return ''.join(dst)

def hexToString(hexStr):
   ''' Convert a string of two-digit hex values to a string of bytes with those 
values '''
   return ''.join([chr(int(hexStr[i:i+2], 16)) for i in range(0, len(hexStr), 
2)])

def stringToHex(src):
   ''' Convert a byte string to a string of two-digit hex values '''
   return ''.join([ '%02x' % ord(s) for s in src ])
  if __name__ == '__main__':
   data = '0002860104DB203F0100'
   print data
   data = hexToString(data)
   print
  newData = unstuff(data)
   print stringToHex(newData)


> 
> -mike
> 
> 
> --- Alan Gauld <[EMAIL PROTECTED]> wrote:
> 
> 
>>>I am a noob to converting pointers in C++ to
>>
>>arrays in
>>
>>>python, although the first time I see it done, I
>>
>>will
>>
>>>have no problem. Can you help converting the below
>>>(what I think is the 'decoder' section) to python?
>>
>>It won't be working code but I think this is whats
>>happening...
>>
>>
>>>UINT CCobsPackets::UnStuffData(unsigned char *src,
>>>unsigned char *dst, UINT length)
>>
>>def UnStuffData(src,dst,len):
>>
>>
>>>{
>>>unsigned char *dstStart = dst;
>>>unsigned char *end = src + length;
>>
>># I don't think these are needed for Pyhon.
>>
>>
>>>while (src < end)
>>
>>for code in src:
>>
>>
>>>{
>>>int code = *src++;
>>>for (int i=1; i>>{
>>>*dst++ = *src++;
>>>}
>>
>>for i in range(1,code):
>>   dst.append(i)
>>
>>
>>>if (code < 0xFF) 
>>>{
>>>*dst++ = 0;
>>>}
>>
>>   if code < 0xff
>>   dst.append('\0')   # may not be needed in
>>python...
>>
>>
>>>}
>>>return (UINT)(dst - dstStart);
>>>}
> 
> 
> 
> 
>   
>   
> __ 
> Yahoo! Mail - PC Magazine Editors' Choice 2005 
> http://mail.yahoo.com
> ___
> 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] is there any Python code for spatial tessellation?

2005-10-08 Thread Shi Mu
is there any Python code for spatial tessellation?
thanks a lot!
 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 20, Issue 26: New Python Book

2005-10-08 Thread Matt Williams
IMHO, as regards the book using wxPython, rather than Tkinter: 
I've failed to get Tkinter to compile on several installs, 
whereas I can usually get wxPython to work. Also, wx seems 
to be better documented.I know it's not ideal to pick one
platform, but I would guess that wx would be a reasonable default.

Matt



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