Re: [Tutor] Memory consumption question

2007-11-15 Thread Marc Tompkins
Sorry, sloppy cutting and pasting.  Should be:

Referring to the original post:
>
> > >>> dir(A)
> > ['__doc__', '__module__']
> > >>> dir(B)
> > ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',
> > '__hash__', '__init__', '__module__', '__new__', '__reduce__',
> > '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__']
> >
> >
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Memory consumption question

2007-11-15 Thread Marc Tompkins
Referring to the original post:

> >>> dir(B)
> ['__doc__', '__module__']
> >>> dir(B)
> ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',
> '__hash__', '__init__', '__module__', '__new__', '__reduce__',
> '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__']
>
>

On Nov 15, 2007 6:50 PM, Kent Johnson <[EMAIL PROTECTED]> wrote:

> OK, the analogy is cute, but I really don't know what it means in
> Python. Can you give an example? What are the parts of an old-style
> class that have to be 'ordered' separately? How do you 'order' them
> concisely with a new-style class?
>
> Thanks,
> Kent
>
> Marc Tompkins wrote:
> > I thought of an analogy I like better than my sign-painting one:
> > ordering a sandwich.
> > Imagine: you're at the deli, and your waitron asks what you want.
> > (Granted, this is a silly example.)
> >   "Classic" order: "I'd like a sandwich with two slices of rye bread,
> > Russian dressing, corned beef, and Swiss cheese.  Oh, and I'd like that
> > grilled."
> >   "New-style" order: "Reuben, please."
> >
> > Now, I speak not of the time and materials required to construct the
> > above-mentioned tasty treat - in my analogy, Python is the
> > long-suffering waitron, not the cook - but I gotta figure that the
> > second option will take less space to write on the check.  Perhaps about
> > 134 bytes' worth.
>



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


Re: [Tutor] Memory consumption question

2007-11-15 Thread Kent Johnson
OK, the analogy is cute, but I really don't know what it means in 
Python. Can you give an example? What are the parts of an old-style 
class that have to be 'ordered' separately? How do you 'order' them 
concisely with a new-style class?

Thanks,
Kent

Marc Tompkins wrote:
> I thought of an analogy I like better than my sign-painting one: 
> ordering a sandwich. 
> Imagine: you're at the deli, and your waitron asks what you want.  
> (Granted, this is a silly example.)
>   "Classic" order: "I'd like a sandwich with two slices of rye bread, 
> Russian dressing, corned beef, and Swiss cheese.  Oh, and I'd like that 
> grilled." 
>   "New-style" order: "Reuben, please."
> 
> Now, I speak not of the time and materials required to construct the 
> above-mentioned tasty treat - in my analogy, Python is the 
> long-suffering waitron, not the cook - but I gotta figure that the 
> second option will take less space to write on the check.  Perhaps about 
> 134 bytes' worth.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Memory consumption question

2007-11-15 Thread Eric Brunson

I'm sorry, but a Reuben with no 'kraut is just a corned beef sandwich.  :-)

Marc Tompkins wrote:
> And here's another reason to use new-style:  I forgot the sauerkraut!  
> Oh, the horror!
>
> On Nov 15, 2007 1:42 PM, Marc Tompkins <[EMAIL PROTECTED] 
> > wrote:
>
> I thought of an analogy I like better than my sign-painting one:
> ordering a sandwich. 
> Imagine: you're at the deli, and your waitron asks what you want. 
> (Granted, this is a silly example.)
>   "Classic" order: "I'd like a sandwich with two slices of rye
> bread, Russian dressing, corned beef, and Swiss cheese.  Oh, and
> I'd like that grilled." 
>   "New-style" order: "Reuben, please."
>
> Now, I speak not of the time and materials required to construct
> the above-mentioned tasty treat - in my analogy, Python is the
> long-suffering waitron, not the cook - but I gotta figure that the
> second option will take less space to write on the check.  Perhaps
> about 134 bytes' worth.
>
> For some reason I'm hungry now...
>
>
> On Nov 15, 2007 11:22 AM, Kent Johnson <[EMAIL PROTECTED]
>  > wrote:
>
> Marc Tompkins wrote:
> > I didn't mean that exactly literally - for goodness' sake,
> this is a
> > high-level, object-oriented, interpreted language!  We're
> not writing
> > machine language here.
>
> Yes, I was thinking I should re-word my email, it was worded a
> bit too
> strongly...
>
> > What I did mean, and will probably still not express as
> clearly as I'd
> > like, is that when you create a "classic" class, lots of
> options remain
> > unresolved - slots vs. dict comes to mind - and Python needs
> to reserve
> > extra space accordingly.   About 134 extra bytes, it would
> appear.
>
> Still not sure I know what you mean. AFAIK old-style classes
> don't
> support slots, at least not user-defined slots. I do remember
> talk of
> new-style classes and properties allowing a much cleaner
> implementation
> of the class mechanisms, and it seems plausible that such
> generalization
> would lead to fewer options and streamlining of the class
> structure, but
> I don't know enough about the specifics to know if that is right.
>
> I poked around a bit in the source to see if I could figure it
> out but
> got tired of trying to sift through the header files...
>
> Kent
> >
> > On Nov 15, 2007 9:32 AM, Kent Johnson <[EMAIL PROTECTED]
> 
> > >> wrote:
> >
> > Marc Tompkins wrote:
> >
> >  > class B is a "new-style' class, meaning that it
> inherits from a base,
> >  > pre-existing class (in this case "object", which is
> as basic and
> > generic
> >  > as you can get!).  class A has to start from nothing,
> which is why it
> >  > consumes more memory yet has less functionality.
> >
> > I don't think it is really accurate to say that an
> old-style class
> > "starts from nothing". It doesn't have an explicit base
> class but it
> > does have all the old-style class machinery which is
> built in to Python.
> >
> > I don't know why new-style classes are smaller though.
> My guess is that
> > it is because there was an opportunity to streamline the
> class structure
> > based on experience.
> >
> > Kent
> >
> >
> >
> >
> > --
> > www.fsrtechnologies.com  <
> http://www.fsrtechnologies.com>
>
>
>
>
> -- 
> www.fsrtechnologies.com  
>
>
>
>
> -- 
> www.fsrtechnologies.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] Memory consumption question

2007-11-15 Thread Marc Tompkins
And here's another reason to use new-style:  I forgot the sauerkraut!  Oh,
the horror!

On Nov 15, 2007 1:42 PM, Marc Tompkins <[EMAIL PROTECTED]> wrote:

> I thought of an analogy I like better than my sign-painting one: ordering
> a sandwich.
> Imagine: you're at the deli, and your waitron asks what you want.
> (Granted, this is a silly example.)
>   "Classic" order: "I'd like a sandwich with two slices of rye bread,
> Russian dressing, corned beef, and Swiss cheese.  Oh, and I'd like that
> grilled."
>   "New-style" order: "Reuben, please."
>
> Now, I speak not of the time and materials required to construct the
> above-mentioned tasty treat - in my analogy, Python is the long-suffering
> waitron, not the cook - but I gotta figure that the second option will take
> less space to write on the check.  Perhaps about 134 bytes' worth.
>
> For some reason I'm hungry now...
>
>
> On Nov 15, 2007 11:22 AM, Kent Johnson <[EMAIL PROTECTED]> wrote:
>
> > Marc Tompkins wrote:
> > > I didn't mean that exactly literally - for goodness' sake, this is a
> > > high-level, object-oriented, interpreted language!  We're not writing
> > > machine language here.
> >
> > Yes, I was thinking I should re-word my email, it was worded a bit too
> > strongly...
> >
> > > What I did mean, and will probably still not express as clearly as I'd
> > > like, is that when you create a "classic" class, lots of options
> > remain
> > > unresolved - slots vs. dict comes to mind - and Python needs to
> > reserve
> > > extra space accordingly.   About 134 extra bytes, it would appear.
> >
> > Still not sure I know what you mean. AFAIK old-style classes don't
> > support slots, at least not user-defined slots. I do remember talk of
> > new-style classes and properties allowing a much cleaner implementation
> > of the class mechanisms, and it seems plausible that such generalization
> >
> > would lead to fewer options and streamlining of the class structure, but
> > I don't know enough about the specifics to know if that is right.
> >
> > I poked around a bit in the source to see if I could figure it out but
> > got tired of trying to sift through the header files...
> >
> > Kent
> > >
> > > On Nov 15, 2007 9:32 AM, Kent Johnson <[EMAIL PROTECTED]
> > > > wrote:
> > >
> > > Marc Tompkins wrote:
> > >
> > >  > class B is a "new-style' class, meaning that it inherits from a
> > base,
> > >  > pre-existing class (in this case "object", which is as basic
> > and
> > > generic
> > >  > as you can get!).  class A has to start from nothing, which is
> > why it
> > >  > consumes more memory yet has less functionality.
> > >
> > > I don't think it is really accurate to say that an old-style class
> > > "starts from nothing". It doesn't have an explicit base class but
> > it
> > > does have all the old-style class machinery which is built in to
> > Python.
> > >
> > > I don't know why new-style classes are smaller though. My guess is
> > that
> > > it is because there was an opportunity to streamline the class
> > structure
> > > based on experience.
> > >
> > > Kent
> > >
> > >
> > >
> > >
> > > --
> > > www.fsrtechnologies.com < http://www.fsrtechnologies.com>
> >
> >
>
>
> --
> www.fsrtechnologies.com




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


Re: [Tutor] class accessing another's updated property

2007-11-15 Thread Alan Gauld
"Alan Gauld" <[EMAIL PROTECTED]> wrote 
> 
> class Master:
> 
> class PublishedMaster(Master):
> 
> class client:
> 
> This allows the subscriber classes to be informed of any changes

I should have pointed out that the code I posted was not tested
and should be treated as pseudo code - albeit very close to 
real code! 

Alan G.

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


Re: [Tutor] manipulating data

2007-11-15 Thread Tiger12506
If you run this code

#
f = open('test1.mlc')
for line in f:
print f.split()
#

You will see that about halfway through the file there is an empty list. I
assume that there was nothing on that line, in which case, there is no [0]
value.
In which case, you need to put in a try: except IndexError:  block like
this~

f = open('test1.mlc')
fields={}
for line in f:
try:
words = line.split()
firstword = words[0]
except IndexError: continue

if firstword == 'Field':
field = int(words[-1])
elif firstword == 'Leaf':
fields[field] = words[-1]


You will notice I made a few other changes. I changed it so line.split() is
assigned to a variable. That means I don't have to make the split() call
every time I want to check for a different word. The try except block just
fixes the problem you encountered. Also, I took out the last block-the else
block-because it is not necessary, and in fact will cause what you would
consider an error in the program. Calling f.next() will increment the line,
yes, but that is exactly for what the "for loop" is intended. The natural
conclusion of the for block is "finish the elif test and its block, then
execute code after it. Since there is no code after it indented to that
level, it automatically increments 'line' (line = f.next())

HTH,
JS


- Original Message - 
From: "Bryan Fodness" <[EMAIL PROTECTED]>
To: "Alan Gauld" <[EMAIL PROTECTED]>
Cc: 
Sent: Monday, November 12, 2007 2:43 PM
Subject: Re: [Tutor] manipulating data


>I try this,
>
> f = open('TEST1.MLC')
>
> fields = {}
>
> for line in f:
>if line.split()[0] == 'Field':
>field = int(line.split()[-1])
>elif line.split()[0] == 'Leaf':
>fields[field] = line.split()[-1]
>else:
>line = f.next()
>
> and get,
>
> Traceback (most recent call last):
>  File "", line 1, in 
>line.split()[0]
> IndexError: list index out of range
>
> I have attached my data file.
>





> ___
> 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] width

2007-11-15 Thread bhaaluu
In pack() add:
expand=YES, fill=X,
expand=YES, fill=Y
or
expand=YES, fill=BOTH

Example:

from Tkinter import *
root = Tk()
Button(root, text='Red', bg="red", fg="white",
command=root.quit).pack(expand=YES,fill=X)
Button(root, text='Green', bg="green", fg="white",
command=root.quit).pack(expand=YES,fill=Y)
Button(root, text='Blue', bg="blue", fg="white",
command=root.quit).pack(expand=YES,fill=BOTH)
root.mainloop()


On Nov 15, 2007 4:40 PM, linda.s <[EMAIL PROTECTED]> wrote:
> I wonder why the widths are different for the three labels?
> Thanks,
> Linda
>
> from Tkinter import *
>
> root = Tk()
>
> w = Label(root, text="Red", bg="red", fg="white")
> w.pack()
> w = Label(root, text="Green", bg="green", fg="white")
> w.pack()
> w = Label(root, text="Blue", bg="blue", fg="white")
> w.pack()
>
> mainloop()
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
b h a a l u u at g m a i l dot c o m
http://www.geocities.com/ek.bhaaluu/index.html
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to import modules using the input() command

2007-11-15 Thread Alan Gauld
"bob gailer" <[EMAIL PROTECTED]> wrote 

> modname = raw_input()
> exec "import " + modname
> 
> That can be a security risk, in that a use could 
> enter "time; import os; os.rmdir('some_valuable_directory')"

Even more risky is the fact that modules can contain executable 
code that is run when the module is imported. If someone wrote 
such a module they would only need to type the filename and 
the exec would result in the rogue code being executed. If the 
rogue code had the same name as a standard module it would 
be extremely hard to detect. All of which are good reasons 
for not doing this unless you intend to build an IDE or 
somesuch - and even then there are better solutions!

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

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


Re: [Tutor] width

2007-11-15 Thread bhaaluu
As to the WHY it works like it does?

http://effbot.org/tkinterbook/pack.htm

On Nov 15, 2007 4:40 PM, linda.s <[EMAIL PROTECTED]> wrote:
> I wonder why the widths are different for the three labels?
> Thanks,
> Linda
>
> from Tkinter import *
>
> root = Tk()
>
> w = Label(root, text="Red", bg="red", fg="white")
> w.pack()
> w = Label(root, text="Green", bg="green", fg="white")
> w.pack()
> w = Label(root, text="Blue", bg="blue", fg="white")
> w.pack()
>
> mainloop()
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
b h a a l u u at g m a i l dot c o m
http://www.geocities.com/ek.bhaaluu/index.html
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] class accessing another's updated property

2007-11-15 Thread Alan Gauld
"ted b" <[EMAIL PROTECTED]> wrote

>I want class One to be able to access access class
> Two's value property after its been updated. Everytime
> I try (by running, say testTwo().value) I get the
> __init__ value.

Others have explained that you need to use instances
or class attributes.

I'll tackle the woder issue of synchronising
classes/instances. If you have a class (or classes) that
depend on another it is common to set up a publish/subscribe
mechanism so that the owner of the data notifies the subscribed
classesof changes. This can be a simple boolean flag to indicate
that something has changed or it can contain a list of the
published attributes that have changed(usually as a list of
name/value pairs or a dictionary)

This allows the subscribed objects to fetch the updated value
(or update their copy) whenever the master object changes value.
This is particularly common in the Model View architectures
used in GUIs where the model data may change and all
dependant views in the GUI need to be updated in synch.

To implement this requires that you create a publish/subscribe
method pair in the master class and then call publish every time
any of the public data changes. Client classes need to subscribe
to the master when created - ie in the init method. One common
way to do this with an established data class is via inheritance
and overloaded opertators, like so:

class Master:
def __init__(self, v1,v2,v3):
   self.v1 = v1
   self.v2 = v2
   self.v3 = v3
def m1(self): self.v1 = 42
def m1(self): self.v2 = 66
def m1(self): self.v3 = 27

class PublishedMaster(Master):
def __init__(self,v1,v2,v3):
Master.__init__(self,v1,v2,v3)
self.subs = []
def subscribe(self.obj):
self.subs.append(obj)
def publish(self):
for obj in self.subs:
obj.update(self)# notify subscriber of change
def m2(self):
Master.m2(self)
self.publish()
def m3(self):
Master.m3(self)
self.publish()

class client:
def __init__(self, master):
self.myVal = master.v2
master.subscribe(self)   # register interest in updates
def update(self.publisher):
self.v2 = publisher.v2

This allows the subscriber classes to be informed of any changes
to either v2 or v3. The client class is only interested in v2 so 
updates
its local copy when it receives the update message from the master.

Much more sophisticated regimes can be created but for simple
scenarios this suffices.Take care to avoid infinite loops caused by
calling a master method in client.update that results in the masdter
sending updates!

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


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


Re: [Tutor] Memory consumption question

2007-11-15 Thread Marc Tompkins
I thought of an analogy I like better than my sign-painting one: ordering a
sandwich.
Imagine: you're at the deli, and your waitron asks what you want.  (Granted,
this is a silly example.)
  "Classic" order: "I'd like a sandwich with two slices of rye bread,
Russian dressing, corned beef, and Swiss cheese.  Oh, and I'd like that
grilled."
  "New-style" order: "Reuben, please."

Now, I speak not of the time and materials required to construct the
above-mentioned tasty treat - in my analogy, Python is the long-suffering
waitron, not the cook - but I gotta figure that the second option will take
less space to write on the check.  Perhaps about 134 bytes' worth.

For some reason I'm hungry now...

On Nov 15, 2007 11:22 AM, Kent Johnson <[EMAIL PROTECTED]> wrote:

> Marc Tompkins wrote:
> > I didn't mean that exactly literally - for goodness' sake, this is a
> > high-level, object-oriented, interpreted language!  We're not writing
> > machine language here.
>
> Yes, I was thinking I should re-word my email, it was worded a bit too
> strongly...
>
> > What I did mean, and will probably still not express as clearly as I'd
> > like, is that when you create a "classic" class, lots of options remain
> > unresolved - slots vs. dict comes to mind - and Python needs to reserve
> > extra space accordingly.   About 134 extra bytes, it would appear.
>
> Still not sure I know what you mean. AFAIK old-style classes don't
> support slots, at least not user-defined slots. I do remember talk of
> new-style classes and properties allowing a much cleaner implementation
> of the class mechanisms, and it seems plausible that such generalization
> would lead to fewer options and streamlining of the class structure, but
> I don't know enough about the specifics to know if that is right.
>
> I poked around a bit in the source to see if I could figure it out but
> got tired of trying to sift through the header files...
>
> Kent
> >
> > On Nov 15, 2007 9:32 AM, Kent Johnson <[EMAIL PROTECTED]
> > > wrote:
> >
> > Marc Tompkins wrote:
> >
> >  > class B is a "new-style' class, meaning that it inherits from a
> base,
> >  > pre-existing class (in this case "object", which is as basic and
> > generic
> >  > as you can get!).  class A has to start from nothing, which is
> why it
> >  > consumes more memory yet has less functionality.
> >
> > I don't think it is really accurate to say that an old-style class
> > "starts from nothing". It doesn't have an explicit base class but it
> > does have all the old-style class machinery which is built in to
> Python.
> >
> > I don't know why new-style classes are smaller though. My guess is
> that
> > it is because there was an opportunity to streamline the class
> structure
> > based on experience.
> >
> > Kent
> >
> >
> >
> >
> > --
> > www.fsrtechnologies.com 
>
>


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


[Tutor] width

2007-11-15 Thread linda.s
I wonder why the widths are different for the three labels?
Thanks,
Linda

from Tkinter import *

root = Tk()

w = Label(root, text="Red", bg="red", fg="white")
w.pack()
w = Label(root, text="Green", bg="green", fg="white")
w.pack()
w = Label(root, text="Blue", bg="blue", fg="white")
w.pack()

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


[Tutor] selection

2007-11-15 Thread linda.s
Hi,
I wonder how to hold the ctrl key and button-1 to do multiple
selection of the following items?
Thanks,
Linda

import Tkinter

s = Tkinter.Scrollbar()
L = Tkinter.Listbox()

s.pack(side=Tkinter.RIGHT, fill=Tkinter.Y)
L.pack(side=Tkinter.LEFT, fill=Tkinter.Y)

s.config(command=L.yview)
L.config(yscrollcommand=s.set)

for i in range(30):
   L.insert(Tkinter.END, str(i)*3)

Tkinter.mainloop()
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Memory consumption question

2007-11-15 Thread Kent Johnson
Marc Tompkins wrote:
> I didn't mean that exactly literally - for goodness' sake, this is a 
> high-level, object-oriented, interpreted language!  We're not writing 
> machine language here.

Yes, I was thinking I should re-word my email, it was worded a bit too 
strongly...

> What I did mean, and will probably still not express as clearly as I'd 
> like, is that when you create a "classic" class, lots of options remain 
> unresolved - slots vs. dict comes to mind - and Python needs to reserve 
> extra space accordingly.   About 134 extra bytes, it would appear.

Still not sure I know what you mean. AFAIK old-style classes don't 
support slots, at least not user-defined slots. I do remember talk of 
new-style classes and properties allowing a much cleaner implementation 
of the class mechanisms, and it seems plausible that such generalization 
would lead to fewer options and streamlining of the class structure, but 
I don't know enough about the specifics to know if that is right.

I poked around a bit in the source to see if I could figure it out but 
got tired of trying to sift through the header files...

Kent
> 
> On Nov 15, 2007 9:32 AM, Kent Johnson <[EMAIL PROTECTED] 
> > wrote:
> 
> Marc Tompkins wrote:
> 
>  > class B is a "new-style' class, meaning that it inherits from a base,
>  > pre-existing class (in this case "object", which is as basic and
> generic
>  > as you can get!).  class A has to start from nothing, which is why it
>  > consumes more memory yet has less functionality.
> 
> I don't think it is really accurate to say that an old-style class
> "starts from nothing". It doesn't have an explicit base class but it
> does have all the old-style class machinery which is built in to Python.
> 
> I don't know why new-style classes are smaller though. My guess is that
> it is because there was an opportunity to streamline the class structure
> based on experience.
> 
> Kent
> 
> 
> 
> 
> -- 
> www.fsrtechnologies.com 

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


[Tutor] Little subclass understanding problem

2007-11-15 Thread Michael H. Goldwasser


Oops...

Just finished sending my earlier response and realize that I overlooked an 
issue.

The code from http://viner.tv/go?set is potentially errant.  When
invoking the base class constructor, self should have been explcitly
sent as a parameter, using the syntax

class Set(list):
def __init__(self, value = []):
list.__init__(self)
self.concat(value)  # copies mutable default

I had gotten sidetracked by the issue of why value was not being
explicitly sent. This explains in part why the original author used
the syntax 
list.__init__([])

with an empty list as the parameter to __init__.  That makes such a
command legal, but the call is entirely pointless, as it invokes the
initializer on a different instance than the one that we are currently
responsible for initializing.

I suspect that the code as written is faulty because the internal
state of the list is not necessarily properly initialized.   However,
since list is a built-in class, it is possible that the author of this
code is getting lucky because initialization of a Python list may be
happening by other means than list.__init__

This example is certainly not a proper use of inheritance.

With regard,
Michael



On Thursday November 15, 2007, Michael H. Goldwasser wrote: 

>
>On Thursday November 15, 2007, Tom wrote: 
>
>>I am trying to understand what happens in the following scenario:
>>
>>class Sub_class(Base_class):
>>def __init__(self, data):
>>Base_class.__init__(self, data)
>>
>>as in:
>>
>># snippet from http://viner.tv/go?set
>>class Set(list):
>>def __init__(self, value = []):
>>list.__init__([])
>
>
>Tom,
>
>  Indeed, that first line of the Set constructor body is invoking the
>  constructor for the base class (list, in this case).  The reason
>  that the value parameter is NOT being directly sent to the base
>  class is that there is a desire to avoid allowing potentially
>  duplicate elements into something that is representing a set. 
>
>  However, it was entirely unnecessary for them to send an empty list
>  as a parameter.  It would suffice to have written
>
> list.__init__()
>
>  It is important to have the call to the base class initializer
>  because we need to allow for the internal state of the underlying
>  list to be properly intitialized. 
>
>  Please note that the original source for this from viner.tv
>  has an important fourth line:
>
>class Set(list):
>def __init__(self, value = []):
>list.__init__([])
>self.concat(value)  # copies mutable default
>
>  That fourth line uses a custom method defined later to insert
>  designated values into the set while making sure to avoid
>  duplicates.
>
>With regard,
>Michael
>
>___
>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] Little subclass understanding problem

2007-11-15 Thread Kent Johnson
Tom wrote:
> I am trying to understand what happens in the following scenario:
> 
> class Sub_class(Base_class):
> def __init__(self, data):
> Base_class.__init__(self, data)
> 
> as in:
> 
> # snippet from http://viner.tv/go?set
> class Set(list):
> def __init__(self, value = []):
> list.__init__([])

This is a bug, it should be
   list.__init__(self, value)

> I have just re-read the relevant part of Wesley Chun's 'Core' book,
> again, and think I *may* understand.
> 
> Base_class.__init__(self, data)
> 
> is *kind of* like saying:
> 
> self.Base_class.__init__(data)
> 
> i.e. it's doing something *to* self. 

Yes, that is more or less correct.

In general, if c is an instance of class C, a method call
   c.foo()

can also be written as
   C.foo(c)

When you want to call a base class method, you have to use the second 
form. That is what
   Base_class.__init__(self)
is doing.

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


[Tutor] Little subclass understanding problem

2007-11-15 Thread Michael H. Goldwasser

On Thursday November 15, 2007, Tom wrote: 

>I am trying to understand what happens in the following scenario:
>
>class Sub_class(Base_class):
>def __init__(self, data):
>Base_class.__init__(self, data)
>
>as in:
>
># snippet from http://viner.tv/go?set
>class Set(list):
>def __init__(self, value = []):
>list.__init__([])


Tom,

  Indeed, that first line of the Set constructor body is invoking the
  constructor for the base class (list, in this case).  The reason
  that the value parameter is NOT being directly sent to the base
  class is that there is a desire to avoid allowing potentially
  duplicate elements into something that is representing a set. 

  However, it was entirely unnecessary for them to send an empty list
  as a parameter.  It would suffice to have written

 list.__init__()

  It is important to have the call to the base class initializer
  because we need to allow for the internal state of the underlying
  list to be properly intitialized. 

  Please note that the original source for this from viner.tv
  has an important fourth line:

class Set(list):
def __init__(self, value = []):
list.__init__([])
self.concat(value)  # copies mutable default

  That fourth line uses a custom method defined later to insert
  designated values into the set while making sure to avoid
  duplicates.

With regard,
Michael

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


Re: [Tutor] Memory consumption question

2007-11-15 Thread Marc Tompkins
I didn't mean that exactly literally - for goodness' sake, this is a
high-level, object-oriented, interpreted language!  We're not writing
machine language here.

What I did mean, and will probably still not express as clearly as I'd like,
is that when you create a "classic" class, lots of options remain unresolved
- slots vs. dict comes to mind - and Python needs to reserve extra space
accordingly.   About 134 extra bytes, it would appear.

On Nov 15, 2007 9:32 AM, Kent Johnson <[EMAIL PROTECTED]> wrote:

> Marc Tompkins wrote:
>
> > class B is a "new-style' class, meaning that it inherits from a base,
> > pre-existing class (in this case "object", which is as basic and generic
> > as you can get!).  class A has to start from nothing, which is why it
> > consumes more memory yet has less functionality.
>
> I don't think it is really accurate to say that an old-style class
> "starts from nothing". It doesn't have an explicit base class but it
> does have all the old-style class machinery which is built in to Python.
>
> I don't know why new-style classes are smaller though. My guess is that
> it is because there was an opportunity to streamline the class structure
> based on experience.
>
> Kent
>



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


[Tutor] Little subclass understanding problem

2007-11-15 Thread Tom
I am trying to understand what happens in the following scenario:

class Sub_class(Base_class):
def __init__(self, data):
Base_class.__init__(self, data)

as in:

# snippet from http://viner.tv/go?set
class Set(list):
def __init__(self, value = []):
list.__init__([])


The last line is the one I don't understand. Nothing appears to be
assigned or instantiated.

I have just re-read the relevant part of Wesley Chun's 'Core' book,
again, and think I *may* understand.

Base_class.__init__(self, data)

is *kind of* like saying:

self.Base_class.__init__(data)

i.e. it's doing something *to* self. But then the 2nd example above
doesn't make sense! It looks like list.__init__([]) is doing something
special just because of where it is, i.e. in the class definition of a
subclass of list.

Help!

If anyone has a better way of explaining this / thinking about this, I
would be most grateful!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Memory consumption question

2007-11-15 Thread Marc Tompkins
Thus spake Bart Cramer:

> I have a question... :
>
> >>> class A: pass
> ...
> >>> class B(object) : pass
> ...
> >>> dir(A)
> ['__doc__', '__module__']
> >>> dir(B)
> ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',
> '__hash__', '__init__', '__module__', '__new__', '__reduce__',
> '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__']
>
> What is the difference between classes A and B? The funny thing is, when I
> put these things into an array of length, say, a million, it turns out
> that
> class A eats about 184 bytes per instantiation, and class B a lot less
> (sic!): plm 50 bytes. How come?
>

class B is a "new-style' class, meaning that it inherits from a base,
pre-existing class (in this case "object", which is as basic and generic as
you can get!).  class A has to start from nothing, which is why it consumes
more memory yet has less functionality.  (As a very, very rough analogy,
imagine that you have thirty seconds to paint a sign.  Which would be more
efficient - freehand or a stencil?  Given time, you can achieve more
artistic results freehand, but the stencil gets you quick results.)

As I understand it, in Python 3000 (aka 3.0), new-style classes will be
mandatory.  As you can already see, they give you more bang for the buck, so
you might as well get used to using them now!

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


Re: [Tutor] Memory consumption question

2007-11-15 Thread Kent Johnson
Marc Tompkins wrote:

> class B is a "new-style' class, meaning that it inherits from a base, 
> pre-existing class (in this case "object", which is as basic and generic 
> as you can get!).  class A has to start from nothing, which is why it 
> consumes more memory yet has less functionality.

I don't think it is really accurate to say that an old-style class 
"starts from nothing". It doesn't have an explicit base class but it 
does have all the old-style class machinery which is built in to Python.

I don't know why new-style classes are smaller though. My guess is that 
it is because there was an opportunity to streamline the class structure 
based on experience.

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


Re: [Tutor] manipulating data

2007-11-15 Thread Kent Johnson
Bryan Fodness wrote:
> I try this,
> 
> f = open('TEST1.MLC')
> 
> fields = {}
> 
> for line in f:
> if line.split()[0] == 'Field':
> field = int(line.split()[-1])
> elif line.split()[0] == 'Leaf':
> fields[field] = line.split()[-1]
> else:
> line = f.next()
> 
> and get,
> 
> Traceback (most recent call last):
>   File "", line 1, in 
> line.split()[0]
> IndexError: list index out of range

For blank lines, line.split() is [] so there is no line.split()[0]. Try 
skipping blank lines before you split.

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


Re: [Tutor] manipulating data

2007-11-15 Thread Michael H. Goldwasser

On Monday November 12, 2007, Bryan Fodness wrote: 

>I try this,
>
>f = open('TEST1.MLC')
>
>fields = {}
>
>for line in f:
>if line.split()[0] == 'Field':
>field = int(line.split()[-1])
>elif line.split()[0] == 'Leaf':
>fields[field] = line.split()[-1]
>else:
>line = f.next()
>
>and get,
>
>Traceback (most recent call last):
>  File "", line 1, in 
>line.split()[0]
>IndexError: list index out of range

Bryan,

There are some blank lines in your file.  When those lines are
reached, line.split() returns an empty list, and therefore
line.split()[0] is an IndexError.   One way to rewrite this is as
follows (untested):

for line in f:
pieces = line.split()
if pieces:  # non-empty line
if pieces[0] == 'Field':
field = int(pieces[-1])
elif pieces[0] == 'Leaf':
fields[field] = pieces[-1]
else:
line = f.next() # I've left this here, but not sure
# why you have it.  The for loop
# already advances from line to line

Note as well that it is better to perform the split once per line
(rather than recomputing it as you do in your original code).

With regard,
Michael

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


Re: [Tutor] manipulating data

2007-11-15 Thread Bryan Fodness
I try this,

f = open('TEST1.MLC')

fields = {}

for line in f:
if line.split()[0] == 'Field':
field = int(line.split()[-1])
elif line.split()[0] == 'Leaf':
fields[field] = line.split()[-1]
else:
line = f.next()

and get,

Traceback (most recent call last):
  File "", line 1, in 
line.split()[0]
IndexError: list index out of range

I have attached my data file.
File Rev = G
Treatment = Dynamic Dose
Last Name = Fodness
First Name = Bryan
Patient ID = 0001
Number of Fields = 4
Number of Leaves = 120
Tolerance = 0.50

Field = 10
Index = 0.
Carriage Group = 1
Operator = 
Collimator = 0.0
Leaf  1A =   0.00
Leaf  2A =   0.00
Leaf  3A =   0.00
Leaf  4A =   0.00
Leaf  5A =   0.00
Leaf  6A =   0.00
Leaf  7A =   0.00
Leaf  8A =   0.00
Leaf  9A =   0.00
Leaf 10A =   0.00
Leaf 11A =   0.00
Leaf 12A =   0.00
Leaf 13A =   0.00
Leaf 14A =   0.00
Leaf 15A =   0.00
Leaf 16A =   0.00
Leaf 17A =   0.00
Leaf 18A =   0.00
Leaf 19A =   0.00
Leaf 20A =   0.00
Leaf 21A =   5.00
Leaf 22A =   5.00
Leaf 23A =   5.00
Leaf 24A =   5.00
Leaf 25A =   5.00
Leaf 26A =   5.00
Leaf 27A =   5.00
Leaf 28A =   5.00
Leaf 29A =   5.00
Leaf 30A =   5.00
Leaf 31A =   5.00
Leaf 32A =   5.00
Leaf 33A =   5.00
Leaf 34A =   5.00
Leaf 35A =   5.00
Leaf 36A =   5.00
Leaf 37A =   5.00
Leaf 38A =   5.00
Leaf 39A =   5.00
Leaf 40A =   5.00
Leaf 41A =   0.00
Leaf 42A =   0.00
Leaf 43A =   0.00
Leaf 44A =   0.00
Leaf 45A =   0.00
Leaf 46A =   0.00
Leaf 47A =   0.00
Leaf 48A =   0.00
Leaf 49A =   0.00
Leaf 50A =   0.00
Leaf 51A =   0.00
Leaf 52A =   0.00
Leaf 53A =   0.00
Leaf 54A =   0.00
Leaf 55A =   0.00
Leaf 56A =   0.00
Leaf 57A =   0.00
Leaf 58A =   0.00
Leaf 59A =   0.00
Leaf 60A =   0.00
Leaf  1B =   0.00
Leaf  2B =   0.00
Leaf  3B =   0.00
Leaf  4B =   0.00
Leaf  5B =   0.00
Leaf  6B =   0.00
Leaf  7B =   0.00
Leaf  8B =   0.00
Leaf  9B =   0.00
Leaf 10B =   0.00
Leaf 11B =   0.00
Leaf 12B =   0.00
Leaf 13B =   0.00
Leaf 14B =   0.00
Leaf 15B =   0.00
Leaf 16B =   0.00
Leaf 17B =   0.00
Leaf 18B =   0.00
Leaf 19B =   0.00
Leaf 20B =   0.00
Leaf 21B =   5.00
Leaf 22B =   5.00
Leaf 23B =   5.00
Leaf 24B =   5.00
Leaf 25B =   5.00
Leaf 26B =   5.00
Leaf 27B =   5.00
Leaf 28B =   5.00
Leaf 29B =   5.00
Leaf 30B =   5.00
Leaf 31B =   5.00
Leaf 32B =   5.00
Leaf 33B =   5.00
Leaf 34B =   5.00
Leaf 35B =   5.00
Leaf 36B =   5.00
Leaf 37B =   5.00
Leaf 38B =   5.00
Leaf 39B =   5.00
Leaf 40B =   5.00
Leaf 41B =   0.00
Leaf 42B =   0.00
Leaf 43B =   0.00
Leaf 44B =   0.00
Leaf 45B =   0.00
Leaf 46B =   0.00
Leaf 47B =   0.00
Leaf 48B =   0.00
Leaf 49B =   0.00
Leaf 50B =   0.00
Leaf 51B =   0.00
Leaf 52B =   0.00
Leaf 53B =   0.00
Leaf 54B =   0.00
Leaf 55B =   0.00
Leaf 56B =   0.00
Leaf 57B =   0.00
Leaf 58B =   0.00
Leaf 59B =   0.00
Leaf 60B =   0.00
Note = 0
Shape = 4
  500   500
  500  -500
 -500  -500
 -500   500
Magnification = 1.00

Field = 8
Index = 0.4000
Carriage Group = 1
Operator = 
Collimator = 0.0
Leaf  1A =   0.00
Leaf  2A =   0.00
Leaf  3A =   0.00
Leaf  4A =   0.00
Leaf  5A =   0.00
Leaf  6A =   0.00
Leaf  7A =   0.00
Leaf  8A =   0.00
Leaf  9A =   0.00
Leaf 10A =   0.00
Leaf 11A =   0.00
Leaf 12A =   0.00
Leaf 13A =   0.00
Leaf 14A =   0.00
Leaf 15A =   0.00
Leaf 16A =   0.00
Leaf 17A =   0.00
Leaf 18A =   0.00
Leaf 19A =   0.00
Leaf 20A =   0.00
Leaf 21A =   0.00
Leaf 22A =   0.00
Leaf 23A =   4.00
Leaf 24A =   4.00
Leaf 25A =   4.00
Leaf 26A =   4.00
Leaf 27A =   4.00
Leaf 28A =   4.00
Leaf 29A =   4.00
Leaf 30A =   4.00
Leaf 31A =   4.00
Leaf 32A =   4.00
Leaf 33A =   4.00
Leaf 34A =   4.00
Leaf 35A =   4.00
Leaf 36A =   4.00
Leaf 37A =   4.00
Leaf 38A =   4.00
Leaf 39A =   0.00
Leaf 40A =   0.00
Leaf 41A =   0.00
Leaf 42A =   0.00
Leaf 43A =   0.00
Leaf 44A =   0.00
Leaf 45A =   0.00
Leaf 46A =   0.00
Leaf 47A =   0.00
Leaf 48A =   0.00
Leaf 49A =   0.00
Leaf 50A =   0.00
Leaf 51A =   0.00
Leaf 52A =   0.00
Leaf 53A =   0.00
Leaf 54A =   0.00
Leaf 55A =   0.00
Leaf 56A =   0.00
Leaf 57A =   0.00
Leaf 58A =   0.00
Leaf 59A =   0.00
Leaf 60A =   0.00
Leaf  1B =   0.00
Leaf  2B =   0.00
Leaf  3B =   0.00
Leaf  4B =   0.00
Leaf  5B =   0.00
Leaf  6B =   0.00
Leaf  7B =   0.00
Leaf  8B =   0.00
Leaf  9B =   0.00
Leaf 10B =   0.00
Leaf 11B =   0.00
Leaf 12B =   0.00
Leaf 13B =   0.00
Leaf 14B =   0.00
Leaf 15B =   0.00
Leaf 16B =   0.00
Leaf 17B =   0.00
Leaf 18B =   0.00
Leaf 19B =   0.00
Leaf 20B =   0.00
Leaf 21B =   0.00
Leaf 22B =   0.00
Leaf 23B =   4.00
Leaf 24B =   4.00
Leaf 25B =   4.00
Leaf 26B =   4.00
Leaf 27B =   4.00
Leaf 28B =   4.00
Leaf 29B =   4.00
Leaf 30B =   4.00
Leaf 31B =   4.00
Leaf 32B =   4.00
Leaf 33B =   4.00
Leaf 34B =   4.00
Leaf 35B =   4.00
Leaf 36B =   4.00
Leaf 37B =   4.00
Leaf 38B =   4.00
Leaf 39B =   0.00
Leaf 40B =   0.00
Leaf 41B =   0.00
Leaf 42B =   0.00
Leaf 43B =   0.00
Leaf 44B =   0.00
Leaf 45B =   0.00
Leaf 46B =   0.00
Leaf 47B =   0.00
Leaf 48B =   0.00
Leaf 49B =   0.00
Leaf 50B =   0.00
Leaf 51B =   0.00
Leaf 52B =   0.00
Leaf 53B =   0.00
Leaf 54B

[Tutor] Memory consumption question

2007-11-15 Thread Bart Cramer
Dear all,

I have a question... :

>>> class A: pass
...
>>> class B(object) : pass
...
>>> dir(A)
['__doc__', '__module__']
>>> dir(B)
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',
'__hash__', '__init__', '__module__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__']

What is the difference between classes A and B? The funny thing is, when I
put these things into an array of length, say, a million, it turns out that
class A eats about 184 bytes per instantiation, and class B a lot less
(sic!): plm 50 bytes. How come?

Best,

Bart.

-- 
Bart Cramer

Dudweilerstrasse 31
66111 Saarbrucken, Germany
0049 1577 6806119 (NEW!)

Bedumerstraat 25
9716 BB Groningen, the Netherlands
0031 6 42440326

[EMAIL PROTECTED]
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to import modules using the input() command

2007-11-15 Thread Remco Gerlich
The input() function calls eval() on the value you give it. Eval() can
evaluate any _expression_. That's generally insecure and not
recommended - people could type in anything, as you're trying to do
:-)

But anyway, that is why 'import ...' directly doesn't work, import is
a statement, not an expression.

However, you can use the built-in function __import__(), that imports
the module and returns it. That loads it into memory, but it doesn't
add the module to the current namespace.

What do you need this for?

Remco Gerlich

On Nov 15, 2007 4:25 PM, Mihai Iacob <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I was wondering if there is a way to import modules
> using the input() command. If i try to do it directly
> it gives me an error:
>
> >>> input()
> import time
>
> Traceback (most recent call last):
>   File "", line 1, in 
> input()
>   File "", line 1
> import time
>  ^
> SyntaxError: invalid syntax
> >>>
>
>
> Is there another way in which i can import modules
> with the input() command?
>
>
>
>
>
>   
> 
> Never miss a thing.  Make Yahoo your home page.
> http://www.yahoo.com/r/hs
> ___
> 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 import modules using the input() command

2007-11-15 Thread bob gailer




Mihai Iacob wrote:

  Hello,

I was wondering if there is a way to import modules
using the input() command. If i try to do it directly
it gives me an error:

  
  

  
input()

  

  
  import time
  

The input function takes a character string and attempts to interpret
it as a Python _expression_. import is a statement, not
an _expression_.


  Traceback (most recent call last):
  File "", line 1, in 
input()
  File "", line 1
import time
 ^
SyntaxError: invalid syntax
  
  

Is there another way in which i can import modules
with the input() command?
  

Yes:

modname = raw_input()
exec "import " + modname

That can be a security risk, in that a use could enter "time; import
os; os.rmdir('some_valuable_directory')"
You could prescan modname for semicolons to reduce the risk.

Safer is:

modname = raw_input() 
globals()[modname] = __import__(modname)



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


Re: [Tutor] How to import modules using the input() command

2007-11-15 Thread Kent Johnson
Mihai Iacob wrote:
> Hello,
> 
> I was wondering if there is a way to import modules
> using the input() command. If i try to do it directly
> it gives me an error:
> 
 input()
> import time
> 
> Traceback (most recent call last):
>   File "", line 1, in 
> input()
>   File "", line 1
> import time
>  ^
> SyntaxError: invalid syntax

import is a statement, not an expression, that is why it fails with 
input(). You could input the name of the module and then import it 
yourself with __import__(), or you could type '__import__("time")' to 
input() though that won't bind the module to a name.

Why do you want to do this? It is an unusual request.

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


[Tutor] How to import modules using the input() command

2007-11-15 Thread Mihai Iacob
Hello,

I was wondering if there is a way to import modules
using the input() command. If i try to do it directly
it gives me an error:

>>> input()
import time

Traceback (most recent call last):
  File "", line 1, in 
input()
  File "", line 1
import time
 ^
SyntaxError: invalid syntax
>>> 


Is there another way in which i can import modules
with the input() command?





  

Never miss a thing.  Make Yahoo your home page. 
http://www.yahoo.com/r/hs
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] parsing an array

2007-11-15 Thread Kent Johnson
sith . wrote:
> a = [[1,1],[3,1.5],[5,0]]
> for i in range(len(a)) :

This should use range(1, len(a)). You don't want i to take on the value 0.

> if a[i][1] > a[i-1][1] :

When i==0 this compares a[0] to a[-1] which is the *last* element of the 
list; a[0][1] > a[-1][1] so it prints 'greater !!'.

Kent

PS Please reply to the original post rather than starting a new thread.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] parsing an array

2007-11-15 Thread sith .
greater !!
  greater !!
  smaller
  
  only the second and third "greater" and "smaller" output are correct as 1.5 
is larger than 1 and 0 is smaller than 1.5.  
   
  What is i[1] greater than?  

[Tutor] parsing an array

2007-11-15 Thread sith .
a = [[1,1],[3,1.5],[5,0]]
  for i in range(len(a)) :
if a[i][1] > a[i-1][1] :
print 'greater !!'
else:
print "smaller"
  greater !!
  greater !!
  smaller
  
Thanks for taking the time to help me Aditya.  I tried the code but have 
encountered a problem.  In this new list,
[1,1]
[3,1.5]
[5,0]
  only the second and third "greater" and "smaller" output are correct as 1.5 
is larger than 1 and 0 is smaller than 1.5.  What is i[1] greater than?  
  I also tried using + for next item instread, but that produced an error.  Why?
if a[i][1] > a[i+1][1] 

   
-
Be a better sports nut! Let your teams follow you with Yahoo Mobile. Try it now.___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] [OT] Vacancy - python systems programmer

2007-11-15 Thread Stephen Nelson-Smith
All,

I may shortly be in the position of being able to hire a python
systems programmer for a short contract (1-2 days initially to spike
an ongoing project).

The ideal person will have the following:

* Solid experience of Python for systems programming and database interaction
* Familiarity with MySQL 5 - inserting and querying medium-sized
databases with Python
* Systems experience on RHEL or equivalent clone
* Sysadmin experience on Unix / Linux with patching and package
management systems
* Experience in a high-availability environment, eg managed hosting.
* Experience of working in an agile environment (test first, pairing)

This is, of course, a shopping list, but is intended to give a sense
of the sort of background I'm after.

If this sounds like the sort of thing you'd be interested in, please
contact me off list.

Thanks,

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


[Tutor] selecting elements from a list that do not meet selection criteria

2007-11-15 Thread ted b
Is there a way i can select all elements from a list
that do not meet selection criteria. I want to be able
to select elements that have values of, say, < 1 but
only if at least one of the elements has a value of >
0.

What i mean is, for example, in the code below, if one
of the elements of "list 'a'" has a value greater than
1, then i want to print all the other elements in the
list (i.e., class One and class Three) and to do
otherStuff associated with those classes. Right now,
it prints those elements that *do* have values of > 0,
(i.e. class Two). But in situations where all of the
classes have values set to 0, then i don't want
anything selected. 

I don't want to just use something like "if x.value()
!= 0" or "if x.value() < 1" since those would give
results if all elements were less than 1, and i only
want to select elements of the list that are less than
1 if at least one of the elements is > 1.

Here's the sample code:

class One:
   def value(self):
  return 0
  
class Two:
   def value(self):
  return 1

class Three:
   def value(self):
  return 0

a = [One(), Two(), Three()]

for x in a:
   if x.value() > 0:
  print x
  x.otherStuff()

Thanks in advance!!! :)))


  

Be a better pen pal. 
Text or chat with friends inside Yahoo! Mail. See how.  
http://overview.mail.yahoo.com/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Interactive Menu Woes

2007-11-15 Thread Bryan Magalski
I wish I would have read your response before posting to Evert Rol's response.  
They compliment each other in both explanation and detail.  I thank you as well 
for your contribution, as I said in my response to Evert, I will post my script 
completed when I get home.

Thank you.


--Bryan


- Original Message 
From: Wesley Brooks <[EMAIL PROTECTED]>
To: Bryan Magalski <[EMAIL PROTECTED]>
Sent: Thursday, November 15, 2007 10:12:26 AM
Subject: Re: [Tutor] Interactive Menu Woes

No worries, I'm still learning myself - be it four years down the
line. Don't think you ever really finsh learning these languages,
there's always new tricks to learn!

The __init__ functions are called when you create an instance of a
class, and are optional.

class a:
def __init__(self, text):
self.text = text

def PrintText(self):
print self.text

>>> aa = a("Testing __init__")
>>> aa.PrintText()
Testing __init__
>>>

More useful for the telephone number example would be an init function
that created a dictionary to contain your name/number information;

class Directory:
def __init__(self):
self.directory = {}

def AddNumber(self, name, number):
# name should be a string,
# number can be string or integer.
self.directory[name] = number

def RetrieveNumber(self, name):
nameList = self.directory.keys() # Returns a list of all the
names in the dictionary
if name not in nameList: # Checks to make sure the name is in the list
# if this check was not
made an error would be raised
# if you tried to get the
name from the dictionary.
print "Sorry, do not have that persons name!"
else:
return self.directory[name]

>>> telObj = Directory()
>>> telObj.AddNumber("Damion", 666)
>>> telObj.RetrieveNumber("Eric")
Sorry, do not have that persons name!
>>> telObj.RetrieveNumber("Damion")
666

However you would like to give these people different types of numbers
etc so you could create a new dictionary to store various details
inplace of the numbers:

class Directory:
def __init__(self):
self.directory = {}

def AddDetail(self, name, type, data):
if name not in self.directory.keys():
self.directory[name] = {}
personDetails = self.directory[name]
personDetails[type] = data

def RetrieveDetail(self, name, type):
nameList = self.directory.keys()
if name not in nameList:
print "Sorry, do not have that persons name!"
else:
personDetails = self.directory[name]
storedDetailTypes = personDetails.keys()
if type not in storedDetailTypes:
print "Sorry, do not have those details for that person"
else:
return personDetails[type]

>>> telObj = Directory()
>>> telObj.AddDetail("Damion", "HomeTel", 666)
>>> telObj.RetrieveDetail("Damion", "Mobile")
Sorry, do not have those details for that person
>>> telObj.RetrieveDetail("Damion", "HomeTel")
666

You can take this a further still. Instead of creating a dictionary,
you could create a new instance of an object that inherits the
dictionary class, and that way you can override the functions that add
data to, and retrieve data from the personalDetails object. This is a
little more advanced, and I guess you've got a fair bit to digest
above!

Hope that helps.

Cheers,

Wes.

On 14/11/2007, Bryan Magalski <[EMAIL PROTECTED]> wrote:
>
> Thank you very much for the prompt reply.
>
> I believe the way you explained my inability to grasp the concept really
> helped and I think I understand it better now.  It just proves that I need
> to practice more.
>
> If you have the time, I have another question pertaining to objects.   There
> is a ton of information on the web about how to use __init__ and self when
> creating functions within an object.  I simply "aped" the code from the
> millions of examples out there without really understanding them totally,
> (maybe now I am script kiddie?).  As I really cannot digest this, can you
> help me and elaborate on the reason of their existence and when it is
> appropriate for their use?
>
>
> Again, excellent explanation and thank you very much.  I hope that I am not
> burdening you by bombarding you with these questions.
>
>
> --Bryan
>
>
> Wesley Brooks <[EMAIL PROTECTED]> wrote:
> In the middle of your addName function you have defined another
> function that requires 'self' and you've got a default argument
> 'get=1';
>
> def numberType(self, get = 1):
>
> You call this further down the function with the line;
>
> self.type = numberType(self.get)
>
> This should have been;
>
> self.type = numberType(self)
>
> I would suggest moving the numberType function from inside the addName
> function as follows;
>
> class MenuInput:
> def addName(self):
> print "To add a name, please input he following informatio

Re: [Tutor] CSV TO LDIF

2007-11-15 Thread Kent Johnson
sacha rook wrote:

> I am using the csv module to parse the csv, anyone got any suggestions 
> for creating the ldif file from this?

http://python-ldap.sourceforge.net/doc/python-ldap/ldif-example.html

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


Re: [Tutor] Interactive Menu Woes

2007-11-15 Thread Bryan Magalski
Awesome, awesome, awesome.  I will check my script when I get home from work, 
but your explanation is top notch!  I think I understand it now.  Thank you.

I will post my corrected script and the answers when I get home from work 
tonight.

Many thanks!


- Original Message 
From: Evert Rol <[EMAIL PROTECTED]>
To: Bryan Magalski <[EMAIL PROTECTED]>
Cc: tutor@python.org
Sent: Thursday, November 15, 2007 11:37:43 AM
Subject: Re: [Tutor] Interactive Menu Woes

> Thank you for your suggestion.  I did not create the original  
> script, so it will stay as is and my addition for the menu has been  
> adjusted.
>
> Now that I can make a clear distinction of what I am returning, I  
> am getting a new error that leads me that I am trying to call a  
> function that cannot be seen when instantiated:
>
> To add a name, please input he following information:
> Name: Bryan
> Number: 1234567890
> What type of number is this? (choose one):
>  1. Home:
>  2. Work:
>  3. Cell:
>  : 1
> Traceback (most recent call last):
>  File "menu_modified.py", line 95, in 
>menu.addName()
>  File "menu_modified.py", line 73, in addName
>enter(name, number, returnType)
> AttributeError: phoneentry instance has no __call__ method


You're first creating a phoneentry object, and then calling the  
actual object. That doesn't work; it's somewhat similar to:
>>> a = dict()
>>> a(key=5)
which gives a slightly different error, but obviously the correct  
form is:
>>> a = dict(key=5)
and also
>>> phoneentry(name, number, returnType)

When creating an object (instantiating the class), the __init__  
method is automatically called, and you provide the arguments of the  
__init__ method when creating the object.
In your current script, the actual entry you create (enter =  
phoneenetry()) creates an entry with name & number 'Unknown' (default  
arguments), and types=UNKNOWN; then you want to assign the actual  
values to the entry. If you *really* want to do this (don't, though),  
you'd be doing:
entry = phoneentry()
entry.name = name
entry.number = number
entry.types = returnType

See the add() method in the phonedb class, where it is done correctly.


A few other thoughts:
- what does numberType return if 'n is not in typeDict'? It should  
return UNKNOWN I guess.
- why not remove that function, and put typeDict to addName? It's  
really only one extra line, and avoids the whole extra function call  
(replacing it with something one might call a 'dictionary call')
- I noticed you use tabs, while the original part of the code uses  
spaces. Try to avoid mixing them: at some point things will go wrong  
(spaces are preferred; for a good read on that and other stuff:  
http://www.python.org/doc/essays/styleguide.html )


  Evert


  

Be a better sports nut!  Let your teams follow you 
with Yahoo Mobile. Try it now.  
http://mobile.yahoo.com/sports;_ylt=At9_qDKvtAbMuh1G1SQtBI7ntAcJ___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] selecting elements from a list that do not meet selection criteria

2007-11-15 Thread Kent Johnson
ted b wrote:
> Is there a way i can select all elements from a list
> that do not meet selection criteria. I want to be able
> to select elements that have values of, say, < 1 but
> only if at least one of the elements has a value of >
> 0.

I'm not sure if you mean > 0 or >1, you seem to say both at different times.

> I don't want to just use something like "if x.value()
> != 0" or "if x.value() < 1" since those would give
> results if all elements were less than 1, and i only
> want to select elements of the list that are less than
> 1 if at least one of the elements is > 1.

Use any():
   if any(x.value() > 0 for x in a):
 for x in a:
  if x.value() > 0:
print x
x.otherStuff()

> Here's the sample code:
> 
> class One:
>def value(self):
>   return 0

BTW this style of programming - using getter methods to access values - 
is not idiomatic Python. Better would be to use a value attribute directly:

class One:
   def __init__(self):
 self.value = 0

Then refer to One().value instead of One().value()

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


Re: [Tutor] retrieve data from an online database without knowing the url

2007-11-15 Thread Kent Johnson
pileux systeme wrote:
> Hello,
> 
> I was wondering whether it was possible to write a program which could 
> directly write some word in a box and click 'search' on a typical online 
> database without using the url. (e.g. is there a way to write a program 
> which would write some keyword, say 'tomato' on google and click 'google 
> search' automatically and copy the page without having to know the url 
> 'http://www.google.com/search?hl=en&sa=X&oi=spell&resnum=0&ct=result&cd=1&q=tomato&spell=1')

Maybe ClientForm is what you want:
http://wwwsearch.sourceforge.net/ClientForm/

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


Re: [Tutor] class accessing another's updated property

2007-11-15 Thread Yoram Hekma
On Wed, Nov 14, 2007 at 04:43:28AM -0800, ted b wrote:
> I want class One to be able to access access class
> Two's value property after its been updated. Everytime
> I try (by running, say testTwo().value) I get the
> __init__ value. The update method fro class Two is
> called elsewhere in the program, and I want class
> One's "getTwo" method to access class Two's updated
> value and give me '9' but i get '1'
> 
> Here's the code:
> 
> class One:
>def __init__(self):
>   self.value = 3
>def getTwo(self):
>   print "testTwo's updated value", Two().value
> 
> class Two:
>def __init__(self):
>   self.value = 1
>def update(self):
>   self.value = 9
> 
> Thanks in advance!

I think you want to update an instance of a class, not the class itself.
If you do:

class Two:
   def __init__(self):
  self.value = 1
   def update(self):
  self.value = 9

class One:
def __init__(self):
self.value = 3
instance_of_Two = Two()
def getTwo(self):
print "testTwo's value", instance_of_Two().value
instance_of_Two.update()
print "testTwo's updated value", instance_of_Two().value

HTH
Yoram

-- 
Yoram Hekma
Unix Systems Administrator
CICT Department
AOES Netherlands B.V.
Haagse Schouwweg 6G
2332 KG Leiden, The Netherlands
Phone:  +31 (0)71 5795588
Fax:+31 (0)71 5721277
e-mail: [EMAIL PROTECTED]
http://www.aoes.com



signature.asc
Description: Digital signature
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] retrieve data from an online database without knowing the url

2007-11-15 Thread Yoram Hekma
On Thu, Nov 15, 2007 at 04:06:31AM +0100, pileux systeme wrote:
> Hello,
> 
> I was wondering whether it was possible to write a program which could 
> directly write some word in a box and click 'search' on a typical online 
> database without using the url. (e.g. is there a way to write a program which 
> would write some keyword, say 'tomato' on google and click 'google search' 
> automatically and copy the page without having to know the url 
> 'http://www.google.com/search?hl=en&sa=X&oi=spell&resnum=0&ct=result&cd=1&q=tomato&spell=1')
> Thank you very much for any help you could provide,
> 
> N.
> 

Yes, this is possible. Have a look at urllib
(http://docs.python.org/lib/module-urllib.html) and within that page see
urlencode. The idea is that first you make a connection to google.com,
and then post the search values to the form. If you look at the form on
google.com (from source) you see the following:


--snip--



--snip--


For example:

import urllib
search_string = 'cars'
encoded_search_string = urllib.urlencode({'q': search_string})
reponse = urllib.urlopen('www.google.com', encoded_search_string)

To search for "cars"

Good luck!
-- 
Yoram Hekma
Unix Systems Administrator
CICT Department
AOES Netherlands B.V.
Haagse Schouwweg 6G
2332 KG Leiden, The Netherlands
Phone:  +31 (0)71 5795588
Fax:+31 (0)71 5721277
e-mail: [EMAIL PROTECTED]
http://www.aoes.com



signature.asc
Description: Digital signature
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Obtaining image date of creation

2007-11-15 Thread pyprog
On jeu, 2007-11-15 at 04:17 +0100, pyprog wrote:
> 
> >>> import Image
> >>> ouv=Image.open('path_to_your_picture_with_exif_data__jpeg')
> >>> exifdata=imgExif._getexif() 

A little error :


>>> import Image
>>> ouv=Image.open('path_to_your_picture_with_exif_data__jpeg')
>>> exifdata=ouv._getexif()
>>> ...

I'm EKD developper : http://ekd.tolosano.info and it work with EXIF. You
can download and test it if you want. It works with Tkinter nowadays and
in future he will work with PyQt4 .

http://ekd.tolosano.info/html_docs/fonctionnalites_ekd/images_pages_html/cop_ecr_interfac_ekd_exif_00.jpg
  
http://ekd.tolosano.info/html_docs/fonctionnalites_ekd/exif/essai_exif_ekd_1.html

Excuse me for my bad english .

a+
-- 
Venez faire un tour ici :

http://ekd.tolosano.info
http://monsitt.irruption.net
http://irruption.net/progdudim

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


Re: [Tutor] Interactive Menu Woes

2007-11-15 Thread Evert Rol
> Thank you for your suggestion.  I did not create the original  
> script, so it will stay as is and my addition for the menu has been  
> adjusted.
>
> Now that I can make a clear distinction of what I am returning, I  
> am getting a new error that leads me that I am trying to call a  
> function that cannot be seen when instantiated:
>
> To add a name, please input he following information:
> Name: Bryan
> Number: 1234567890
> What type of number is this? (choose one):
>  1. Home:
>  2. Work:
>  3. Cell:
>  : 1
> Traceback (most recent call last):
>   File "menu_modified.py", line 95, in 
> menu.addName()
>   File "menu_modified.py", line 73, in addName
> enter(name, number, returnType)
> AttributeError: phoneentry instance has no __call__ method


You're first creating a phoneentry object, and then calling the  
actual object. That doesn't work; it's somewhat similar to:
 >>> a = dict()
 >>> a(key=5)
which gives a slightly different error, but obviously the correct  
form is:
 >>> a = dict(key=5)
and also
 >>> phoneentry(name, number, returnType)

When creating an object (instantiating the class), the __init__  
method is automatically called, and you provide the arguments of the  
__init__ method when creating the object.
In your current script, the actual entry you create (enter =  
phoneenetry()) creates an entry with name & number 'Unknown' (default  
arguments), and types=UNKNOWN; then you want to assign the actual  
values to the entry. If you *really* want to do this (don't, though),  
you'd be doing:
entry = phoneentry()
entry.name = name
entry.number = number
entry.types = returnType

See the add() method in the phonedb class, where it is done correctly.


A few other thoughts:
- what does numberType return if 'n is not in typeDict'? It should  
return UNKNOWN I guess.
- why not remove that function, and put typeDict to addName? It's  
really only one extra line, and avoids the whole extra function call  
(replacing it with something one might call a 'dictionary call')
- I noticed you use tabs, while the original part of the code uses  
spaces. Try to avoid mixing them: at some point things will go wrong  
(spaces are preferred; for a good read on that and other stuff:  
http://www.python.org/doc/essays/styleguide.html )


   Evert

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


Re: [Tutor] retrieve data from an online database without knowing the url

2007-11-15 Thread Evert Rol
> I was wondering whether it was possible to write a program which  
> could directly write some word in a box and click 'search' on a  
> typical online database without using the url. (e.g. is there a way  
> to write a program which would write some keyword, say 'tomato' on  
> google and click 'google search' automatically and copy the page  
> without having to know the url 'http://www.google.com/search? 
> hl=en&sa=X&oi=spell&resnum=0&ct=result&cd=1&q=tomato&spell=1')
> Thank you very much for any help you could provide,

I would use urllib & urllib2 (google around for some example code),  
but then you'll still have to know
- the names of the input search box and search button
- whether it's a get or post form
Some of this info can be gotten by first downloading the form and  
examine it for tags (such as 'action'), but possibly not all.

Other than that, I wouldn't really know.

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


[Tutor] CSV TO LDIF

2007-11-15 Thread sacha rook
Hi
 
I have a csv of users that I want to update their records in edirectory.
 
I am quite happy to use the ldap import utility to pull an ldif file into 
edirectory to update information.
 
I am using the csv module to parse the csv, anyone got any suggestions for 
creating the ldif file from this?
 
Any help or pointers greatly appreciated.
 
Regards
 
S
_
Celeb spotting – Play CelebMashup and win cool prizes
https://www.celebmashup.com___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] parsing an array

2007-11-15 Thread Aditya Lal
On Nov 15, 2007 12:37 PM, sith . <[EMAIL PROTECTED]> wrote:

> a = [[1,2],[3,1.5],[5,6]]
> for i in a:
> print i
> if i[1]>i[0]:
> print "second index is larger"
> else:
> print "second index is smaller"
> [1, 2]
> second index is larger
> [3, 1.5]
> second index is small
> er
> [5, 6]
> second index is larger
>
> What I'd like do is compare if 1.5 in i[1] is greater than 2 in i[0];
> for time series, t(1)>t(0) and interate through the entire list - is 6 in
> i[2]>than 1.5 in i[1] etc?
> Since the data is in columns in a text file or csv, I can't put 1.5 in the
> same sublist as 2, and 6 in the same sublist as 1.5 to make things
> easier.  What can I do?
> Thank you for your help.
>
> --
>
>
for i in range(1,len(a)) :
  if a[i][1] > a[i-1][1] :
 print 'greater !!' # or whatever you want

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