Re: [Tutor] Tutor Digest, Vol 26, Issue 62

2006-04-19 Thread nywbon001
Quoting [EMAIL PROTECTED]:

> Send Tutor mailing list submissions to
>   tutor@python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
>   http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
>   [EMAIL PROTECTED]
>
> You can reach the person managing the list at
>   [EMAIL PROTECTED]
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
>
>
> Today's Topics:
>
>1. Help Entry  !!! (Cesar Garcia)
>2. creating a tab delim file (Srinivas Iyyer)
>3. Re: Olle-Olla (Kent Johnson)
>4. Re: Tutorial on bitwise Python? (Alan Gauld)
>5. Re: creating a tab delim file (Karl Pfl?sterer)
>6. Version of a .pyc file (Don Taylor)
>7. unit testing raw_input() (Andre Roberge)
>8. Re: Version of a .pyc file (Terry Carroll)
>9. Re: unit testing raw_input() (Michael)
>   10. Re: unit testing raw_input() (Danny Yoo)
>
>
> --
>
> Message: 1
> Date: Tue, 18 Apr 2006 11:14:03 -0700 (PDT)
> From: Cesar Garcia <[EMAIL PROTECTED]>
> Subject: [Tutor] Help Entry  !!!
> To: tutor@python.org
> Message-ID: <[EMAIL PROTECTED]>
> Content-Type: text/plain; charset="iso-8859-1"
>
> Hi !!!
>   Friends, i nedd process Data Entry in python
>   Example
>
>   Entry = 20
>   Result = 20*10
>
>   This Result in Windows (Tkinter)
>   How do you do Think !!!
>
>   Regards
>   Cesar
>   Exmaple
>   from Tkinter import *
>   class MyDialog:
>   def __init__(self, parent):
> top = self.top = Toplevel(parent)
> Label(top, text="Valor").pack()
> self.e = Entry(top)
> self.e.pack(padx=5)
> b = Button(top, text="OK", command=self.ok)
> b.pack(pady=5)
>   def ok(self):
> print "value is", self.e.get()
> self.top.destroy()
>   root = Tk()
> root.update()
> d = MyDialog(root)
> root.wait_window(d.top)
>
>
> -
> New Yahoo! Messenger with Voice. Call regular phones from your PC and save
> big.
> -- next part --
> An HTML attachment was scrubbed...
> URL:
>
http://mail.python.org/pipermail/tutor/attachments/20060418/0bb19d34/attachment-0001.htm
>
> --
>
> Message: 2
> Date: Tue, 18 Apr 2006 11:53:58 -0700 (PDT)
> From: Srinivas Iyyer <[EMAIL PROTECTED]>
> Subject: [Tutor] creating a tab delim file
> To: tutor@python.org
> Message-ID: <[EMAIL PROTECTED]>
> Content-Type: text/plain; charset=iso-8859-1
>
> Hi group,
>  I asked similar questions in the past. I am unable to
> get to the crux of this problem so that I can solve on
> my own. apologies for my ignorance.
>
>
> The problem:
>
> I have 50 tab delim files. Each file has 500 rows and
> 50 columns.
>
> I have to read the first column of each file. Repeat
> the same for 50 files and write a tab delim text file
> containing 500 rows and 50 columns.
>
> code that works through half of the problem:
>
> import glob
>
> files = glob.glob('*.proc')
>
>
> for each in files:
>   f = open(each,'r')
>   da = f.read().split('\n')
>   dat = da[:-1]
>   for m in dat:
> mycol = m.split('\t')[0]
> ..
>
> >From here I am blanked out. Although I can extract the
> first column from each file:I have no idea how to
> store each list.
>
> thought 1. Create an empty string and join each by a
> tab.
> ##
>mycol = ''
>for m in dat:
> mycol = m.split('\t')[0]
> mstr = '\t'.join(mycol)
> how can i append the data from second file to that
> string.
>
>
> could tutors help me with this situation.
>
> Thanks
> srini
>
> __
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com
>
>
> --
>
> Message: 3
> Date: Tue, 18 Apr 2006 14:59:38 -0400
> From: Kent Johnson <[EMAIL PROTECTED]>
> Subject: Re: [Tutor] Olle-Olla
> To: Python Tutor 
> Message-ID: <[EMAIL PROTECTED]>
> Content-Type: text/plain; charset=UTF-8; format=flowed
>
> Andre Engels wrote:
> > 2006/4/18, Kent Johnson <[EMAIL PROTECTED]>:
> >> J?nos Juh?sz wrote:
> >>> Hi All,
> >>>
> >>> Is it possible to replace the print statement with one of mine function ?
> >>>
> >>> In reality, I would like to replace the print in my PyCrust app with the
> >>> log.write() function.
> >> Best: Use a good editor to change your print statements to log.write()
> >
> > Even better: Use a good editor to change your print statements to
> > myprint() and then def myprint() to be log.write(). This has the
> > advantage that if (for example) you want prints later to be "usually
> > log.write() but if redFlagHighestWarning is True, then both
> > log.write() and print()", you don't need to go through all this again,
> > but just have to change myprint().
>
> Or use the logging module, w

Re: [Tutor] pyexpat

2006-04-19 Thread Andre Engels
2006/4/18, Danny Yoo <[EMAIL PROTECTED]>:

> H Can you send a link to the text that's causing performance
> issues?  It might be possible that someone here might isolate the
> performance problem.  (Hey, it happened before with BeautifulSoup...
> *grin*)

I have sent the text (and another text that did not cause problems) to
Danny; sending it to this list was disallowed because of length (about
1.5M for the 'slow' case and about half of that for the 'fast' one).

--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pyexpat

2006-04-19 Thread Danny Yoo


On Wed, 19 Apr 2006, Andre Engels wrote:

> 2006/4/18, Danny Yoo <[EMAIL PROTECTED]>:
>
>> H Can you send a link to the text that's causing performance
>> issues?  It might be possible that someone here might isolate the
>> performance problem.  (Hey, it happened before with BeautifulSoup...
>> *grin*)
>
> I have sent the text (and another text that did not cause problems) to 
> Danny; sending it to this list was disallowed because of length (about 
> 1.5M for the 'slow' case and about half of that for the 'fast' one).

Can you provide a web link somewhere?  That will help solve the 
distribution problem by turning it from a "push" to a "pull".
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] net ettiquette and sentence sorting/homework

2006-04-19 Thread Danny Yoo
>> *
> i want to write a function which will sort the sentence by the length of 
> each word in the sentece, short length first.please help.

Hi Nywbon,

First: please do not reply to the whole email digest.  The point of a 
reply is to continue a previous conversation.  Please be aware that not 
everyone has high-speed internet access: quoting the whole archive 
actually can strain some people's network bandwidth, if not their good 
humor and patience.

Since you are starting a new question, start a new email to create a new 
"thread" of conversation.


Second (and related to the first): please use a useful subject line.  It 
helps when people try to learn from the mailing list archives at:

 http://mail.python.org/pipermail/tutor/



Finally, to get back to your question:

> i want to write a function which will sort the sentence by the length of 
> each word in the sentece, short length first.please help.

This looks very much like a homework question.  We can not help you much 
with this.  The only thing we can really do is try to guide you 
indirectly.

Here are a few things you can do:

 1.  Write some concrete test examples of the problem statement and
 what you'd like to get out of it.

 2.  Show us some of the code that you've written so far, so we can at
 least point out areas of improvement.


For point one, let's take a totally different problem and demonstrate. 
Let's say we wanted to write a function to turn a number from 0-9 to a 
string of the Esperanto rendition.


If we wanted to write example cases, we'd imagine what calling this 
function for interesting inputs would look like.  For example:

 translate(0) --> "nul"
 translate(1) --> "unu"
 translate(2) --> "du"
 ...
 translate(9) --> "nau"

I use the arrow notation '-->' as an ad-hoc way of saying "I expect to get 
this value on the right hand side if everything is going well with my 
function".


Can you write examples of your own for your problem?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] OOPs Concept

2006-04-19 Thread Kaushal Shriyan
Hi All

I wanted to understand about OOPs Concept in Python in a easy way,
Please explain me with an example

I have been reading http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm
but at the moment still the concept is not clear

Thanks in Advance

Regards

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


Re: [Tutor] GUI

2006-04-19 Thread Chris Lasher
It's a dual license. If you use Qt in non-commercial software, the GPL
applies and you pay no licensing fees. If you use Qt in commercial
software, licensing fees are due to TrollTech.

Chris

On 4/18/06, Alan Gauld <[EMAIL PROTECTED]> wrote:
> [snip]
> TrollTech own Qt, their licensing arrangements seem a tad complex to me.
> Try their web site.
>
> Alan G.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re-instantiate within __init__

2006-04-19 Thread Jan Eden
Hi,

is it correct that an object cannot be re-instantiated within it's __init__ 
method?

I tried:

class Omega:
def Display(self):
print self

class Alpha(Omega):
def __init__(self):
self = Beta()

class Beta(Omega):
def __init__(self):
pass

objectus = Alpha()
objectus.Display()

which prints

<__main__.Alpha instance at 0x54d50>

Background: I need to create a new object upon instantiation when a database 
query returns no records. The rest of the program should just use the new 
object.

Is there any way to achieve this? I can always place the equivalent of 'self = 
Beta()' in the Display() function:

def Display(self):
if self.not_found:
self = Beta()
self.Display()
return
print self

 but this does not look very elegant.

Thanks,

Jan
-- 
Any sufficiently advanced technology is insufficiently documented.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re-instantiate within __init__

2006-04-19 Thread Kent Johnson
Jan Eden wrote:
> Hi,
> 
> is it correct that an object cannot be re-instantiated within it's __init__ 
> method?
> 
> I tried:
> 
> class Omega:
> def Display(self):
> print self
> 
> class Alpha(Omega):
> def __init__(self):
> self = Beta()
> 
> class Beta(Omega):
> def __init__(self):
> pass
> 
> objectus = Alpha()
> objectus.Display()
> 
> which prints
> 
> <__main__.Alpha instance at 0x54d50>

Binding to self in a method just changes the local value of self, it 
doesn't change the object itself. The only thing special about 'self' is 
the way it is bound before the method is entered; inside the method it 
is a local name like any other.

To bind objectus to a new object you have to assign to objectus. But I 
suspect you are really looking for a way to change the behaviour of the 
object bound to objectus.
> 
> Background: I need to create a new object upon instantiation when a
database query returns no records. The rest of the program should just
use the new object.
> 
> Is there any way to achieve this? I can always place the equivalent
> of
'self = Beta()' in the Display() function:
> 
> def Display(self):
> if self.not_found:
> self = Beta()
> self.Display()
> return
> print self
> 
>  but this does not look very elegant.

I don't understand what you are trying to do, but here are some ideas:
- have Display() look at self.not_found itself, or pass self.not_found 
as a parameter to display.
- use a factory method to create a class of the correct type
- change self.Display to be the correct function
- you can change the class of an object at runtime by assigning to its 
__class__ attribute. This may be what you are looking for but I suspect 
there is a simpler, less magic solution
- I'm not sure why classes are needed at all here.

Can you give a more complete example of what you are trying to do? Even 
if your code above worked the way you want it to, it wouldn't do 
anything interesting, since Alpha and Beta have exactly the same 
attributes and behaviour.

Kent

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


Re: [Tutor] OOPs Concept

2006-04-19 Thread Matthew White
Even though I am still new to python, I've recently had an insight as
to what makes OOP different from procedural programming.

Let's take perl for example.  A variable in perl is like a bowl.  It's an
empty vessel you can put things in.  You can change the contents of
the bowl, you can empty the bowl but it doesn't really *do* anything.
It has no real attributes aside from the fact that it's a container.

So when I create a variable in perl it looks like this:

$x = 'hello'

If I want to make the first letter of the value of $x a capital letter,
I have to use a function to do it:

$y = ucfirst($x)

now $y contains the value 'Hello'

In python one doesn't really create variables, one creates objects.
Sring objects, list objects, etc.  And objects are cool because they can
do things.  They are more than just merely bowls, they are like swiss
army knives.  So in python, if I say:

x = 'hello'

Then I can do all sorts of things with x:

x.capitalize()  -> 'Hello'
x.swapcase() -> 'HELLO'
x.count('l') -> 2

This is just a very small example but I hope that my example can help
you understand what objects are what makes OOP different from procedural
programming.

-mtw

On Wed, Apr 19, 2006 at 06:07:27PM +0530, Kaushal Shriyan ([EMAIL PROTECTED]) 
wrote:
> Hi All
> 
> I wanted to understand about OOPs Concept in Python in a easy way,
> Please explain me with an example
> 
> I have been reading http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm
> but at the moment still the concept is not clear
> 
> Thanks in Advance
> 
> Regards
> 
> Kaushal
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Matthew White - District Systems Administrator
Tigard/Tualatin School District
503.431.4128

"The greatest thing in this world is not so much where we are, but in
what direction we are moving."   -Oliver Wendell Holmes

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


Re: [Tutor] OOPs Concept

2006-04-19 Thread Kaushal Shriyan
On 4/19/06, Matthew White <[EMAIL PROTECTED]> wrote:
> Even though I am still new to python, I've recently had an insight as
> to what makes OOP different from procedural programming.
>
> Let's take perl for example.  A variable in perl is like a bowl.  It's an
> empty vessel you can put things in.  You can change the contents of
> the bowl, you can empty the bowl but it doesn't really *do* anything.
> It has no real attributes aside from the fact that it's a container.
>
> So when I create a variable in perl it looks like this:
>
> $x = 'hello'
>
> If I want to make the first letter of the value of $x a capital letter,
> I have to use a function to do it:
>
> $y = ucfirst($x)
>
> now $y contains the value 'Hello'
>
> In python one doesn't really create variables, one creates objects.
> Sring objects, list objects, etc.  And objects are cool because they can
> do things.  They are more than just merely bowls, they are like swiss
> army knives.  So in python, if I say:
>
> x = 'hello'
>
> Then I can do all sorts of things with x:
>
> x.capitalize()  -> 'Hello'
> x.swapcase() -> 'HELLO'
> x.count('l') -> 2
>
> This is just a very small example but I hope that my example can help
> you understand what objects are what makes OOP different from procedural
> programming.
>
> -mtw
>
> On Wed, Apr 19, 2006 at 06:07:27PM +0530, Kaushal Shriyan ([EMAIL PROTECTED]) 
> wrote:
> > Hi All
> >
> > I wanted to understand about OOPs Concept in Python in a easy way,
> > Please explain me with an example
> >
> > I have been reading http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm
> > but at the moment still the concept is not clear
> >
> > Thanks in Advance
> >
> > Regards
> >
> > Kaushal
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
>
> --
> Matthew White - District Systems Administrator
> Tigard/Tualatin School District
> 503.431.4128
>
> "The greatest thing in this world is not so much where we are, but in
> what direction we are moving."   -Oliver Wendell Holmes
>
>

Thanks Matthew
Just wanted to know
x.count('l') -> 2 Here 2 means what I didnot understood this
and also does x is a object and capitalize(), swapcase()  and
count('l') are methods, is that correct what i understand

Awaiting your earnest reply

Regards

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


Re: [Tutor] OOPs Concept

2006-04-19 Thread Matthew White
On Wed, Apr 19, 2006 at 09:10:41PM +0530, Kaushal Shriyan ([EMAIL PROTECTED]) 
wrote:
> Thanks Matthew
> Just wanted to know
> x.count('l') -> 2 Here 2 means what I didnot understood this
> and also does x is a object and capitalize(), swapcase()  and
> count('l') are methods, is that correct what i understand

yes, count(), capitalize(), and swapcase() are called methods.

The count() method counts the number of the given string in the object.

x = 'hello'
x.count('l') -> 2
x.count('h') -> 1

y = 'good morning'
y.count('o') -> 3
y.count('oo')-> 1

you can find out which methods belong to an object using the dir()
function and can get help for a method by using the help() function:

% python
Python 2.3.5 (#2, Sep  4 2005, 22:01:42) 
[GCC 3.3.5 (Debian 1:3.3.5-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 'hello'
>>> dir(x)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__',
'__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__str__', 'capitalize', 'center', 'count', 'decode', 'encode',
'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha',
'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rstrip',
'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']
>>> help(x.swapcase)
Help on built-in function swapcase:

swapcase(...)
S.swapcase() -> string

Return a copy of the string S with uppercase characters
converted to lowercase and vice versa.
>>> 


-mtw

-- 
Matthew White - District Systems Administrator
Tigard/Tualatin School District
503.431.4128

"The greatest thing in this world is not so much where we are, but in
what direction we are moving."   -Oliver Wendell Holmes

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


[Tutor] Fw: anybody tried Google calendar?

2006-04-19 Thread Alan Gauld
Contained in a reply about a Google calendar issue...

> http://www.google.com/support/calendar/bin/answer.py?answer=37083&query=free+busy&topic=0&type=f
>

Note the answer.py

Looks like Google have expanded their use of Python from test scripts and
config/admin to mainstream web pages, albeit their help system...

Alan G.

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


[Tutor] Some help with properties and accessor functions....

2006-04-19 Thread Mark True
class SOFileIndexRecord(object):    def __init__(self, so):    self._so=so    def _get_code(self):    return self._so.code    def _set_code(self, value):    self._so.code=value
    testCode=property(_get_code, _set_code) # What does this do?    def _get_fileName(self):    return self._so.fileName    def _set_fileName(self, value):    self._so.fileName=value    fileName=property(_get_fileName, _set_fileName) # What does this do?
I am playing with SQLobject, and I managed to cobble together some code for it based on information in the FAQ but I am not understanding entirely what I am doingcan someone help? I don't really understand what setting properties does and how I access the defined get/set functions in this object. 
Any info would be wonderful, thanks in advance!--Mark
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] [Summary] Re: unit testing raw_input()

2006-04-19 Thread Andre Roberge
Thank you Michael, Danny and Alan for your suggestions.
I've included below my summary of the three very different
suggestions, my brief analysis of them, and my conclusion.
Anyone is free and welcome to comment!

On 4/18/06, Andre Roberge <[EMAIL PROTECTED]> wrote:
> Hi all-
>
> Suppose I had a function like the following:
>
> def y_n(prompt="Answer yes or no"):
> while True:
> answer = raw_input(prompt)
> if answer in ['y', 'Y', 'yes']:
> print "You said yes!"
> break
> elif answer in ['n', 'N', 'no']:
> print "You said no!"
> break
> else:
> print "%s is an invalid answer."%answer
>
> How could I go about to write an automated test for it?
>
> André
>
Alan Gauld suggested to create a data file that simulate
possible user responses and to use redirection to feed
the data to the program.  Assuming the function to be
tested is in y_n.py, it would look like the following:

$ python y_n.py < fake_user_data > test_result

Then, I assume I would do an automated comparison between
"test_result" and some "expected_result" file to ensure everything
is ok.

This, in my opinion, is the "cleanest" solution.  However, it may
not scale well if one wants to build a test suite with many
functions/methods, some of which require some user-input.
Ideally, one should be able to change the order in which unit tests
are run; with this approach, both the test suite and the user data
file would probably have to be change in sync.



Danny Yoo suggested to change the function to be tested, to
include an extra parameter, i.e. go from
def y_n(prompt="Answer yes or no"):
to
def y_n(prompt="Answer yes or no", raw_input=raw_input):

To quote Danny:
But now we can hardcode particular inputs by sending y_n() a mock
"raw_input" that returns precooked values.

###
def yes1_raw_input(prompt):
return "y"

def yes2_raw_input(prompt):
return "Y"

def yes3_raw_input(prompt):
return "yes"

def yes4_raw_input(prompt):
return "YES"
###
[end quote]

My first reaction is "Neat! :-)".   However,
this is only usable if one has access to the original
function.  If one uses a "library" function like y_n()
(for example, there is a similar function in the livewires module
which some of you probably know)
which is not, in principle, modifyable, this approach fails.



Michael (last name unknown) suggests another approach, which
shares some similarities with Danny's.  Here's Michael's
edited/truncated explanation:

You create a mock for raw_input, put the above code inside a module and rebind
raw_input in the module before calling your function.

ie:
(CONTENTS of y_n.py)
def y_n(prompt="Answer yes or no"):
   while True:
   answer = raw_input(prompt)
   if answer in ['y', 'Y', 'yes']:
   print "You said yes!"
   break
[snip]
(END CONTENTS of y_n.py)

[Michael's explanation using the interpreter is modified below]

Then, one can have a test function in a separate file

--- begin test function
import y_n
def raw_input_mock(prompt): # create a mock
return "n"
y_n.raw_input = raw_input_mock  # rebind the name inside the module
y_n.y_n() # Run, this now calls our mock instead of the real raw_input
--- end test function
[end of quote]

Note that y_n() should probably return a string
(instead of using a print statement)
so that the output can be compared with the expected result;
otherwise, one has to redirect the output to a file
and do a comparison, as I mentioned with Alan's explanation.

This is a rather clever method; I would never have thought
of rebinding y_n.raw_input in this way.

The only weakness that I see with this approach is if one
wants to test a function like y_n() knowing that it ask
the user for some input ... but not knowing what function
it uses to do so.  This can be the case if one has a compiled
library with only the interface (what values can be passed
to the functions and how; what are the expected outputs) being
known.  Danny's approach would also not work here, whereas
Alan's would.

As it is, I will be working on a very small project with another
programmer, where I will be responsible to write some
unit tests.  I have access to the source code (so I know
which function is used to get input from the user), but I do not want
the other programmer to have to change the way his code
is written simply to accommodate my tests.
The other programmer's code will be in a single module; similarly,
I want to write a single test module myself - without having to
worry about keeping a separate data file.
Therefore, I will go with Michael's approach.

Thanks to everyone, and I hope that I didn't misrepresent any
of the three solutions proposed.  It's been fun!

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


Re: [Tutor] Re-instantiate within __init__

2006-04-19 Thread Alan Gauld
> is it correct that an object cannot be re-instantiated within it's 
> __init__ method?

There are some tricks you can pull but the object is actually instantiated
before the init gets called. Really init is for initialisation of the 
instance,
it's not a true constructor.

> Background: I need to create a new object upon instantiation
> when a database query returns no records.

I'd probably create a factory function to do this that
returns the appropriate type of instance.

def makeDbResponseInstance(queryStatus):
  if queryStatus:
 return DBClass()
  else: return Emptyclass()

If the two classes are subclassed from a common ancestor you
might put the factory into the class as a class method, but I'd
probably just keep it as a function. That keeps the two class's
definitions clean and decoupled from the instantiation decision
which isn't really their responsibility - children don't choose to be
born!.

Alan G. 

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


Re: [Tutor] Some help with properties and accessor functions....

2006-04-19 Thread Alan Gauld
class SOFileIndexRecord(object):
def __init__(self, so):
self._so=so

def _get_code(self):
return self._so.code
def _set_code(self, value):
self._so.code=value
testCode=property(_get_code, _set_code) # What does this do?

It says that testCode is a property of SOFileIndexRecord
A property looks like a data attribute from the user of the 
class's point of view but internallty it is accessed via the 
get/set methods.

Thus I can do:

s = SOFileIndexRecord(mySo):
s.testCode = myCode   # actually does s._setCode(myCode)
print s.testCode# actually s._getCode()

properties allow for creation of read only attributes in Python 
by having a null set method.(Of course you can still cheat and 
use the 'hidden' methods, or even the real data attributes. Buit 
if everyone behaves properly it can help a wee bit.

HTH,

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


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


Re: [Tutor] GUI

2006-04-19 Thread Hugo González Monteverde
> Ok,
> If I can get it for free, I might as well go with say wxPython. Thanks

Yes, free as in beer, as in speech, and cross platform. Oh, and better 
documented.

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


[Tutor] [Linux] open a file in any home "~" ?

2006-04-19 Thread learner404
Hello,

I want to read a configuration file from a small python app (user preferences).

The ".myapp.conf" is in the home folder of the user.

if I do:

f=open("/home/user1/.myapp.conf","r")  #it works

obviously I won't know the home user folder name then I wanted to use:

f=open("~/.myapp.conf","r")  # but it returns a IOError: [Errno 2] No such file or directory: 

How can I do to access this file whatever the user is ? 

Thanks for your help.

---


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


Re: [Tutor] [Linux] open a file in any home "~" ?

2006-04-19 Thread Matthew White
os.getenv('HOME') will return the user's home directory as long as that
environment variable is set.

you can also use the pwd module:

>>> pwd.getpwnam('mtw')
('mtw', 'x', 1000, 1000, ',,,', '/home/mtw', '/bin/bash')

-mtw

On Wed, Apr 19, 2006 at 07:55:14PM +0200, learner404 ([EMAIL PROTECTED]) wrote:
> Hello,
> 
> I want to read a configuration file from a small python app (user
> preferences).
> 
> The ".myapp.conf" is in the home folder of the user.
> 
> if I do:
> 
> f=open("/home/user1/.myapp.conf","r")  #it works
> 
> obviously I won't know the home user folder name then I wanted to use:
> 
> f=open("~/.myapp.conf","r")  # but it returns a IOError: [Errno 2] No such
> file or directory:
> 
> How can I do to access this file whatever the user is ?
> 
> Thanks for your help.
> 
> ---

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


-- 
Matthew White - District Systems Administrator
Tigard/Tualatin School District
503.431.4128

"The greatest thing in this world is not so much where we are, but in
what direction we are moving."   -Oliver Wendell Holmes

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


Re: [Tutor] [Linux] open a file in any home "~" ?

2006-04-19 Thread w chun
>  f=open("~/.myapp.conf","r")  # but it returns a IOError: [Errno 2] No such
> file or directory:
>
>  How can I do to access this file whatever the user is ?

use os.path.expanduser(path)

http://www.python.org/doc/2.4.3/lib/module-os.path.html

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

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


Re: [Tutor] Re-instantiate within __init__

2006-04-19 Thread Danny Yoo
> I tried:
>
> class Omega:
>def Display(self):
>print self
>
> class Alpha(Omega):
>def __init__(self):
>self = Beta()
>
> class Beta(Omega):
>def __init__(self):
>pass
>
> objectus = Alpha()
> objectus.Display()
>
> which prints
>
> <__main__.Alpha instance at 0x54d50>
>
> Background: I need to create a new object upon instantiation when a 
> database query returns no records. The rest of the program should just 
> use the new object.

I think you're looking for the "Strategy" design pattern: your class has a 
default behavior, but in a certain case, you want it to switch behaviors 
to something else.

http://www.exciton.cs.rice.edu/JavaResources/DesignPatterns/StrategyPattern.htm

That is, rather than Alpha being a subclass of Omega, Alpha can have an 
instance of Omega:

#
class Alpha:
 def __init__(self):
 self.strategy = DefaultStrategy()

 def display(self):
 self.strategy.display()


class DefaultStrategy:
 def display(self):
 print "I am the default strategy"
#

The advantage here is that the strategy can be swapped out just by setting 
self.strategy to something else.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [Linux] open a file in any home "~" ?

2006-04-19 Thread learner404
It works great, thanks very much to the three of you for these light-speed answers ... I love this list ! 
Wesley, I've just pre-order your new edition "Core Python programming" on amazon France, it looks great. :)

Thanks 
 
On 19/04/06, w chun <[EMAIL PROTECTED]> wrote:
>  f=open("~/.myapp.conf","r")  # but it returns a IOError: [Errno 2] No such> file or directory:>>  How can I do to access this file whatever the user is ?use os.path.expanduser
(path)http://www.python.org/doc/2.4.3/lib/module-os.path.htmlhope this helps!-- wesley- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001http://corepython.comwesley.j.chun :: wescpy-at-gmail.com
python training and technical consultingcyberweb.consulting : silicon valley, cahttp://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [Linux] open a file in any home "~" ?

2006-04-19 Thread Paidhi Aiji
Hi,

You can use expanduser() from os.path for this:

import os.path
homedir = os.path.expanduser('~user1')
file_to_open = os.path.join(homedir, '.myapp.conf')
f = open(file_to_open, 'r')


Regards,
  -Markus-


Quoting learner404 <[EMAIL PROTECTED]>:

> Hello,
>
> I want to read a configuration file from a small python app (user
> preferences).
>
> The ".myapp.conf" is in the home folder of the user.
>
> if I do:
>
> f=open("/home/user1/.myapp.conf","r")  #it works
>
> obviously I won't know the home user folder name then I wanted to use:
>
> f=open("~/.myapp.conf","r")  # but it returns a IOError: [Errno 2] No such
> file or directory:
>
> How can I do to access this file whatever the user is ?
>
> Thanks for your help.
>
> ---
>




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


Re: [Tutor] [Linux] open a file in any home "~" ?

2006-04-19 Thread Alan Gauld
> The ".myapp.conf" is in the home folder of the user.
> ...
> obviously I won't know the home user folder name then I wanted to use:
> How can I do to access this file whatever the user is ?

You can get the user name using getpass.getuser() as described in 
the OS topic of my tutor under the Securiity heading.

You can also try using os.getenv() or the os.environ variable 
to look up the HOME environment variable, also discussed 
in the OS topic.

HTH,

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


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


Re: [Tutor] [Linux] open a file in any home "~" ?

2006-04-19 Thread w chun
we are all happy to help.  it is really good that you were able to get
it working so fast!  also, if you want to do any kind of pattern
matching with * or ?, then check out the "glob" module.

merci!  "le livre" does not look that good from here... it is a mess
and i have to clean it up before giving it to the publisher!  :-)

cheers,
-wesley


On 4/19/06, learner404 <[EMAIL PROTECTED]> wrote:
> It works great, thanks very much to the three of you for these light-speed
> answers ... I love this list !
>
>  Wesley, I've just pre-order your new edition "Core Python programming" on
> amazon France, it looks great. :)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] GUI

2006-04-19 Thread R. Alan Monroe
>> If I can get it for free, I might as well go with say wxPython. Thanks

> Yes, free as in beer, as in speech, and cross platform. Oh, and better 
> documented.

Sadly, you still pay for it in RAM usage :^)

Alan

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


Re: [Tutor] GUI

2006-04-19 Thread Liam Clarke
Hmm? How so? I'm using a whole lot of raw wxPython mixed with
Pythoncard for a project, and the entire process sits at 7Mb RAM usage
idle. WinXP btw.

Considering my small command line appns to start/stop Windows services
written in C use just over 1Mb, 7Mb isn't overly bad.

The other good thing about wxPython is stuff like Pythoncard and Wax,
although development on Pythoncard seems to have slowed right down,
Kevin Altis got busy, I guess; Wax is nice looking but... not very
well documented... It's great being able to use Pythoncard for the not
overly complicated stuff, but with the wxPython still lurking beneath
the surface.

Regards,

Liam Clarke

On 4/20/06, R. Alan Monroe <[EMAIL PROTECTED]> wrote:
> >> If I can get it for free, I might as well go with say wxPython. Thanks
>
> > Yes, free as in beer, as in speech, and cross platform. Oh, and better
> > documented.
>
> Sadly, you still pay for it in RAM usage :^)
>
> Alan
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Brain In Vice: Why is this so fun to me?

2006-04-19 Thread doug shawhan
I think I'm going to have to suck it up and learn some regular expressions.

I have finally gotten my script (using the excellent pyserial module)
to behave. Most of my troubles as enumerated here before were utterly
self-induced. Apparently one cannot watch the execution of one's script
through another program without affecting it's outcome in unforseen
ways. (Sound familiar Herr Schroedinger? :-)

Now that I am actually extracting data in a fairly predictable way, I
am at the point where I need to parse it! I have some output here
(modified to show  the ESC and NUL characters.) 

When I pull data from the port, the remote computer sends it in one
long string per screen: newlines are not painted in by using the
expected x\0a that I had hoped for! No easy readlines() fun for me.
Instead I get:

ESC=(  1. ESC=($4x2, 6-239 (3.9L) ..ESC=(a03252  ESC=(k0
ESC=)  2. ESC=))8-318 (5.2L) ..ESC=)a03242  ESC=)k0
ESC=*  3. ESC=*)8-360 (5.9L) ..ESC=*a03351  ESC=*k    0
ESC=+  4. ESC=+$4x4, 6-239 (3.9L) ..ESC=+a03240  ESC=+k    0
ESC=,  5. ESC=,)8-318 (5.2L) ..ESC=,a03243  ESC=,k    0
ESC=-  6. ESC=-)8-360 (5.9L) ..ESC=-a03352  ESC=-k    0
ESC=.  7. ESC=.aCH8299  ESCTNULESC)NULESC=%
LINEESCTNULESC=&  R = RELIST 
 = NONE    

I have broken it up for ease of viewing. I need to split the string
where ESC= , k  and 0 are found, but ESC= ,k and 0 are seperated
by various spaces, parentheis and other characters that are apparently
used to mark the end of the line until the next ESC is found, thereby
displaying a new line (note how the character after the first ESC on
each line is repeated after the ESC on the end.

I cannot for the life of me figure out a pythonic way (read: using the
split() builtin) to scan for instances of these characters in such and
such order and proximity. I know this is what regex is for, but I have
no experience.  I have obtained a copy of "Mastering Regular
Expressions" but thought I would inquire here first for caveats and
tips as the book is larger than my brain, and I haven't used the re
module, ever. 

Why in the world does this make me so happy? :-)~
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Brain In Vice: Why is this so fun to me?

2006-04-19 Thread Liam Clarke
Hi Doug,

Best tip ever is your_python_dir\tools\scripts\redemo.py

Interactive regexes. :)

This is pretty good as well - http://www.amk.ca/python/howto/regex/

Good luck,

Liam Clarke

On 4/20/06, doug shawhan <[EMAIL PROTECTED]> wrote:
> I think I'm going to have to suck it up and learn some regular expressions.
>
>  I have finally gotten my script (using the excellent pyserial module) to
> behave. Most of my troubles as enumerated here before were utterly
> self-induced. Apparently one cannot watch the execution of one's script
> through another program without affecting it's outcome in unforseen ways.
> (Sound familiar Herr Schroedinger? :-)
>
>  Now that I am actually extracting data in a fairly predictable way, I am at
> the point where I need to parse it! I have some output here (modified to
> show  the ESC and NUL characters.)
>
>  When I pull data from the port, the remote computer sends it in one long
> string per screen: newlines are not painted in by using the expected x\0a
> that I had hoped for! No easy readlines() fun for me. Instead I get:
>
>  ESC=(  1. ESC=($4x2, 6-239 (3.9L)
> ..ESC=(a03252
> ESC=(k0
>  ESC=)  2. ESC=))8-318 (5.2L)
> ..ESC=)a03242
> ESC=)k0
>  ESC=*  3. ESC=*)8-360 (5.9L)
> ..ESC=*a03351
> ESC=*k0
>  ESC=+  4. ESC=+$4x4, 6-239 (3.9L)
> ..ESC=+a03240
> ESC=+k0
>  ESC=,  5. ESC=,)8-318 (5.2L)
> ..ESC=,a03243
> ESC=,k0
>  ESC=-  6. ESC=-)8-360 (5.9L)
> ..ESC=-a03352
> ESC=-k0
>  ESC=.  7. ESC=.aCH8299  ESCTNULESC)NULESC=% LINEESCTNULESC=&  R =
> RELIST   = NONE
>
>  I have broken it up for ease of viewing. I need to split the string where
> ESC= , k  and 0 are found, but ESC= ,k and 0 are seperated by various
> spaces, parentheis and other characters that are apparently used to mark the
> end of the line until the next ESC is found, thereby displaying a new line
> (note how the character after the first ESC on each line is repeated after
> the ESC on the end.
>
>  I cannot for the life of me figure out a pythonic way (read: using the
> split() builtin) to scan for instances of these characters in such and such
> order and proximity. I know this is what regex is for, but I have no
> experience.  I have obtained a copy of "Mastering Regular Expressions" but
> thought I would inquire here first for caveats and tips as the book is
> larger than my brain, and I haven't used the re module, ever.
>
>  Why in the world does this make me so happy? :-)~
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Reqiest Centre - Adding New Call

2006-04-19 Thread Liam Clarke
Hi,

The categories of calls under this drop down box, are they going to
increase anytime soon, or shall I go with what's there?

Regards,

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


Re: [Tutor] [Linux] open a file in any home "~" ?

2006-04-19 Thread Alan Gauld
>  How can I do to access this file whatever the user is ?
>
> use os.path.expanduser(path)

Neat Wesley, I've  never noticed that one before.

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


Re: [Tutor] Brain In Vice: Why is this so fun to me?

2006-04-19 Thread Alan Gauld
> I cannot for the life of me figure out a pythonic way (read: using the
> split() builtin) to scan for instances of these characters in such and 
> such
> order and proximity. I know this is what regex is for,

I'm afraid so, it looks like the time has come to import re.

>  I have obtained a copy of "Mastering Regular Expressions"

Good book but probably overkill unless you get really serious

> I would inquire here first for caveats and tips

Build them up gradually, test them at the >>> prompt or using
the tool that comes with Python. Don;t forget the power of building
a negative of what you want and then searching for the inverse.
Finally remember that match() is usually the wrong function to
use - it only searches at the beginning of the string!

And, of course, I have a topic on regex :-)

Good luck!

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




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


[Tutor] Splitting a number into even- and odd- numbered digits

2006-04-19 Thread Carroll, Barry
Greetings:

I am writing a function that accepts a string of decimal digits, calculates a 
checksum and returns it as a single character string.  
The first step in the calculation is to split the input into two strings: the 
even- and odd- numbered digits, respectively.  The least significant digit is 
defined as odd.  

The following code fragment does the job but seems sort of brutish and 
inelegant to me:

>>>
>>> s = '987654321'
>>> odd = ''
>>> for c in s[::-2]:
... odd = c + odd
... 
>>> s = s[:-1]
>>> even = ''
>>> for c in s[::-2]:
... even = c + even
... 
>>> odd
'97531'
>>> even
'8642'
>>>

Is there a better (i.e. more Pythonic) way to do this?  

Thanks in advance for all your help.

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.
-Quarry worker's creed


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


Re: [Tutor] Splitting a number into even- and odd- numbered digits

2006-04-19 Thread John Fouhy
On 20/04/06, Carroll, Barry <[EMAIL PROTECTED]> wrote:
> The following code fragment does the job but seems sort of brutish and 
> inelegant to me:
>
> >>>
> >>> s = '987654321'
> >>> odd = ''
> >>> for c in s[::-2]:
> ... odd = c + odd
> ...
> >>>

String slicing will actually produce strings :-)

eg:

>>> s = '987654321'
>>> s1, s2 = s[::-2], s[-2::-2]
>>> s1
'13579'
>>> s2
'2468'

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


Re: [Tutor] Version of a .pyc file

2006-04-19 Thread Don Taylor
Terry Carroll wrote:

>>How can I tell if a .pyc file was built with 2.3 or 2.4?
> 
> 
> There's a "Magic Number" in the first 2 or 4 bytes, (depending on whether 
> you consider the \r\n part of the MN).
> 
> 
f = open("pycfile.pyc", "rb")
magictable = {'\x3b\xf2\r\n': "2.3", '\x6d\xf2\r\n' : "2.4"}
magic = f.read(4)
release = magictable.get(magic,"unknown")
print "Python release:", release
> 
> Python release: 2.4
> 

I have used Terry's code to write a script to find all of the the .pyc 
files on my system that were compiled with the 2.3 version of the 
compiler, and I have removed these files.

But my underlying problem still occurs: somewhere somebody is calling 
for the 2.3 version of the Python vm .dll and not finding it.  This is 
happening under Pydev/Eclipse and my only recourse is to blow Eclipse 
away using Task Manager.

So maybe I have  a .pyd file somewhere that is a 2.3 extension.

Is there a way to examine .pyd files to see if they were built for 
Python 2.3?

Finally, are there any other possible file extension types that I should 
be looking at?

Thanks,

Don.

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


Re: [Tutor] Version of a .pyc file

2006-04-19 Thread Kent Johnson
Don Taylor wrote:
> Finally, are there any other possible file extension types that I should 
> be looking at?

.pyo is like a .pyc but compiled with optimizations on.

Kent

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


Re: [Tutor] Reqiest Centre - Adding New Call

2006-04-19 Thread Liam Clarke
Hi all, I do apologise for this,

This was an email that has nothing to do with Python or the tutor
list, so my apologies to all. Somehow I managed to send it to the
wrong recepient.

(And my thanks to Bob for being brave enough to attempt to answer what
would be a hopelessly vague question. :-) )

Regards,

an embarrassed Liam Clarke

On 4/20/06, Bob Gailer <[EMAIL PROTECTED]> wrote:
> Liam Clarke wrote:
> > Hi,
> >
> > The categories of calls under this drop down box, are they going to
> > increase anytime soon, or shall I go with what's there?
> >
> I'm in the dark. What is "this drop down box"?
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor