[Tutor] Inputting elements of a list

2007-01-22 Thread vanam

For standard input from the keyboard raw_input will be used for string and
input for number.Suppose i want to input a list of some elements how could
it be done. Actually i am looking for sorting out elements in a
list.Belowis the given script
list = [45,4,5]
list.sort()
for y in list:
  print y ->this would sort out elements in that list. my question is in
the above script all the elements that list carry are defined i want to
input some elements in the list how could it be done


--

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


Re: [Tutor] direction and draw

2007-01-22 Thread Luke Paireepinart
linda.s wrote:
> I have a segment (two ending points are A and B) which is 0 degree.
> How to draw a segment with 10 degrees and 15 in length?
>   
You'll need a pen, some paper, a protractor, a ruler, and a steady hand.
Good luck.
-Luke

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


Re: [Tutor] pyw bug ?

2007-01-22 Thread Luke Paireepinart
Dave S wrote:
> Hi all,
>
> My GUI app dumps some diagnostic output to the terminal, starting it from an 
> XP terminal, all is well.
>
> Starting it as app.pyw so no terminal is needed - and err - the app randomly 
> locks because the diagnostic output is - backing up ?
Hmm, maybe check where sys.stdout is directed?
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Inputting elements of a list

2007-01-22 Thread Alan Gauld

"vanam" <[EMAIL PROTECTED]> wrote
> For standard input from the keyboard raw_input will be used for 
> string and
> input for number.

input can read more than numbers. It will take whatever you type
and try to evaluate it as a Python expression. That's why input is
so dangerous and should be avoided in programs you are distributing
since a malicious user could enter a command that destroys your
data (or worse!).

But for your own use you can do things like:

>>> L = input('Enter a list: ')
Enter a list: [1,2,3,4,'five']
>>> print L
[1, 2, 3, 4, 'five']
>>>

In real programs its better to use raw_input and
convert the string to the expected value, hence to read a number:

n = int( raw_input('enter a number: ') )

to read a list you need to split the input string by some agreed
separator, say commas:

L = raw_input('enter a comma separated list: ')
L = L.split(',')

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] Inputting elements of a list

2007-01-22 Thread Luke Paireepinart
vanam wrote:
> For standard input from the keyboard raw_input will be used for string 
> and input for number.Suppose i want to input a list of some elements 
> how could it be done. Actually i am looking for sorting out elements 
> in a list.Below is the given script
> list = [45,4,5]
> list.sort()

Don't call your lists 'list', or a character 'chr' or an int 'int'... 
These are all reserved keywords in Python and if you use them as 
variables you'll overwrite the builtins in that scope.
Example:

 >>> int = 1
 >>> int('1000')
Traceback (most recent call last):
  File "", line 1, in ?
int('1000')
TypeError: 'int' object is not callable


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


[Tutor] Better printing?

2007-01-22 Thread Steve Nelson
Hello,

See below a program that will go through a directory and for each file
print user, group, size and md5sum.

A few questions:

1) It seems to fall over if I pass "." as a directory - how can I stop this?
2) When I wrote the methods I decided to do isafile() checks there,
but subsequently realised that in __main__ it would print out None for
each non-file, so I put the check in here too.  Which is better?  Or
is there a better approach?
3) How can I get this to print in a format that makes it easy to read?
ie tabulated so that the info is presented in aligned columns?

Code follows:

#!/usr/bin/env python

# Standard library imports

import unittest, os, sys, pwd, grp, md5

# Global defines

wp = sys.argv[1]

# Exception classes

# Utility functions

def getSize(fn):
  """Get the size of a file in kb"""
  fp = os.path.join(wp, fn)
  if os.path.isfile(fp):
return os.stat(fp).st_size

def getUser(fn):
  """Get username of file owner."""
  fp = os.path.join(wp, fn)
  if os.path.isfile(fp):
uid = os.stat(fp).st_uid
return pwd.getpwuid(uid).pw_name

def getGroup(fn):
  """Get the group name of the file owner."""
  fp = os.path.join(wp, fn)
  if os.path.isfile(fp):
gid = os.stat(fp).st_gid
return grp.getgrgid(gid).gr_name

def md5Sum(fn):
  """Get md5sum for a file."""
  fp = os.path.join(wp, fn)
  if os.path.isfile(fp):
try:
  fo = open(fp, 'rb')
except (IOError, OSError):
  print "Could not open file '%s', skipping..." % fp
  return None
else:
  m = md5.new(fo.read()).hexdigest()
  fo.close()
return m

# Classes

# Unit tests

class UnitTests(unittest.TestCase):
  """Do not taunt unit tests."""

  def testGetSize(self):
"""Get the size of a file in kb"""
self.assertEqual(getSize("foo"), 24)

  def testGetUser(self):
"""Get the username of the file owner"""
self.assertEqual(getUser("foo"), "nelsonst")

  def testGetGroup(self):
"""Get the group name of the file owner"""
self.assertEqual(getGroup("foo"), "staff")

  def testMd5Sum(self):
"""Get md5sum for file."""
self.assertEqual(md5Sum("foo"), "faac88479f39ba498e827622a2a4d649")

def doTests():
  suite = unittest.makeSuite(UnitTests,'test')
  runner = unittest.TextTestRunner()
  result = runner.run(suite)

if __name__ == "__main__":
  doTests()
  for f in os.listdir(wp):
if os.path.isfile(os.path.join(wp, f)):
  print f, getSize(f), getUser(f), getGroup(f), md5Sum(f)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Are there any MAC OSX python users here?

2007-01-22 Thread ALAN GAULD
Forwarding to list.

--- Tony Cappellini <[EMAIL PROTECTED]> wrote:

> >>They need to start Applications-Utilities->Terminal
> It turned out that the users needed to change the 
> permissions to +x, then the script would be 
> invoked normally.

Ah, but you specifically said it was a command 
line program, so I thought you wanted to run it 
that way. :-)

> writing simple gui launcher to get around that problem.

You could use Applescript for that.

> No- my question to you is-
> I am using a python graphics framework/lib called PyQT/QT.

Is that available for the Mac?

> When I want to deploy it on OSX, how do I get 
> around having to have the user install/compile 
> pyQT/QT on their system?

Unless there are precompiled binaries available 
you don't. I didn't even know Qt was available 
for the Mac.

If you only need a GUI launcher you might be 
better off using the standard Python GUI Tkinter 
which runs on almost any platform that Python 
runs on. Thats why its the standard... wxPython 
also works on Mac but I haven't tried it.

Alan G.




___ 
All new Yahoo! Mail "The new Interface is stunning in its simplicity and ease 
of use." - PC Magazine 
http://uk.docs.yahoo.com/nowyoucan.html
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Better printing?

2007-01-22 Thread Kent Johnson
Steve Nelson wrote:
> Hello,
> 
> See below a program that will go through a directory and for each file
> print user, group, size and md5sum.
> 
> A few questions:
> 
> 1) It seems to fall over if I pass "." as a directory - how can I stop this?

Falls over how?

> 2) When I wrote the methods I decided to do isafile() checks there,
> but subsequently realised that in __main__ it would print out None for
> each non-file, so I put the check in here too.  Which is better?  Or
> is there a better approach?

Are the checks needed in the individual methods? What happens if they 
are passed a non-file? Since you are checking in the main loop, do you care?

> 3) How can I get this to print in a format that makes it easy to read?
> ie tabulated so that the info is presented in aligned columns?

You can print with fixed fields using the string formatting operations.
http://docs.python.org/tut/node9.html#SECTION00910
http://docs.python.org/lib/typesseq-strings.html

If you want something even fancier then look at this recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662

> def getSize(fn):
>   """Get the size of a file in kb"""
>   fp = os.path.join(wp, fn)
>   if os.path.isfile(fp):
> return os.stat(fp).st_size
> 
> def getUser(fn):
>   """Get username of file owner."""
>   fp = os.path.join(wp, fn)
>   if os.path.isfile(fp):
> uid = os.stat(fp).st_uid
> return pwd.getpwuid(uid).pw_name
> 
> def getGroup(fn):
>   """Get the group name of the file owner."""
>   fp = os.path.join(wp, fn)
>   if os.path.isfile(fp):
> gid = os.stat(fp).st_gid
> return grp.getgrgid(gid).gr_name

These functions are using the global variable wp. A better design would 
be to compute the full file path once in the main loop and pass it in.

The above three functions have a lot in common and they are always 
called together. You could combine them into one function that returns a 
tuple of size, user, group.

Kent

> 
> def md5Sum(fn):
>   """Get md5sum for a file."""
>   fp = os.path.join(wp, fn)
>   if os.path.isfile(fp):
> try:
>   fo = open(fp, 'rb')
> except (IOError, OSError):
>   print "Could not open file '%s', skipping..." % fp
>   return None
> else:
>   m = md5.new(fo.read()).hexdigest()
>   fo.close()
> return m
> 
> # Classes
> 
> # Unit tests
> 
> class UnitTests(unittest.TestCase):
>   """Do not taunt unit tests."""
> 
>   def testGetSize(self):
> """Get the size of a file in kb"""
> self.assertEqual(getSize("foo"), 24)
> 
>   def testGetUser(self):
> """Get the username of the file owner"""
> self.assertEqual(getUser("foo"), "nelsonst")
> 
>   def testGetGroup(self):
> """Get the group name of the file owner"""
> self.assertEqual(getGroup("foo"), "staff")
> 
>   def testMd5Sum(self):
> """Get md5sum for file."""
> self.assertEqual(md5Sum("foo"), "faac88479f39ba498e827622a2a4d649")
> 
> def doTests():
>   suite = unittest.makeSuite(UnitTests,'test')
>   runner = unittest.TextTestRunner()
>   result = runner.run(suite)
> 
> if __name__ == "__main__":
>   doTests()
>   for f in os.listdir(wp):
> if os.path.isfile(os.path.join(wp, f)):
>   print f, getSize(f), getUser(f), getGroup(f), md5Sum(f)
> ___
> 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] direction and draw

2007-01-22 Thread Kent Johnson
linda.s wrote:
> I have a segment (two ending points are A and B) which is 0 degree.
> How to draw a segment with 10 degrees and 15 in length?

Presumably you mean, how to draw a segment on screen? Are you using a 
GUI toolkit? Which one?

Kent

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


Re: [Tutor] How to import this program, and other questions

2007-01-22 Thread Dick Moores
At 01:56 AM 1/22/2007, ALAN GAULD wrote:

>--- Dick Moores <[EMAIL PROTECTED]> wrote:
>
> > > ...Is the answer to put all 3 functions inside one big
> > > one?
> > >
> > Probably not, its more likely to be a small function
> > that checks its input parameters and calls one of
> > the 3 worker functions.
>
> > Yes. I just realized that I quoted the link wrong. Try
> > 
>
>OK, Now I've seen the code I need a few more
>clues about how you would expose this code?
>
>It seems at first glance as if your main() function
>could just be renamed and made to use parameters and
>it would act as the driver?
>
> > you meant by "a small function that checks its input
> > parameters and calls one of the 3 worker functions."?
>
>I should have said "one or more" but essentially
>your main function does what I meant. If you rename
>it to something more meaningful and add input parameters
>it should be all you need.
>
>Something ike this:
>
>def precision_divide(x,y,digits):
> s = clnumDiv(x, y, digits)
> s = numberRounding(s, digits)
> s = sciNotation(s)
> return s
>
>Notice I've also made it return s rather than
>print it since thats better practice and more reusable.
>You might want to consider naming x,y
>numerator/denominator to make it more obvious which
>is which. And add a doc string for help() to find.
>
>Then you can just import as usual:
>
>from clnumDivision import precision_divide

Thanks, Alan. Did you see my later reply to myself?

=
I've been experimenting, and came up with this solution. At least it 
works. I slightly rewrote < 
http://www.rcblue.com/Python/clnumDivision_for-web.py> as clnumDiv.py
(< http://www.rcblue.com/Python/clnumDiv.py>) and put it in
E:\Python25\Lib\site-packages\mine and can now import by
from mine.clnumDiv import clnumDiv
or by
from mine.clnumDiv import clnumDiv as div

I can use this in other scripts, or at the interactive prompt:

from mine.clnumDiv import clnumDiv as div
 >>> x = '1234.5678567856785678567856786586'
 >>> y = '-.00098769876897687654654'
 >>> prec = 50
 >>> div(x, y, prec)
'-1.2499437030427053037075454076437920433253956536740E+006'
 >>>

As I said, this works, but is clnumDiv.py organized correctly pythonically?

Also, I'm still hoping for some suggestions about the details of the code.
=

So you can see I'd already pretty much implemented what you suggest 
(I think), except for some naming changes, and the doc string. Any 
comments on the code itself? Are there easier ways to do some of the 
things I've done?

As I said, this program is for myself, and I'd like to keep the 
"clnum" string in the function names (I'm writing a bunch of them). 
Using numerator and denominator as arguments in function defs is a 
lot better than x and y, I agree. Or maybe dividend and divisor.

Dick




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


[Tutor] Can we add labels to tkinter canvas..?

2007-01-22 Thread Asrarahmed Kadri

Hello Folks,

Is it possible to add a Label to tkinter canvas or i'll need to use
create_text method ?

Thanks in anticipation..


Best Regards,

Asrarahmed Kadri


--
To HIM you shall return.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Variables of Variables

2007-01-22 Thread Tino Dai

On 1/18/07, Danny Yoo <[EMAIL PROTECTED]> wrote:


> Rather than storing your data as variables, you could store it in a
> dictionary.  Then you can dynamically access data however you like..

Suggesting a dictionary here is right.

** Stuff deleted about why using variables of variables is bad ***



Actually, I started off with a dictionary with a bunch of parameters. To
give you some background, I writing my
first GUI, and using the parameters in a dictionary to control what box the
GUI displays next. So, it looks
something that looks like this:

data={'position':'middle','next':'self.add_entry_db
(widget,None)','previous':'self.add_entry(widget,None)'}

The dictionary called data gets passed to a button maker function that will
show various buttons depending on
the position value in the data dictionary. The clicked signal is then hooked
up to a callback function (I think that's
what you call it), and the next/previous values get sent up to various
functions. An example one of these various functions
is:

   def add_next_button(self,widget,Data=None):
   self.dbTableName=self.addEntryBox.get_text()
   self.addWin.destroy()
   if type(Data) == type(None):
   print "Why are we here?"
   exit()
   print Data
   Data()

where the Data variable is 'self.add_entry_db(widget,None)'. How do I pass
the Data variable to the add_next_button so
that the contents itself the data variable can execute?

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


Re: [Tutor] Variables of Variables

2007-01-22 Thread Danny Yoo

> Actually, I started off with a dictionary with a bunch of parameters. To
> give you some background, I writing my
> first GUI, and using the parameters in a dictionary to control what box the
> GUI displays next. So, it looks
> something that looks like this:
>
> data={'position':'middle',
>   'next':'self.add_entry_db (widget,None)',
>   'previous':'self.add_entry(widget,None)'}

Hi Tino,


Ok, so it looks like you're trying to encode the idea that, when 'next' is 
pressed, then the content of:

 'self.add_entry_db (widget,None)'

should fire off.  A good way to say this in Python is to say that 'next' 
refers to a function.


Let's do a quick refresher.  Functions can be held without them 
immediately firing off.  For example:

###
>>> def square(x):
... return x * x
...
>>> square

###

You may have left out the parentheses by accident and wondered why Python 
lets us do this: isn't it obvious that functions are meant to be called?


But this time, we are going to leave off the parens deliberately.  *grin* 
If you twist your mind enough, you can analogize this with "numbers" and 
"strings" by thinking of "functions" as just another data type.

And like those other data types, we can actually stuff functions in as 
dictionary values:


>>> cmds = { '^2' : square,
...  '*2' : double }


This 'cmds' is a dictionary from strings to functions!  And, weird as it 
might look, we can do the following:

###
>>> cmds['^2']

>>>
>>> cmds['^2'](42)
1764
>>> cmds['*2'](42)
84
###

That is, we pull the function out of the dictionary, and then call it. 
That's the key idea we can take advantage of for your problem.



Looking back at the definition of data:

###
data={'position':'middle',
   'next':'self.add_entry_db (widget,None)',
   'previous':'self.add_entry(widget,None)'}
###

we can change things a bit, and make 'next' and 'previous' refer to 
functions that eat widgets:

###
 ## [in the context where data is being defined]
 def next_cmd(widget):
 self.add_entry_db(widget,None)

 def previous_cmd(widget):
 self.add_entry(widget, None)

 data = { 'position' : 'middle',
  'next' : next_cmd,
  'previous' : previous_cmd }
###


That is, we're building two functions on the fly and just adding them to 
our data.



Later on, when we are in your callback, the Data values are going to be 
functions that are just waiting to fire.


> The dictionary called data gets passed to a button maker function that 
> will show various buttons depending on the position value in the data 
> dictionary. The clicked signal is then hooked up to a callback function 
> (I think that's what you call it), and the next/previous values get sent 
> up to various functions. An example one of these various functions is:
>
>   def add_next_button(self,widget,Data=None):
>   self.dbTableName=self.addEntryBox.get_text()
>   self.addWin.destroy()
>   if type(Data) == type(None):
>   print "Why are we here?"
>   exit()
>   print Data
>   Data()


Yup.  With the changes above, this becomes:

###
def add_next_button(self,widget,Data=None):
self.dbTableName=self.addEntryBox.get_text()
self.addWin.destroy()
if type(Data) == type(None):
print "Why are we here?"
exit()
Data(widget)
###



> where the Data variable is 'self.add_entry_db(widget,None)'. How do I 
> pass the Data variable to the add_next_button so that the contents 
> itself the data variable can execute?

Learn how to treat functions as data.  That's really what you are asking 
for.  If you have questions about this, please feel free to ask.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Better printing?

2007-01-22 Thread Alan Gauld

"Steve Nelson" <[EMAIL PROTECTED]> wrote 

> def getSize(fn):
>  """Get the size of a file in kb"""
>  fp = os.path.join(wp, fn)
>  if os.path.isfile(fp):
>return os.stat(fp).st_size

One problem with all of these is that you only return 
a value if it is a file. If its not a file you return None
(the default return value). It would be easier to maintain 
if you make the return explicit.

Personally I would probably raise an exception 
(maybe a TypeError) if it's not a file. That puts the onus 
on the client to check that they pass something that 
you can get the size of - or use a try/except to catch 
the invalid entries..

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] Can we add labels to tkinter canvas..?

2007-01-22 Thread Alan Gauld

"Asrarahmed Kadri" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hello Folks,
>
> Is it possible to add a Label to tkinter canvas or i'll need to use
> create_text method ?

What exactly do you expect a label in a canvas to do?
Or to look like?

You can attach a label to a canvas externally by wrapping them
in a single Frame, does that do what you want? Othewise just
putting a bit of text onto the canvas itself seems the best bet.
What would the lavbel do for you that a bit of text wouldn't?

-- 
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] Can we add labels to tkinter canvas..?

2007-01-22 Thread Michael Lange
On Mon, 22 Jan 2007 17:47:14 -
"Alan Gauld" <[EMAIL PROTECTED]> wrote:

> 
> "Asrarahmed Kadri" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> > Hello Folks,
> >
> > Is it possible to add a Label to tkinter canvas or i'll need to use
> > create_text method ?
> 
> What exactly do you expect a label in a canvas to do?
> Or to look like?
> 
> You can attach a label to a canvas externally by wrapping them
> in a single Frame, does that do what you want? Othewise just
> putting a bit of text onto the canvas itself seems the best bet.
> What would the lavbel do for you that a bit of text wouldn't?
> 

Or put a label (or any other widget) onto the canvas using the create_window()
method (though I don't know what's the benefit of a label over some text or 
image).

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


[Tutor] problem with canvas.postscript()

2007-01-22 Thread Asrarahmed Kadri

Hi folks,

I am trying to save a tkinter canvas using canvas.postscript() method...

The thing works fine when the canvas size is small; but it gets cut (from
the top and left side) when the size increases..
Here is the code:

c.postscript(file=filename,height = canvas_height,width =
canvas_width,colormode='color',pagex=200,pagey=250)

The image also gets printed very low on the page in the postscript file..??

Can anybody help me to fix the problem..?

Thanks in anticipation.

Best Regards,
Asrarahmed
--
To HIM you shall return.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] direction and draw

2007-01-22 Thread János Juhász
Dear Linda,

> I have a segment (two ending points are A and B) which is 0 degree.
> How to draw a segment with 10 degrees and 15 in length?
It is very simple with complex numbers:

import math

class vect:
## begin and end are tuples (x, y)
## and represented as complex numbers
def __init__(self, begin, end):
self.begin = complex(begin[0], begin[1])
self.end = complex(end[0], end[1])

def Rotate(self, deg=0):
rad = math.radians(deg)
rot = complex(math.cos(rad), math.sin(rad))
self.end = self.begin + (self.end-self.begin)*rot

def SetLength(self, length):
dist = self.end - self.begin
actlength = math.sqrt(dist.real**2 + dist.imag**2)
dist = dist * length / actlength
self.end = self.begin + dist

def __str__(self):
return '(%.2f, %.2f)->(%.2f, %.2f)' % \
   (self.begin.real, self.begin.imag, self.end.real, 
self.end.imag)


v = vect((10,0),(20,0))
print 'orig:', v
v.Rotate(10)
print 'rotated:', v
v.SetLength(15)
print 'sretched:', v



It seems to be a kind of homework, 
but I wanted to test how can I response in a thread.

All of my earlier responses started new threads in this list like this 
http://mail.python.org/pipermail/tutor/2007-January/052169.html.

Have I remove the '[Tutor]' or '[Tutor] ' from the subject of the response 
? 
Do I need any special about the mail in notes ?


[Tutor] 'elp!!!1Totally Clueless Newbie In Distress   Karl 
Wittgenstein 
[Tutor] 'elp!!!1Totally Clueless Newbie In Distress   Geoframer 
[Tutor] 'elp!!!1Totally Clueless Newbie In Distress   Geoframer 
[Tutor] 'elp!!!1Totally Clueless Newbie In Distress   Geoframer 
[Tutor] 'elp!!!1Totally Clueless Newbie In Distress   Danny Yoo 
[Tutor] 'elp!!!1Totally Clueless Newbie In Distress   Karl 
Wittgenstein 
[Tutor] 'elp!!!1Totally Clueless Newbie In Distress   Karl 
Wittgenstein 
[Tutor] 'elp!!!1Totally Clueless Newbie In Distress   Kent Johnson 
[Tutor] 'elp!!!1Totally Clueless Newbie In Distress   Karl 
Wittgenstein 


I don't understand how these threads are built up. The subject fields 
seems to be identicals.
Is there used anything else than the subject field for recognize the base 
of the response ?

RTFM about how to respond to this list is welcomed with valuable links.


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


[Tutor] metaclass question

2007-01-22 Thread Kim Branson
Hi i'm interested in implementing a factoryclass in python

What i'd like to do is have my factoryClass produce an instance of a  
class with some methods defined in arguments to the factory class.

The classes that are produced have many common methods, but a single  
unique method. This method actually is a series of calls to a c++ api.
Depending on what we are doing with the produced class, i'd like the  
unique method to call api function A, or api function B etc.   
Alternatively the unique method might call A and the B and return a  
dict of the results.

I'm doing this because i'd like all my produced class instances to  
simply have  a calculateResults method which will then go and do the  
right thing.  I don't want to set some values in the init, like A==  
True  and have a if A: call methodA etc statement.

I'm not sure if a factory class is the best way to solve this  
problem, but i can see future cases where the unique function will  
need to do many things with intermediate results before returning the  
results dict.   i think a factory class might be the best way of  
ensuring an extensible design.

So whats the best way to do this. I have found many references to  
creating a class with __metaclass__ = SomeMetaClass,  but i don't see  
how one can pass arguments to the meta class.

An alternative might be to have a class that operates on an existing  
instance and adds the correct method, but this seems slightly clunky,  
and is probably not the python way


Cheers

Kim


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


Re: [Tutor] Are there any MAC OSX python users here?

2007-01-22 Thread Markus Rosenstihl


Am 22.01.2007 um 10:23 schrieb ALAN GAULD:


Forwarding to list.

--- Tony Cappellini <[EMAIL PROTECTED]> wrote:


They need to start Applications-Utilities->Terminal

It turned out that the users needed to change the
permissions to +x, then the script would be
invoked normally.


Ah, but you specifically said it was a command
line program, so I thought you wanted to run it
that way. :-)


writing simple gui launcher to get around that problem.


You could use Applescript for that.


Or, for simple scripts to be started by "double clicking":

http://www.sveinbjorn.org/platypus

It's a lovely program.

regards

Markus


PGP.sig
Description: Signierter Teil der Nachricht
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] metaclass question

2007-01-22 Thread Andreas Kostyrka
Technically, you don't need metaclasses probably:

class A(object):
def methA(self, abc):
pass
def methB(self, def, ghi):
pass
def defaultMethod(self):
raise UnknownMethodError()
def __init__(self, methodName):
self._calc = getattr(self, "meth%s" % methodName, self.defaultMethod)
def calcResult(self, *args, **kw):
return self._calc(*args, **kw)

a=A("A")
b=A("B")

a.calcResult(123)
b.calcResult(234, 345)
a.calcResult(1,2) => TypeError
b.calcResult(1) => TypeError

metaclasses in Python are a way to get control of the class creation
process. E.g. it's quite useful if you need to do some changes to some
classes, no matter what.

(E.g. I've implemented a class where methods can be synchronized (by
using a lock) with a metaclass => the meta class makes sure that all
methods get wrapped with a function that acquires and releases the
needed locks.)

Andreas

* Kim Branson <[EMAIL PROTECTED]> [070122 23:51]:
> Hi i'm interested in implementing a factoryclass in python
> 
> What i'd like to do is have my factoryClass produce an instance of a  
> class with some methods defined in arguments to the factory class.
> 
> The classes that are produced have many common methods, but a single  
> unique method. This method actually is a series of calls to a c++ api.
> Depending on what we are doing with the produced class, i'd like the  
> unique method to call api function A, or api function B etc.   
> Alternatively the unique method might call A and the B and return a  
> dict of the results.
> 
> I'm doing this because i'd like all my produced class instances to  
> simply have  a calculateResults method which will then go and do the  
> right thing.  I don't want to set some values in the init, like A==  
> True  and have a if A: call methodA etc statement.
> 
> I'm not sure if a factory class is the best way to solve this  
> problem, but i can see future cases where the unique function will  
> need to do many things with intermediate results before returning the  
> results dict.   i think a factory class might be the best way of  
> ensuring an extensible design.
> 
> So whats the best way to do this. I have found many references to  
> creating a class with __metaclass__ = SomeMetaClass,  but i don't see  
> how one can pass arguments to the meta class.
> 
> An alternative might be to have a class that operates on an existing  
> instance and adds the correct method, but this seems slightly clunky,  
> and is probably not the python way
> 
> 
> Cheers
> 
> Kim
> 
> 
> ___
> 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] metaclass question

2007-01-22 Thread Alan Gauld

"Kim Branson" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi i'm interested in implementing a factoryclass in python
>
> What i'd like to do is have my factoryClass produce an instance of a
> class with some methods defined in arguments to the factory class.
>
> The classes that are produced have many common methods, but a single
> unique method. This method actually is a series of calls to a c++ 
> api.

It sounds like you could create the basic class as normal but
pass in the appropriate function to the init constructor. Then
instead of making it a method create a metjod that calls that
function, something like this:

class C:
def __init__(self, myfunc):
   self.func = myfunc
def driver(self,params_as_needed):
   return self.func(params_as_needed)
def common1(self)
etc...

Now you can create instances like:

def f1():...
def f2(...)

c = C(f1)
d = C(f2)

etc.

Is that what you want?

Alan G. 


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


Re: [Tutor] metaclass question

2007-01-22 Thread Kent Johnson
Kim Branson wrote:
> Hi i'm interested in implementing a factoryclass in python
> 
> What i'd like to do is have my factoryClass produce an instance of a  
> class with some methods defined in arguments to the factory class.
> 
> The classes that are produced have many common methods, but a single  
> unique method. This method actually is a series of calls to a c++ api.
> Depending on what we are doing with the produced class, i'd like the  
> unique method to call api function A, or api function B etc.   
> Alternatively the unique method might call A and the B and return a  
> dict of the results.
> 
> I'm doing this because i'd like all my produced class instances to  
> simply have  a calculateResults method which will then go and do the  
> right thing.  I don't want to set some values in the init, like A==  
> True  and have a if A: call methodA etc statement.

Do you need to be passing in the unique method, or can you just make a 
base class with the common methods and subclasses that define their 
unique methods? For example,

class Base(object):
   def a(self):
 pass
   def b(self):
 pass
   def calculateResults(self):
 raise NotImplementedError

class A(Base):
   def calculateResults(self):
 return self.a() * self.b()

class B(Base):
   def calculateResults(self):
 return dict(a=self.a(), b=self.b())

Kent

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


Re: [Tutor] direction and draw

2007-01-22 Thread Kent Johnson
János Juhász wrote:
> I wanted to test how can I response in a thread.
> 
> All of my earlier responses started new threads in this list like this 
> http://mail.python.org/pipermail/tutor/2007-January/052169.html.
> 
> Have I remove the '[Tutor]' or '[Tutor] ' from the subject of the response 
> ? 
> Do I need any special about the mail in notes ?

You did fine. You don't have to edit the subject line, just reply to the 
message.

> [Tutor] 'elp!!!1Totally Clueless Newbie In Distress   Karl 
> Wittgenstein 
> 
> 
> I don't understand how these threads are built up. The subject fields 
> seems to be identicals.
> Is there used anything else than the subject field for recognize the base 
> of the response ?

Yes, email contains many headers which contain information about the 
email. Your mail client may let you view the headers, for example in 
Thunderbird you can choose View / Message source to see the actual text 
of the email.

I'm not sure which header(s) are used for the threading; perhaps 
In-Reply-To.

Kent

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


Re: [Tutor] Inputting elements of a list

2007-01-22 Thread Bob Gailer
Luke Paireepinart wrote:
> vanam wrote:
>   
>> For standard input from the keyboard raw_input will be used for string 
>> and input for number.Suppose i want to input a list of some elements 
>> how could it be done. Actually i am looking for sorting out elements 
>> in a list.Below is the given script
>> list = [45,4,5]
>> list.sort()
>> 
>
> Don't call your lists 'list', or a character 'chr' or an int 'int'... 
> These are all reserved keywords in Python
actually they are built-in functions / types. Reserved words (for, if, 
def, ) can't be used for anything else.
>  and if you use them as 
> variables you'll overwrite the builtins in that scope.
> Example:
>
>  >>> int = 1
>  >>> int('1000')
> Traceback (most recent call last):
>   File "", line 1, in ?
> int('1000')
> TypeError: 'int' object is not callable
>
>
> HTH,
> -Luke
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


-- 
Bob Gailer
510-978-4454

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