Re: [Tutor] iteration is overwriting the previous set value

2005-10-20 Thread Jonas Melian
bob wrote:

> At 04:16 PM 10/19/2005, Jonas Melian wrote:
>
>> def _pre_save(self):
>> for field in [self.name, self.native_name]:
>> if not field.istitle():
>> #print field.title()
>> field = field.title()
>>
>> The change I try to do there (field = field.title()) is not being 
>> applied
>
>
> Yes it is. field (a local variable) is being replaced by 
> field.title(). You can confirm that by putting
> print field after the assignment.
>
> However I guess you want the change to apply to self.name and 
> self.native_name.
>
> Unfortunately you have a list containing the values of self.name and 
> self.native_name. Even if you modified the list elements (which 
> assignment to field does not do) self.name and self.native_name would 
> not be affected.
>
> Use getattr and setattr to access and assign the attributes, which you 
> specify by name.
>
> def _pre_save(self):
> for fieldname in ['name', 'native_name']:
> setattr(self, fieldname) = getattr(self, fieldname).title()
>
> [snip]
>
This fails:
SyntaxError: can't assign to function call

Danny Yoo's goes ok

You've the reason: there is no benefit in using "if not field.istitle():"

Thanks all

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


Re: [Tutor] iteration is overwriting the previous set value

2005-10-20 Thread Jonas Melian
Your code is correct. Thanks
I understood it. 'field' is a local variable inner that loop.

Respect to a related matter, a should be '42'

Danny Yoo wrote:

>On Thu, 20 Oct 2005, Jonas Melian wrote:
>
>  
>
>Hi Jonas,
>
>
>Do you understand why it isn't working?
>
>The issue is that 'field' is just another variable name, and the
>assignment just redirects that particular name to some other value.  So
>when we're doing:
>
>field = field.title()
>
>this statement has no effect on any other name, and in particular, doesn't
>do any mutation on 'self'.
>
>
>As a related matter:
>
>##
>  
>
a = "42"
b = a
b = "17"


>##
>
>What do you expect 'a' to be?
>
>
>
>  
>
>>I'm supposed that each iteration is overwriting the previous set value
>>
>>how solve it? using a dict?
>>
>>
>
>One way to do this is to use getattr() and setattr() so that we can do
>mutation on 'self'.  Your example above should work with:
>
>###
>def _pre_save(self):
>for fieldname in ['name', 'native_name']:
>value = getattr(self, fieldname)
>if not value.istitle():
>setattr(self, fieldname, value.title())
>###
>
>
>Hope this helps!
>
>
>  
>

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


[Tutor] pytunes (Was __slots__, struct, etc.)

2005-10-20 Thread Liam Clarke
Hi all,

Well, the fruits of my labour and your assistance is now at a basic
level. 'Tis called pytunes, designed to parse and make sense of the
iPod's database file.

I'm not satisfied with it at all, it's a bit half baked in terms of
functions and classes, but I would heartily welcome your perusal and
feedback, criticisms, suggestions regarding it as you see fit.

I need to take a break and gain some perspective, but I'm going to
keep working on this until it's usable and consistent.

And, if anyone's got an iPod of any sort, please give it a go, and let
me know how it goes, my little iPod mini isn't a broad test.

Page is here - http://silence.decivex.net/pytunes.htm

Please note, as I'm an absolute beginner with webpages and CSS, my
website looks absolutely terrible in Internet Explorer, and I have no
idea why, but I'm trying to fix it.
(Any hints on this also gratefully received.)

I'd like to thank those who've assisted me in grappling with some more
unusual corners of Python, with special thanks (in no particular
order) to Kent, Alan Gauld and Danny.

Regards,

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


[Tutor] file opening and errors.

2005-10-20 Thread Dan Klose
Hi,

I usually use perl but fancy a bit of a change so have started playing
with python.

using perl to open a file or directory I usually use:

open(FILE, $file) or die "Error: $!\n";

The $! is a perl variable that holds an error should the open fail,
example being : "No such file or directory".

With python I have use a try except block but I have no idea how I would
get the same warning from python as I would from perl (the reason for
the exception), I am not even sure if this is possible (I assume it must
be) as google searching has been fruitless.

Thanks for any help, pointers and suggestions.

Dan.

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


Re: [Tutor] file opening and errors.

2005-10-20 Thread w chun
On 10/20/05, Dan Klose <[EMAIL PROTECTED]> wrote:
>
> I usually use perl but fancy a bit of a change so have started playing
> with python.

congrats!  :-)

> using perl to open a file or directory I usually use:
> open(FILE, $file) or die "Error: $!\n";
>
> The $! is a perl variable that holds an error should the open fail,
> example being : "No such file or directory".
>
> With python I have use a try except block but I have no idea how I would
> get the same warning from python as I would from perl (the reason for
> the exception), I am not even sure if this is possible (I assume it must
> be) as google searching has been fruitless.

in the body of your code, you'd have something like:

try:
f = open(filename, 'r')
except IOError, e:
print 'Error: %s' % str(e)  # 'e' is a exception instance obj w/
the error string
return # or sys.exit(1) or whatever you like

hope this helps,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2006,2001
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Rebate on "Beginning Python"

2005-10-20 Thread Kent Johnson
Apress, publisher of the book "Beginning Python: From Novice to Professional", 
is offering a $10 rebate if you purchase the book before October 30. See for 
example
http://www.bookpool.com/sm/159059519X

Kent

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


Re: [Tutor] file opening and errors.

2005-10-20 Thread Kent Johnson
Dan Klose wrote:
> Hi,
> 
> I usually use perl but fancy a bit of a change so have started playing
> with python.
> 
> using perl to open a file or directory I usually use:
> 
> open(FILE, $file) or die "Error: $!\n";
> 
> The $! is a perl variable that holds an error should the open fail,
> example being : "No such file or directory".

If you want the error to be fatal as in the example above, my recommendation is 
to just use a plain open() call. If the open fails it will raise an exception 
which will be caught by the interpreter. The interpreter will print the text of 
the error and a complete stack trace which can be very useful in locating and 
troubleshooting the error. For example:

 >>> f=open('foo.txt')
Traceback (most recent call last):
  File "", line 1, in ?
IOError: [Errno 2] No such file or directory: 'foo.txt'

If you catch the exception and just print the error message you are suppressing 
useful information.

If you want to print the error and continue processing, instead of aborting, 
traceback.print_exc() is handy - it prints the same information as the 
interpreter would. For example:

 >>> import traceback
 >>> def trapper():
 ...   try:
 ... f = open('foo.txt')
 ...   except IOError:
 ... traceback.print_exc()
 ...   print 'Still here...'
 ...
 >>> trapper()
Traceback (most recent call last):
  File "", line 3, in trapper
IOError: [Errno 2] No such file or directory: 'foo.txt'
Still here...

In these small examples the traceback is not that interesting, but in a larger 
program they can be helpful. Also it is a good habit in general not to suppress 
tracebacks - for file errors you may have a pretty good idea where the problem 
is, but other kinds of errors can be harder to track down.

Kent

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


Re: [Tutor] regular expression matching a dot?

2005-10-20 Thread Frank Bloeink
Hi [Christian|List]

This post is not regarding your special problem (which anyway has been
solved by now), but I'd like to share some general tip on working with
regular expressions.
There are some nice regex-debuggers out there that can help clearify
what went wrong when a regex doesn't match when it should or vice versa.

Kodos http://kodos.sourceforge.net/ is one of them, but there are many
others that can make your life easier ; at least in terms of
regex-debugging ;) 

Probably most of you (especially all regex-gurus) know about this
already, but i thought it was worth the post as a hint for all beginners

hth Frank

On Wed, 2005-10-19 at 09:45 +0200, Christian Meesters wrote:
> Hi
> 
> I've got the problem that I need to find a certain group of file names 
> within a lot of different file names. Those I want to match with a 
> regular expression are a bit peculiar since they all look like:
> ...
> ...(regex-problem)
> ...
> Any ideas what I could do else?
> TIA
> Christian
> 
> PS Hope that I described the problem well enough ...



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


Re: [Tutor] regular expression matching a dot?

2005-10-20 Thread Kent Johnson
Frank Bloeink wrote:
> There are some nice regex-debuggers out there that can help clearify
> what went wrong when a regex doesn't match when it should or vice versa.
> 
> Kodos http://kodos.sourceforge.net/ is one of them, but there are many
> others that can make your life easier ; at least in terms of
> regex-debugging ;) 

Yes, these programs can be very helpful. There is even one that ships with 
Python - see
C:\Python24\Tools\Scripts\redemo.py

Kent

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


Re: [Tutor] "Decompile" pyc file

2005-10-20 Thread Bernard Lebel
Sorry for the late reply.

Thanks a lot Kent, that was really helpful.


Bernard



On 10/14/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Bernard Lebel wrote:
> > Hello,
> >
> > Is there a way to "decompile" a pyc file? I have a big problem where
> > the py file was lost, but the pyc file is instact. I would need to
> > extract the source code from the pyc file.
>
> Google 'python decompiler'
>
> try http://www.freshports.org/devel/decompyle/
> or the commercial service at http://www.crazy-compilers.com/decompyle/
>
> Kent
>
> ___
> 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] define vars by iteration

2005-10-20 Thread Luke Jordan
Danny,
 
It does help. I'm still stuck on part of it though, maybe a little background will help.
 
To learn more about classes I decided to make a class Map, with many instances that have directions pointing to other Map instances. Each Map has different objects you can find on it, but is still a Map, so I have to customize each one. 

 
So if the only solution involves having names that could collide with builtins, I'd like to do it that way. I recognize the potential for chaos, but none of the names that I am using will collide (crossed fingers) becuase I'm using names like "Backyard", "Kitchen" etc. So, 

 
>>> MyBackyard = Map("MyBackyard")
>>> MyBackyard.setDirections()
set direction for N: MyHouse
set direction for S: TheStreet
>>> MyBackyard.N
MyHouse
 
etc, where MyHouse and TheStreet are made, via function, into MyHouse = Map("MyHouse") and so forth. Each instance is pickled in its own file named after self.name.
 

When I load the pickles like this
 
classNameList = ["Yard","Kitchen","LivingRoom"]
 
def getPickles():
    for name in classNameList:
    filepath = "C:\Python24\"+name+".dat"
    openedFile = file(filepath,"r")
    classInstanceName = pickle.load(openedFile)
    classInstanceName.name = classInstanceName
    print classInstanceName.name, classInstanceName
 
Yard 
Kitchen 
LivingRoom 
>>> LivingRoom

>>> Kitchen
name Kitchen not defined
>>> Yard
name Yard not defined
 
Also, I have done what I'm trying to do successfully by populating a dictionary with class instances named after self.name, which, after the function runs, I can access this way
 
>>> classDictionary["Yard"]

 
the thing is I would like to be able to get at Yard's attributes by typing
 
>>> Yard.anAttribute
garbage cans
 
at the prompt rather than
 
>>> Yard = classDictionary["Yard"]
>>> Yard.anAttribute
garbage cansIt's just that I can't pin down how to automate it, say through a loadAllMaps() func. 
Thanks again for your helpful advice!
 
Luke
 
On 10/19/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
On Wed, 19 Oct 2005, Luke Jordan wrote:> I've got a bunch of pickled class instances with
> self.nameattributes, and I would like to assign the> instances themselves to variables> named whatever is stored in 
self.name  using a function.> "Can't assign to literal", right? Is there a way to do this?Hi Luke,It's technically possible to do this, but discouraged.  The reason it's
not so safe is because some of those names might collide with your ownprogram's names, or with the builtins.  So if you start having pickledinstances with names like 'list' or 'open', havoc is bound to ensue.
Furthermore, Python variable names have some physical restrictions thatmay interfere with what you're trying to do:##>>> 4meUshouldnthave = 42File "", line 1
   4meUshouldnthave = 42  ^SyntaxError: invalid syntax##(For the gory details on what's allowed in a name "identifier", see:
http://www.python.org/doc/ref/identifiers.html)A safer way to do that I think you want is to use a separate dictionarycontainer for those instances.  As a concrete example:##class Person:
   def __init__(self, name):   self.name = namepeople_names = ['fred', 'barney', 'wilma', 'betty']people = {}for name in people_names:   people[name] = Person(name)
##Rather than using a direct variable name to refer to the person, we can goan indirect route, and refer to the corresponding entry in the 'people'dictionary.  Does this make sense?  This is safer because there's no
potential to munge up the toplevel, plus the 'name' keys won't have therestrictions that Python variable names have.Hope this helps!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iteration is overwriting the previous set value

2005-10-20 Thread bob
At 12:32 AM 10/20/2005, Jonas Melian wrote:
>bob wrote:
>
> > At 04:16 PM 10/19/2005, Jonas Melian wrote:
> >
> >> def _pre_save(self):
> >> for field in [self.name, self.native_name]:
> >> if not field.istitle():
> >> #print field.title()
> >> field = field.title()
> >>
> >> The change I try to do there (field = field.title()) is not being
> >> applied
> >
> >
> > Yes it is. field (a local variable) is being replaced by
> > field.title(). You can confirm that by putting
> > print field after the assignment.
> >
> > However I guess you want the change to apply to self.name and
> > self.native_name.
> >
> > Unfortunately you have a list containing the values of self.name and
> > self.native_name. Even if you modified the list elements (which
> > assignment to field does not do) self.name and self.native_name would
> > not be affected.
> >
> > Use getattr and setattr to access and assign the attributes, which you
> > specify by name.
> >
> > def _pre_save(self):
> > for fieldname in ['name', 'native_name']:
> > setattr(self, fieldname) = getattr(self, fieldname).title()
> >
> > [snip]
> >
>This fails:
>SyntaxError: can't assign to function call

Oops me bad. Did not test!  setattr(self, fieldname,  getattr(self, 
fieldname).title())


>Danny Yoo's goes ok
>
>You've the reason: there is no benefit in using "if not field.istitle():"

Is that a question or an appreciation? If question:

It takes execution time to test to see if something is already set. If the 
variables are already set the cost of checking them to avoid assigning then 
is about the same as the cost of just assigning. If the variables are not 
set then the cost of checking and assigning is twice the cost of just 
assigning. Also just assigning is less code to write and maintain. 

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


[Tutor] how to do systematic searching in dictionary and printing it

2005-10-20 Thread Srinivas Iyyer
dear group, 


I have two files in a text format and look this way:


File a1.txt:
>a1
TTAATTGGAACA
>a2
AGGACAAGGATA
>a3
TTAAGGAACAAA



File b1.txt:
>b1
TTAATTGGAACA
>b2
AGGTCAAGGATA
>b3
AAGGCCAATTAA


I want to check if there are common elements based on
ATGC sequences. a1 and b1 are identical sequences and
I want to select them and print the headers (starting
with > symbol). 

a1 '\t' b1



Here:
>X is called header and the line followed by >line
is sequence. In bioinformatics, this is called a FASTA
format.  What I am doing here is, I am matching the
sequences (these are always 25 mers in this instance)
and if they match, I am asking python to write the
header +'\t'+ header


ak = a[1::2]
av = a[::2]
seq_dict = dict(zip(ak,av))

**
>>>seq_dict
{'TTAAGGAACAAA': '>a3', 'AGGACAAGGATA': '>a2',
'TTAATTGGAACA': '>a1'}
**



bv = b[1::2]  

***
>>>bv
['TTAATTGGAACA', 'AGGTCAAGGATA', 'AAGGCCAATTAA']


>>>for i in bv:
if seq_dict.has_key(i):
print seq_dict[i]


>a1

***

Here a1 is the only common element.

However, I am having difficulty printing that b1 is
identical to a1


how do i take b and do this search. It was easy for me
to take the sequence part by doing

b[1::2]. however, I want to print b1 header has same
sequence as a1

a1 +'\t'+b1

Is there anyway i can do this. This is very simple and
due to my brain block, I am unable to get it out. 
Can any one please help me out. 

Thanks





__ 
Yahoo! Mail - PC Magazine Editors' Choice 2005 
http://mail.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] file opening and errors.

2005-10-20 Thread Andrew P
It's not in direct answer to your question, but a real short answer is
"Python doesn't need 'or die' here."  It throws exceptions gleefully
whenever it encounters an error:

>>> f = open('no_such_file')

Traceback (most recent call last):
  File "", line 1, in ?
IOError: [Errno 2] No such file or directory: 'no_such_file'

>>> import os
>>> os.rmdir('/squeak')

Traceback (most recent call last):
  File "", line 1, in ?
OSError: [Errno 41] Directory not empty: '/squeak'

This behavior highlights one of the philosophical differences between
the languages.

Another reversal of stances to keep in mind is that variables are
local by default in Python, and global by default in Perl.

These are also two of my absolute favorite differences.  Silent errors
and global variables never sat well with me.  Die and my are the
general use cases :)

Good luck,

Andrew

On 10/20/05, Dan Klose <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I usually use perl but fancy a bit of a change so have started playing
> with python.
>
> using perl to open a file or directory I usually use:
>
> open(FILE, $file) or die "Error: $!\n";
>
> The $! is a perl variable that holds an error should the open fail,
> example being : "No such file or directory".
>
> With python I have use a try except block but I have no idea how I would
> get the same warning from python as I would from perl (the reason for
> the exception), I am not even sure if this is possible (I assume it must
> be) as google searching has been fruitless.
>
> Thanks for any help, pointers and suggestions.
>
> Dan.
>
> ___
> 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] how to do systematic searching in dictionary and printing it

2005-10-20 Thread Kent Johnson
I would do this by making a dictionary mapping sequence to header for each data 
set. Then make a set that contains the keys common to both data sets. Finally 
use the dictionaries again to look up the headers.

a = '''>a1
TTAATTGGAACA
>a2
AGGACAAGGATA
>a3
TTAAGGAACAAA'''.split()

# Make a dict mapping sequence to header for the 'a' data set
ak = a[1::2]
av = a[::2]
a_dict = dict(zip(ak,av))
print a_dict

b = '''>b1
TTAATTGGAACA
>b2
AGGTCAAGGATA
>b3
AAGGCCAATTAA'''.split()

# Make a dict mapping sequence to header for the 'b' data set
bk = b[1::2]
bv = b[::2]
b_dict = dict(zip(bk,bv))
print b_dict

# Make a set that contains the keys common to both dicts
common_keys = set(a_dict.iterkeys())
common_keys.intersection_update(b_dict.iterkeys())
print common_keys

# For each common key, print the corresponding headers
for common in common_keys:
print '%s\t%s' % (a_dict[common], b_dict[common])
 

Kent

Srinivas Iyyer wrote:
> dear group, 
> 
> 
> I have two files in a text format and look this way:
> 
> 
> File a1.txt:
> 
>>a1
> 
> TTAATTGGAACA
> 
>>a2
> 
> AGGACAAGGATA
> 
>>a3
> 
> TTAAGGAACAAA
> 
> 
> 
> File b1.txt:
> 
>>b1
> 
> TTAATTGGAACA
> 
>>b2
> 
> AGGTCAAGGATA
> 
>>b3
> 
> AAGGCCAATTAA
> 
> 
> I want to check if there are common elements based on
> ATGC sequences. a1 and b1 are identical sequences and
> I want to select them and print the headers (starting
> with > symbol). 
> 
> a1 '\t' b1
> 
> 
> 
> Here:
> 
>>X is called header and the line followed by >line
> 
> is sequence. In bioinformatics, this is called a FASTA
> format.  What I am doing here is, I am matching the
> sequences (these are always 25 mers in this instance)
> and if they match, I am asking python to write the
> header +'\t'+ header
> 
> 
> ak = a[1::2]
> av = a[::2]
> seq_dict = dict(zip(ak,av))
> 
> **
> 
seq_dict
> 
> {'TTAAGGAACAAA': '>a3', 'AGGACAAGGATA': '>a2',
> 'TTAATTGGAACA': '>a1'}
> **
> 
> 
> 
> bv = b[1::2]  
> 
> ***
> 
bv
> 
> ['TTAATTGGAACA', 'AGGTCAAGGATA', 'AAGGCCAATTAA']
> 
> 
> 
for i in bv:
> 
>   if seq_dict.has_key(i):
>   print seq_dict[i]
> 
>   
> 
>>a1
> 
> 
> ***
> 
> Here a1 is the only common element.
> 
> However, I am having difficulty printing that b1 is
> identical to a1
> 
> 
> how do i take b and do this search. It was easy for me
> to take the sequence part by doing
> 
> b[1::2]. however, I want to print b1 header has same
> sequence as a1
> 
> a1 +'\t'+b1
> 
> Is there anyway i can do this. This is very simple and
> due to my brain block, I am unable to get it out. 
> Can any one please help me out. 
> 
> Thanks
> 
> 
> 
>   
>   
> __ 
> 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


Re: [Tutor] file opening and errors.

2005-10-20 Thread Danny Yoo


> open(FILE, $file) or die "Error: $!\n";
>
> The $! is a perl variable that holds an error should the open fail,
> example being : "No such file or directory".
>
> With python I have use a try except block but I have no idea how I would
> get the same warning from python as I would from perl (the reason for
> the exception), I am not even sure if this is possible (I assume it must
> be) as google searching has been fruitless.

Hi Dan,

If we leave off an explicit exception handler, any exceptions that happen
will be considered fatal, and will croak out a stack trace, similar to
what Perl does with its Carp module.

For example:

##
>>> open('/foobar')
Traceback (most recent call last):
  File "", line 1, in ?
IOError: [Errno 2] No such file or directory: '/foobar'
##

In my own programs, I usually don't do exception handling much because I
do want my programs to fail fast and with a visible stack trace --- the
default error message is usually informative enough.  (I'm usually the
only audience for my programs, so having verbose error messages is
acceptable to me.  *grin*)


Best of wishes to you!

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


Re: [Tutor] regular expression matching a dot?

2005-10-20 Thread Hugo González Monteverde
I personally fancy Kiki, that comes with the WxPython installer... It 
has very nice coloring for grouping in Regexes.

Hugo

Kent Johnson wrote:
> Frank Bloeink wrote:
> 
>>There are some nice regex-debuggers out there that can help clearify
>>what went wrong when a regex doesn't match when it should or vice versa.
>>
>>Kodos http://kodos.sourceforge.net/ is one of them, but there are many
>>others that can make your life easier ; at least in terms of
>>regex-debugging ;) 
> 
> 
> Yes, these programs can be very helpful. There is even one that ships with 
> Python - see
> C:\Python24\Tools\Scripts\redemo.py
> 
> Kent
> 
> ___
> 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] file.read..... Abort Problem

2005-10-20 Thread Tomas Markus
Hello Pythoners,

This is probably a very newbie question (after all I am one): 

I am trying to read a file with some 2500 lines and to do a scan for
"not allowed" characters in there (such as accented ones and so on).
The problem is that the file I am testing with has got one of those
somewhere on line 2100 (the hex value of the character is 1a) and all
of the file.read functions (read, readline, readlines) actually stop
reading the file exactly at that line as if it was interpreted as an
EOF. Can you, please, help? Btw: When I am past this problem I will be
asking yet another question: what is the most effective way to check a
file for not allowed characters or how to check it for allowed only
characters (which might be i.e. ASCII only).

Many, many thanks.

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


Re: [Tutor] define vars by iteration

2005-10-20 Thread Danny Yoo


>  Also, I have done what I'm trying to do successfully by populating a
> dictionary with class instances named after self.name ,
> which, after the function runs, I can access this way
>  >>> classDictionary["Yard"]
> 
>  the thing is I would like to be able to get at Yard's attributes by typing
>  >>> Yard.anAttribute
> garbage cans
>  at the prompt rather than
>  >>> Yard = classDictionary["Yard"]
> >>> Yard.anAttribute
> garbage cans


Hi Luke,

One thing to note is that we can formally plunk and embed these places in
some kind of World:

##
class World:
def __init__(self):
self.places = {}
def attach(self, place):
"""Given a place, attaches it to the world."""
self.places[place.name] = place
def lookup(self, name):
return self.places[name]
##


If each place was aware that it was a part of a world --- that is, if we
embed the World inside each place as a part of a place's state --- then
things might work out.

For example, we might have a north-south corridor:

##
class Corridor:
def __init__(self, world, name, northName, southName):
self.world, self.name, self.northName, self.southName = (
world, name, northName, southName)
def N(self):
return self.world.lookup(self.northName)
def S(self):
return self.world.lookup(self.southName)
##

What's a little funny about this Corridor definition is that, because a
cooridor knows its in the world, it can also ask the world what place
'northName' stands for in its N() method.


Here's a small test:

##
>>> world = World()
>>> world.attach(Corridor(world, "Water cooler",
...   north="Stairs", south="Boss Office"))
>>> world.attach(Corridor(world, "Stairs",
...   north="Wall", south="Water cooler"))
>>>
>>>
>>> world.lookup("Water cooler")
<__main__.Corridor instance at 0x403a7fcc>
>>> world.lookup("Water cooler").name
'Water cooler'
>>> world.lookup("Water cooler").N()
<__main__.Corridor instance at 0x403a7f6c>
>>> world.lookup("Water cooler").N().name
'Stairs'
##

Another advantage of having a central place is that saving and restoring
the environment is just a matter of pickling the world.  Hmmm... briny
pickles... *grin* Sorry, I'm getting distracted by food.


Does this make sense?  Please feel free to ask more questions.

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


Re: [Tutor] "Decompile" pyc file

2005-10-20 Thread Kent Johnson
Bernard Lebel wrote:
> Sorry for the late reply.
> 
> Thanks a lot Kent, that was really helpful.

What did you end up doing? I'm interested in what worked for you...

Kent

> 
> 
> Bernard
> 
> 
> 
> On 10/14/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
> 
>>Bernard Lebel wrote:
>>
>>>Hello,
>>>
>>>Is there a way to "decompile" a pyc file? I have a big problem where
>>>the py file was lost, but the pyc file is instact. I would need to
>>>extract the source code from the pyc file.
>>
>>Google 'python decompiler'
>>
>>try http://www.freshports.org/devel/decompyle/
>>or the commercial service at http://www.crazy-compilers.com/decompyle/
>>
>>Kent
>>
>>___
>>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


Re: [Tutor] file.read..... Abort Problem

2005-10-20 Thread Kent Johnson
Tomas Markus wrote:
> Hello Pythoners,
> 
> This is probably a very newbie question (after all I am one):
> 
> I am trying to read a file with some 2500 lines and to do a scan for 
> "not allowed" characters in there (such as accented ones and so on). The 
> problem is that the file I am testing with has got one of those 
> somewhere on line 2100 (the hex value of the character is 1a) and all of 
> the file.read functions (read, readline, readlines) actually stop 
> reading the file exactly at that line as if it was interpreted as an 
> EOF. Can you, please, help?

Are you on windows? Try opening the file in binary mode:

 >>> d='abc\x1adef\nghij\n'
 >>> d
'abc\x1adef\nghij\n'
 >>> open('(temp)/test.txt', 'w').write(d)
 >>> d1=open('(temp)/test.txt').read()
 >>> d1
'abc'
 >>> d1=open('(temp)/test.txt', 'rb').read()
 >>> d1
'abc\x1adef\r\nghij\r\n'

> Btw: When I am past this problem I will be 
> asking yet another question: what is the most effective way to check a 
> file for not allowed characters or how to check it for allowed only 
> characters (which might be i.e. ASCII only).

You can read the file with read() and use a regex to search for unallowed 
characters.

Kent
> 
> Many, many thanks.
> 
> Tom
> 
> 
> 
> 
> ___
> 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] file.read..... Abort Problem

2005-10-20 Thread Danny Yoo


On Thu, 20 Oct 2005, Tomas Markus wrote:

> I am trying to read a file with some 2500 lines and to do a scan for "not
> allowed" characters in there (such as accented ones and so on). The problem
> is that the file I am testing with has got one of those somewhere on line
> 2100 (the hex value of the character is 1a) and all of the
> file.readfunctions (read, readline, readlines) actually stop reading
> the file exactly

Try opening the file in 'binary' mode first: Python assumes that files are
in text format by default.  When it hits an EOF character, that signals
the end of the file if it's in text mode.

We can tell Python to treat a file as binary when we open it.  For
example:

f = open('/usr/share/dict/words', 'rb')

Afterwards, you should be able to look into the entire file.



> what is the most effective way to check a file for not allowed
> characters or how to check it for allowed only characters (which might
> be i.e. ASCII only).

If the file is small enough to fit into memory, you might use regular
expressions as a sledgehammer.  See:

http://www.amk.ca/python/howto/regex/

for a small tutorial on regular expressions.  But unless performance is a
real concern, doing a character-by-character scan shouldn't be too
horrendous.


Best of wishes!

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


Re: [Tutor] file.read..... Abort Problem

2005-10-20 Thread Kent Johnson
Danny Yoo wrote:
> 
> On Thu, 20 Oct 2005, Tomas Markus wrote:
>>what is the most effective way to check a file for not allowed
>>characters or how to check it for allowed only characters (which might
>>be i.e. ASCII only).
> 
> 
> If the file is small enough to fit into memory, you might use regular
> expressions as a sledgehammer.  See:
> 
> http://www.amk.ca/python/howto/regex/
> 
> for a small tutorial on regular expressions.  But unless performance is a
> real concern, doing a character-by-character scan shouldn't be too
> horrendous.

Hi Danny,

I was going to ask why you think regex is a sledgehammer for this one, then I 
decided to try the two alternatives and found out it is actually faster to scan 
for individual characters than to use a regex and look for them all at once!

Here is a program that scans a string for test chars, either using a single 
regex search or by individually searching for the test chars. The test data set 
doesn't include any of the test chars so it is a worst case (neither scan 
terminates early):

# FindAny.py
import re, string

data = string.letters * 2500

testchars = string.digits + string.whitespace
testRe = re.compile('[' + testchars + ']')

def findRe():
return testRe.search(data) is not None

def findScan():
for c in testchars:
if c in data:
return True
return False


and here are the results of timing calls to findRe() and findScan():

F:\Tutor>python -m timeit -s "from FindAny import findRe, findScan" "findRe()"
100 loops, best of 3: 2.29 msec per loop

F:\Tutor>python -m timeit -s "from FindAny import findRe, findScan" "findScan()"
100 loops, best of 3: 2.04 msec per loop

Surprised the heck out of me!

When in doubt, measure! When you think you know, measure anyway, you are 
probably wrong!
Kent

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


[Tutor] is mxDateTime recommended?

2005-10-20 Thread Lance E Sloan
Hello, all.  It's been quite some time since I've sent a message to the 
Python tutor list.

I would like to know if mxDateTime is still the recommended module to use 
for date calculations.  I've been using it for a few years with a set of 
CGIs I had written.  Should I continue to use that, or is there some other 
"preferred" module I should use?

I ask because recently the Webmasters have changed from a Solaris 
environment to a Linux one.  I recompiled the (very) old version of 
mxDateTime I have and it works, but through a process of elimination, I 
found that it is causing a segmentation fault as my program ends.  That is, 
it does all the date manipulation properly, but as the Python interpreter 
terminates (due to a sys.exit() call, implicit end of program, or an error) 
a segmentation fault happens.

I suspect that I could correct this by building a newer version of 
mxDateTime, but I just wanted to be sure that's what I should do before I 
spend the time on it.

Thanks in advance!

--
Lance E Sloan, Systems Research Programmer III
U-M WATS: Web Applications, Technologies, and Solutions
Full-service web and database design, development, and hosting.
http://www.itcs.umich.edu/wats/ - "Putting U on the Web"

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


Re: [Tutor] file.read..... Abort Problem

2005-10-20 Thread Kent Johnson
Kent Johnson wrote:
> Here is a program that scans a string for test chars, either using a single 
> regex search or by individually searching for the test chars. The test data 
> set doesn't include any of the test chars so it is a worst case (neither scan 
> terminates early):
> 
> # FindAny.py
> import re, string
> 
> data = string.letters * 2500
> 
> testchars = string.digits + string.whitespace
> testRe = re.compile('[' + testchars + ']')
> 
> def findRe():
> return testRe.search(data) is not None
> 
> def findScan():
> for c in testchars:
> if c in data:
> return True
> return False
> 
> 
> and here are the results of timing calls to findRe() and findScan():
> 
> F:\Tutor>python -m timeit -s "from FindAny import findRe, findScan" "findRe()"
> 100 loops, best of 3: 2.29 msec per loop
> 
> F:\Tutor>python -m timeit -s "from FindAny import findRe, findScan" 
> "findScan()"
> 100 loops, best of 3: 2.04 msec per loop
> 
> Surprised the heck out of me!

On the other hand, if the number of chars you are searching for is large (and 
unicode?) the regex solution wins:

# FindAny.py (new version)
# From a recipe by Martin v. Löwis, who claims that this regex match is "time 
independent of the number of characters in the class"
# http://tinyurl.com/7jqgt
import re, string, sys

data = string.digits * 2500
data = data.decode('ascii')

uppers = []
for i in range(sys.maxunicode):
  c = unichr(i)
  if c.isupper(): uppers.append(c)
uppers = u"".join(uppers)
uppers_re = re.compile(u'[' + uppers + u']')

def findRe():
return uppers_re.search(data) is not None

def findScan():
for c in uppers:
if c in data:
return True
return False


F:\Tutor>python -m timeit -s "from FindAny import findRe, findScan" "findRe()"
1000 loops, best of 3: 442 usec per loop

F:\Tutor>python -m timeit -s "from FindAny import findRe, findScan" "findScan()"
10 loops, best of 3: 36 msec per loop

Now the search solution takes 80 times as long as the regex!

I'm-a-junkie-for-timings-ly-yrs,
Kent

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


Re: [Tutor] is mxDateTime recommended?

2005-10-20 Thread Kent Johnson
Lance E Sloan wrote:
> Hello, all.  It's been quite some time since I've sent a message to the 
> Python tutor list.
> 
> I would like to know if mxDateTime is still the recommended module to use 
> for date calculations.  I've been using it for a few years with a set of 
> CGIs I had written.  Should I continue to use that, or is there some other 
> "preferred" module I should use?

Since 2.3 Python includes a datetime module which has some facility for date 
calculations. I think mxDateTime is more sophisticated but if your needs are 
simple take a look at datetime.

Kent

> 
> I ask because recently the Webmasters have changed from a Solaris 
> environment to a Linux one.  I recompiled the (very) old version of 
> mxDateTime I have and it works, but through a process of elimination, I 
> found that it is causing a segmentation fault as my program ends.  That is, 
> it does all the date manipulation properly, but as the Python interpreter 
> terminates (due to a sys.exit() call, implicit end of program, or an error) 
> a segmentation fault happens.
> 
> I suspect that I could correct this by building a newer version of 
> mxDateTime, but I just wanted to be sure that's what I should do before I 
> spend the time on it.
> 
> Thanks in advance!
> 
> --
> Lance E Sloan, Systems Research Programmer III
> U-M WATS: Web Applications, Technologies, and Solutions
> Full-service web and database design, development, and hosting.
> http://www.itcs.umich.edu/wats/ - "Putting U on the Web"
> 
> ___
> 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] file.read..... Abort Problem

2005-10-20 Thread Danny Yoo

> I was going to ask why you think regex is a sledgehammer for this one,

Regex's are more complex because we have to then make sure that none of
the testchars have any special meaning as regular expression
metacharacters. If one of those test chars, for example, contained things
like '-' or '\\', we'd have to know to use re.escape() to be safe about
things.

Once we know regex's (and have been bitten by forgetting those issues...
*grin*), then these factors aren't so large.

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


[Tutor] Time - sum/difference

2005-10-20 Thread Jonas Melian
I would get the local time of a country, using UTC (Universal Time 
Coordinated) and DST (Daylight SavingTime) of that country.

An example, utc time -02:30 and dst +1 :

country_utc = datetime.time(2,30)
isUTCNegative = True
dst = datetime.time(1,0)

Now I would the difference of both times.
-02:30 + 01:00 -> -01:30

Is possible get sum/difference of time values? How?

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


[Tutor] greetings...

2005-10-20 Thread carl.badgley
Greetings to list,

Tomorrow is my last day in class with Lutz.  I am not only new to
Python but new to programming in general, this is my first language. 
Looking forward to your help in the days and weeks to come.

Any suggestions for self tutorial, whether on python.org or not, would
be greatly appreciated.  I am going to finish his Learning... book
first then hack open some open code for a simple project in order to
see how it works.

peace

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


Re: [Tutor] is mxDateTime recommended?

2005-10-20 Thread John Fouhy
On 21/10/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Since 2.3 Python includes a datetime module which has some facility for date
> calculations. I think mxDateTime is more sophisticated but if your needs are 
> simple take
> a look at datetime.

The only significant difference I've come across is that mxDateTime
has a .strptime() function (for parsing a string like "10/12/2005"),
and python DateTime doesn't (so you have to go via the time module).

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


[Tutor] Help(!) with OOP/Composition from "Learning Python"

2005-10-20 Thread Andrew P
I've been reading about composition vs inheritance, and went back to
"Learning Python" to look at something I found very confusing a year
ago.  Turns out I still find it very confusing :)

The code at the bottom was taken from the OOP chapter, it's a solution
to one of the end-of-chapter problems.

Honestly, this toy program is enough to make my head spin.  Am I too
stupid for OOP?  Here is me trying to decipher it:

 Starting here:

x = Lunch(  )   # Self-test code
x.order('burritos') # If run, not imported

You have to look at the method of class Lunch:

def order(self, foodName):  # Start a Customer order simulation.
self.cust.placeOrder(foodName, self.empl)

check the instance name:

self.cust = Customer(  )

to see what class it belongs to, jump to class Customer, look up the
method being called:

 def placeOrder(self, foodName, employee):  # Place order with Employee.
self.food = employee.takeOrder(foodName)

 which uses employee as an argument, which was, looking back up, an
instance of class Employee:

class Employee:
def takeOrder(self, foodName):# Return a Food, with requested name.
return Food(foodName)

which seems to return an instance of food?  I don't really understand
that,  but I've already forgotten what it was I started off looking to
find :)

x.result(  )

Which is just entirely too much for my brain to hold at once.  I'm
sorry if this sounds like whining, but this entire program seems as
bad as trying to decipher the GOTO-crazy scribblings of a lunatic. 
There is no linearity, and the extra abstraction of the classes just
adds another layer of complexity.  Instead of functions and arguments
there are methods, classes, and instances being passed about
willy-nilly and no (for me) easy way to follow the path or make sense
of it.

Is this just an example of a technique with a constant complexity
factor that looks ridiculous on a toy program, but very quickly
becomes useful on larger ones?  Are there tools that make reading
something like this more clear?

Thanks,

Andrew


#
# lunch program
#

class Lunch:
def __init__(self):# Make/embed Customer and Employee.
self.cust = Customer(  )
self.empl = Employee(  )
def order(self, foodName):  # Start a Customer order simulation.
self.cust.placeOrder(foodName, self.empl)
def result(self):   # Ask the Customer about its Food.
self.cust.printFood(  )

class Customer:
def __init__(self): # Initialize my food to None.
self.food = None
def placeOrder(self, foodName, employee):  # Place order with Employee.
self.food = employee.takeOrder(foodName)
def printFood(self):   # Print the name of my food.
print self.food.name

class Employee:
def takeOrder(self, foodName):# Return a Food, with requested name.
return Food(foodName)

class Food:
def __init__(self, name):  # Store food name.
self.name = name

if __name__ == '__main__':
x = Lunch(  )   # Self-test code
x.order('burritos') # If run, not imported
x.result(  )
x.order('pizza')
x.result(  )
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pytunes (Was __slots__, struct, etc.)

2005-10-20 Thread John Fouhy
Hmm, neat. I don't have any feedback for you on your code, but since
you're working with this sort of thing, I have a puzzle for you:

Suppose you have a collection of MP3 files.  You want to build a
random playlist, subject to the condition that tracks by the same
artist are as far apart as possible.  You can assume you have the
track / artist data in any structure you like.  How would you do this?

(I have a solution, but I don't think it is optimal.  In fact, I'm not
sure how to actually define "optimal" here... And so I am interested
in how other people would solve this problem :-) )

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


[Tutor] PYBSDDB help

2005-10-20 Thread Valone, Toren W.
I am creating my Db with this code

 def open_db(self):
self.cadmvinfo.open(self.filename, db.DB_HASH,
db.DB_CREATE,db.DB_DUP)

I am putting the data with this code


def
store_data(self,manual_processing_code,date,file_code,license_number,vin_num
ber,
   year_model,make,user_info,End_Usr_ac):
print "storing data..."
self.cadmvinfo.put("manual_processing_code",manual_processing_code)
self.cadmvinfo.put("date" ,date)
self.cadmvinfo.put("filecode" ,file_code)
self.cadmvinfo.put("licensenumber" ,license_number)
self.cadmvinfo.put("vinnumber" ,vin_number)
self.cadmvinfo.put("yearmodel" ,year_model)
self.cadmvinfo.put("make" ,make)
self.cadmvinfo.put("userinfo" ,user_info)
self.cadmvinfo.put("EndUsrac" ,End_Usr_ac)


but I still cannot get it to store duplicate keys (in other words I
overwrite the data over and over)

I know it is something simple, but cannot put my finger on it.
Help!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PYBSDDB help

2005-10-20 Thread Danny Yoo

Hi Toren,

Ok, I see that you've asked your question on the pybsddb mailing list as
well a few weeks ago, which is fine.

http://lists.sourceforge.net/lists/listinfo/pybsddb-users

Unfortunately, it looks like spammers have attacked that mailing list
badly enough that it appears they've done severe damage to that community
there


We'll do what we can to help.  Your call to open():

self.cadmvinfo.open(self.filename, db.DB_HASH,
db.DB_CREATE,db.DB_DUP)

appears to be the culprit.

I see that you're trying to db.DB_CREATE and db.DB_DUP as flags.  I would
have expected to see something like:

db.DB_CREATE | db.DB_DUP

because flags are traditionally combined by using bitwise arithmetic.


However, DB_DUP is not a flag that should be passed off to the open()
function anyway.  I suspect that your problems stem from this, since if we
don't call open() with the right arguments, then pybsddb won't do what you
want.



Let's ignore the DB_DUP stuff for the moment.  According to:

http://pybsddb.sourceforge.net/bsddb3.html

the method signature for open() is:

open(filename, dbname=None, dbtype=DB_UNKNOWN, flags=0, mode=0660)

so if we're going to provide arguments that override the defaults, we'll
want to be explicit in which arguments we'ere overriding.  Rather than:

self.cadmvinfo.open(self.filename, db.DB_HASH,
db.DB_CREATE)

Try:

self.cadmvinfo.open(self.filename,
dbtype=db.DB_HASH,
flags=db.DB_CREATE)

where we explictely say which arguments go where.  That way, we have no
possiblity of accidently putting db.DB_HASH into the place where open()
expects a database name.


According to:

http://pybsddb.sourceforge.net/api_c/db_open.html

I don't see DB_DUP being a flag option that we pass into open().  Instead,
I see it as an option to set_flags() instead:

http://pybsddb.sourceforge.net/api_c/db_set_flags.html


So the following will probably do what you want:

self.cadmvinfo.set_flags(db.DB_DUP)
self.cadmvinfo.open(self.filename,
dbtype=db.DB_HASH,
flags=db.DB_CREATE)

This matches the usage in the test case examples in
bsddb/test/test_basics.py in the pybsddb source distribution.


Do you have any questions on this so far?

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


Re: [Tutor] Help(!) with OOP/Composition from "Learning Python"

2005-10-20 Thread Alan Gauld
> I've been reading about composition vs inheritance, and went back to
> "Learning Python" to look at something I found very confusing a year
> ago.  Turns out I still find it very confusing :)

I don;t know the example but from the snippetts you've posted it doresn't 
look like a particularly good example of OOD. So that won't help. 
However its not a terrible example either...

> Am I too stupid for OOP?  

Definitely not but for some people OOP is not as naturally intuitive as it 
is to others. For some reason those with a background in math seem 
to find OOP less intuitive, I dunno if that applies to you though :-)

WHen OOP first appeared several studies suggestedit took between 
6 months to 2 years for an established non OOP programmer to fully 
"convert" to OOP whereas complete newbies picke it up in less 
than 3 months... So much of the effort comes in unlearning old habits.

x = Lunch(  )   # Self-test code
x.order('burritos') # If run, not imported

Pesonally Lunch is a strange name for a class and order() is not an 
operation I'd assosiate with a lunch object - eat() maybe! These 
are the kind of design issues I referred to above.

 >   def order(self, foodName):  # Start a Customer order simulation.
 >   self.cust.placeOrder(foodName, self.empl)

Again a weird design decision, I wouldn't expect to place an order 
with a customer, I'd expect that to be on the waiter object. I would 
expect to see a customer send a messaage to a waiter asking to place 
an order for a Lunch And the Lunch would comprise several 
courses/foodstuffs. Again a weird OO design IMHO.

> def placeOrder(self, foodName, employee):  # Place order with Employee.
>self.food = employee.takeOrder(foodName)

Now here we have the empoyee taking the order, that makes more sense.

> x.result(  )

And what exactly a Lunch object doesin response to a result message 
I have no idea, again a badly chosen method IMHO.

> Which is just entirely too much for my brain to hold at once.  

Absolutely. You are not supposed to try to follow the chain of command 
to the bottom, you are supposed to work with theobjects as stand alone 
mini programs. YOu don;t think about how they work inside any more 
than you read the Python interpreter source code every time you call it 
(I assume you don't do that???!) Objects are tested independantly and 
thereafter we just trust them to do what they claim to do.

> bad as trying to decipher the GOTO-crazy scribblings of a lunatic. 

Not so because at least there can be no returns from the middle of 
blocks etc...

> There is no linearity, and the extra abstraction of the classes just
> adds another layer of complexity.  

You are right that there is no linearity. Thats one characterisatic of an 
OOP programme. The structure is a directed graph of object 
relationships with messages passing between objects along the 
connecting lines. It is not a heirarchical tree structuire as found 
in structured programming.

> Instead of functions and arguments there are methods, classes, 
> and instances being passed about willy-nilly 

There should be messages which include objects as their arguments.
Its important to conceptually separate messages from methods. We 
send a message to an object and it responds by executing a method 
- which method we mauy not know(this is polymorphism!) - and we 
get a result back. We pass objects around so that the receiving object 
can call methods of that object - this is somewhat akin to passing 
function pointers or lambdas in more traditional languages.

> no (for me) easy way to follow the path or make sense of it.

You cannot easily do that without specialised debuggers such 
as "Look!" etc OOP works on the assumption that you debug 
one object at a time and rarely need to follow the code to 
understand whats happening. In the example given it looks like 
the object lattice and method names are not too intuitive.

> Is this just an example of a technique with a constant complexity
> factor that looks ridiculous on a toy program, but very quickly
> becomes useful on larger ones?  

Thereis a huge amount of trith in that too. I rarely use OOP on 
programs of less than 50 -100 lines but beyond that size and 
the use of OOP really kicks in. By the time you have 
10,000+ lines OOP becomes very powerful.

> Are there tools that make reading something like this more clear?

There are many tools but most are commercial. I mentioned the 
Look! debugger for C++/Java and SmallTalk. Borland and Microsoft 
both provide message visualisation tools too. Many OOD CASE tools
provide simulation tools for testing s design prior to generating code.

Don't give up hope but rather try to live in faith for a spell.
Ty to find some other examples of Python OOP too, I don;t personally 
like the look of the Lunch example. One of the key features of a good 
OOP programme is that each object should have clear reponsibilities
and those shoul

Re: [Tutor] file.read..... Abort Problem (fwd)

2005-10-20 Thread Danny Yoo
[Keeping tutor in CC]

-- Forwarded message --
Date: Thu, 20 Oct 2005 23:21:13 +0200
From: Tomas Markus <[EMAIL PROTECTED]>
To: Danny Yoo <[EMAIL PROTECTED]>
Subject: Re: [Tutor] file.read. Abort Problem

Hi All,

Just to let you know my ressults (+ one tiny question :-):
I did a bit of investigation and narrowed the "invalid" characters group to
jus one the hex 1a. My code now looks quite small:

fpath = 'c:\\pytemp\\bafir550.edi'
fl = file(fpath, 'rb')
print 'Checking file %s' % fpath
x=0
for line in fl.readlines():
x=x+1
if "" in line:
print 'Not allowed chars at line %s --- %s' % (x,line),
print "The check finished on line %s which was %s" % (x,line)

The only proble is tha in the if clause there actually is the hex 1a
character. The code works when executed from idle but when I run it from
command line, I get:

File "c:\Apps\PTOOLS\payfiles\editest.py", line 7
if "
^
SyntaxError: EOL while scanning single-quoted string

Is there any workaround?

Thanks Tom

On 20/10/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
>
>
> > I was going to ask why you think regex is a sledgehammer for this one,
>
> Regex's are more complex because we have to then make sure that none of
> the testchars have any special meaning as regular expression
> metacharacters. If one of those test chars, for example, contained things
> like '-' or '\\', we'd have to know to use re.escape() to be safe about
> things.
>
> Once we know regex's (and have been bitten by forgetting those issues...
> *grin*), then these factors aren't so large.
>
> ___
> 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] Time - sum/difference

2005-10-20 Thread Kent Johnson
Jonas Melian wrote:
> I would get the local time of a country, using UTC (Universal Time 
> Coordinated) and DST (Daylight SavingTime) of that country.
> 
> An example, utc time -02:30 and dst +1 :
> 
> country_utc = datetime.time(2,30)
> isUTCNegative = True
> dst = datetime.time(1,0)
> 
> Now I would the difference of both times.
> -02:30 + 01:00 -> -01:30
> 
> Is possible get sum/difference of time values? How?

I'm not exactly sure what you are looking for, but you can subtract 
datetime.datetime instances. If you are trying to find the difference between 
local time and utc this is one way:

 >>> import datetime as dt
 >>> dt.datetime.now()
datetime.datetime(2005, 10, 20, 19, 41, 30, 393000)
 >>> dt.datetime.utcnow()
datetime.datetime(2005, 10, 20, 23, 41, 52, 195000)
 >>> dt.datetime.utcnow()-dt.datetime.now()
datetime.timedelta(0, 14400)

though there is a race condition here that might give you an error of a 
millisecond sometimes.

Kent

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


Re: [Tutor] file.read..... Abort Problem (fwd)

2005-10-20 Thread Kent Johnson
> From: Tomas Markus <[EMAIL PROTECTED]>
> Just to let you know my ressults (+ one tiny question :-):
> I did a bit of investigation and narrowed the "invalid" characters group to
> jus one the hex 1a. My code now looks quite small:
> 
> fpath = 'c:\\pytemp\\bafir550.edi'
> fl = file(fpath, 'rb')
> print 'Checking file %s' % fpath
> x=0
> for line in fl.readlines():
> x=x+1
> if "" in line:
> print 'Not allowed chars at line %s --- %s' % (x,line),
> print "The check finished on line %s which was %s" % (x,line)
> 
> The only proble is tha in the if clause there actually is the hex 1a
> character. 

You don't have to type an actual 1a character to get it into a Python string. 
You can use special character escapes instead. To put a hex value into a 
string, use the escape \x followed by the two hex digits. So your test can be
  if "\x1a" in line:

This way there is no actual 1a character in your program, but it will still do 
what you want.

Kent

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


Re: [Tutor] Help(!) with OOP/Composition from "Learning Python"

2005-10-20 Thread Andrew P
Hi Alan, thanks for taking the time to answer so thoroughly.  I've
responded to a few things below.   But let me say right off I have
gone through the OOP section in your excellent tutor.  It was one of
my main resources learning Python.  I actually have Bertand Meyer's
book here (and have written a couple small programs in Eiffel!) based
on your recommendation, but I think my main confusion is stemming from
composition vs inheritance, and it's effect on program
readability/understandability.  I went to "Learning Python" looking
for that composition example trying to make things a little more
concrete.

On 10/20/05, Alan Gauld <[EMAIL PROTECTED]> wrote:

> However its not a terrible example either...
>
> > Am I too stupid for OOP?
>
> Definitely not but for some people OOP is not as naturally intuitive as it
> is to others. For some reason those with a background in math seem
> to find OOP less intuitive, I dunno if that applies to you though :-)

I was referring specifically to being able to follow how the classes
interacted to obtain the results.  I know that objects interact
dynamically at runtime, so there may only be so much I can infer, but
I am trying to read code to get an idea of how to write it, and it was
discouraging to be stymied by an example from "Learning Python",
especially a do-nothing example..

> Absolutely. You are not supposed to try to follow the chain of command
> to the bottom, you are supposed to work with theobjects as stand alone
> mini programs. YOu don;t think about how they work inside any more
> than you read the Python interpreter source code every time you call it
> (I assume you don't do that???!) Objects are tested independantly and
> thereafter we just trust them to do what they claim to do.

How does this relate to composition vs inheritance?  When you have
multiple classes composed of multiple parts of multiple other classes,
doesn't that freeze your interface decisions early on?  It seems to
really tightly bind classes together.  I think I just need to track
down a real-world example, maybe.  This was probably the wrong one to
choose.  I just can't picture how it would even be possible to write
and grow.

Inheritance, subclassing, and overloading are much simpler concepts,
and relatively straightforward to read, at any rate, ignoring design
issues :)  You can point to a class and say ok, this is inheriting
that class's methods, or overloading an abstract class.  Perhaps it's
just the interaction between classes that is giving me a problem.

> > Instead of functions and arguments there are methods, classes,
> > and instances being passed about willy-nilly
>
> There should be messages which include objects as their arguments.
> Its important to conceptually separate messages from methods. We
> send a message to an object and it responds by executing a method
> - which method we mauy not know(this is polymorphism!) - and we
> get a result back. We pass objects around so that the receiving object
> can call methods of that object - this is somewhat akin to passing
> function pointers or lambdas in more traditional languages.
>

I should have been more clear here, as well.  I was talking more
specifically about the example as composition.  I think I am just
missing something conceptually.  I've written basic classes for myself
before that just bundle logic and state, and I think they were
reasonable choices for objects.  But really it was just a way to
interact with an object procedurally, like I do every day with Python.

I'm just not sure how to organize the piecemeal composition of new
classes from existing ones, in any sensical way.  Or for that matter,
how to arrange a bundle of classes with no "leader" :)  Speaking of
structural programming biases.  But at least I recognize that hurdle,
and can see how it would be possible.

> At risk of too much blatant self promotion try the OOP topic in my tutor.
> Also try reading through the Games framework (hmgui.zip) that I submitted
> to Useless Python (or is described in the paper book version of my tutor)
>

Well, that sounds like a real-world example I can look at :)  Thanks
again for your time, Alan.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Dynamic Function Assignment

2005-10-20 Thread Greg Lindstrom
Hello-

Suppose I have three objects...

a = MyObject(id=1)
b = MyObject(id=2)
c = MyObject(id=3)

As I read in segments from my file, I need to choose one of the above based on the segment, something like this;

segment = 'A Segment to Process'

for id, S in (('A',a), ('B',b), ('C',c)):
  if segment.upper().startswith(id):
    S.DoSomething(segment)

That is, I want to associate an object to work with a condition on the
input segment (there are dozens of segment types and very large files
to process).  But I'd like to clean up the "for" statement and
have something like this:

for id in ('A', 'B', 'C'):
   if segment.upper().startswith(id):
  ??how can I select the correct object here with a big "if" statement??

The routine works fine as is, but if I can clean up the syntax I will
be able to configure the application via a database; very attractive
because I can process all of the records with one fairly small (~500
line) routine.


Thanks for your consideration...
--greg
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dynamic Function Assignment

2005-10-20 Thread John Fouhy
On 21/10/05, Greg Lindstrom <[EMAIL PROTECTED]> wrote:
>  Suppose I have three objects...
>
>  a = MyObject(id=1)
>  b = MyObject(id=2)
>  c = MyObject(id=3)
>
>  segment = 'A Segment to Process'
>
>  for id in ('A', 'B', 'C'):
> if segment.upper().startswith(id):
>??how can I select the correct object here with a big "if"
> statement??

Perhaps a dictionary?

Something like:

myObjects = { 'A':MyObject(id=1), 'B':MyObject(id=2), 'C':MyObject(id=3) }
for c in ('A', 'B', 'C'):
  if segment.upper().startswith(c):
myObjects[c].doSomething(segment)

If your MyObject instances are going to be constructed in a systematic
way, then you could simplify your definition of myObjects a bit more. 
Eg:

objectData = [('A', 1), ('B', 2), ('C', 3)] # etc
myObjects = dict([(c, MyObject(id=id)) for c, id in objectData])

Hope this helps!

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


Re: [Tutor] Dynamic Function Assignment

2005-10-20 Thread Kent Johnson
John Fouhy wrote:
> On 21/10/05, Greg Lindstrom <[EMAIL PROTECTED]> wrote:
> 
>> Suppose I have three objects...
>>
>> a = MyObject(id=1)
>> b = MyObject(id=2)
>> c = MyObject(id=3)
>>
>> segment = 'A Segment to Process'
>>
>> for id in ('A', 'B', 'C'):
>>if segment.upper().startswith(id):
>>   ??how can I select the correct object here with a big "if"
>>statement??
> 
> Something like:
> 
> myObjects = { 'A':MyObject(id=1), 'B':MyObject(id=2), 'C':MyObject(id=3) }
> for c in ('A', 'B', 'C'):
>   if segment.upper().startswith(c):
> myObjects[c].doSomething(segment)

This can be simplified even further to something like
key = segment[0].upper()
myObjects[key].doSomething(segment)

This will raise an exception if segment doesn't start with A, B or C. But the 
idea is that once you have a dictionary you can look up segment directly.

To handle the exception you can use a try/except block or use a default handler.

Kent

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


Re: [Tutor] "Decompile" pyc file

2005-10-20 Thread Johan Geldenhuys




When I want to download the zip file from the source, I get the error
that the page does not exist. Where can I get it?

Thanx.

Bernard Lebel wrote:

  Sorry for the late reply.

Thanks a lot Kent, that was really helpful.


Bernard



On 10/14/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
  
  
Bernard Lebel wrote:


  Hello,

Is there a way to "decompile" a pyc file? I have a big problem where
the py file was lost, but the pyc file is instact. I would need to
extract the source code from the pyc file.
  

Google 'python decompiler'

try http://www.freshports.org/devel/decompyle/
or the commercial service at http://www.crazy-compilers.com/decompyle/

Kent

___
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


[Tutor] How do I recursively remove the contents of a directory??

2005-10-20 Thread Suri Chitti








If I have a directory /u01/qa/logs and the
logs has a number of children directories and I want to remove everything in
logs and logs itself, is there a single method or command to do that?  I want
to avoid recursively removing the files in each child directory and so on.

 






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