Re: [Tutor] Ide To use? Other extras to install?

2010-10-11 Thread Alan Gauld

"Jorge Biquez"  wrote

I am in the process of leaving Windows as my environment and moving 
to Ubuntu or a Mac. For a few months I will have to continue working 
under windows until I finish my moving process. Anyway, I would like 
to start using and IDE that I can install at least in Windows and 
Linux .


What would be the IDE you recommend me to install that would be 
almost transparent to be using in both platforms?


See the recent thread on IDEs.

If you are not comfortable with the "3 window IDE(*)" - which is 
probably
the most natural one to use in Linux - then I'd say go with Eclipse 
and

PyDev plugin because it works pretty much identically across OS's.

Also Eclipse supports multiple languages so you can do your HTML,
SQL and Python all in one tool.

(*) - An editor window, a testing terminal and a >>> terminal.

HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OpenMP

2010-10-11 Thread Stefan Behnel

Alan Gauld, 09.10.2010 19:50:

Now, the bad news is that so far as I know the python interpreter
does not expose its threading model to the OS to even if you use
threads the interpreter itself will still be running on a single CPU
core. :-(


Python's threads are native system threads. They can run fully concurrent 
on a multiprocessor system with the only exception that only one thread can 
use the interpreter at a time. However, everything that runs in C code can 
run in parallel and I/O will usually also work in parallel (which is the 
main use case of threads anyway).


Stefan

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hiding Superclass Methods

2010-10-11 Thread Alan Gauld


"Denis Gomes"  wrote

  I have a basic python question.  I am writing an n dimensional 
vector
class by inheriting from the builtin python list object.  I want to 
be
able to hide the parent object's methods in the derived class 
instances.


Doing so would break the Liskofff Substitution Principle which says
you should be able to use your subclass anywhere that the parent
class can be used. This is a very bad thing!

If you want to expose a reduced set of operations, rather than an
extended set, then inheritance is the wriong solution. You should
consider using delegation instead. Create a list indside your class
and forward any requests for the operations you do want to the
list object.

The only snag with delegation in this scenartio is that you have
to write an awful lot of one-liner methods. To get round that
you can use setattr() and getattr() combined with a list of allowed
operation names. Check the operation is in the list and then
forward the request by name. That can save a lot of coding!

HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Rounding a Python float to the nearest half integer

2010-10-11 Thread Sithembewena Lloyd Dube
Thanks everyone.

On Fri, Oct 8, 2010 at 11:44 PM, Wayne Werner wrote:

> On Fri, Oct 8, 2010 at 7:58 AM, Sithembewena Lloyd Dube  > wrote:
>
>> I realise that one cannot have a half integer :) I meant how would one
>> round off to the first decimal nearest to either 0.5, or a whole number.
>>
>> Ugh...does anyone get what I'm trying to articulate? :)
>
>
> sample input/output cases are always useful.
>
> -Wayne
>



-- 
Regards,
Sithembewena Lloyd Dube
http://www.lloyddube.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Rounding a Python float to the nearest half integer

2010-10-11 Thread Shantanoo
===
round(...)
round(number[, ndigits]) -> floating point number

Round a number to a given precision in decimal digits (default 0
digits).
This always returns a floating point number.  Precision may be negative.
===

>>> round(1.23423,2)
1.23
>>> round(1.23623,2)
1.24


HTH.

On Mon, Oct 11, 2010 at 13:51, Sithembewena Lloyd Dube wrote:

> Thanks everyone.
>
>
> On Fri, Oct 8, 2010 at 11:44 PM, Wayne Werner wrote:
>
>> On Fri, Oct 8, 2010 at 7:58 AM, Sithembewena Lloyd Dube <
>> zebr...@gmail.com> wrote:
>>
>>> I realise that one cannot have a half integer :) I meant how would one
>>> round off to the first decimal nearest to either 0.5, or a whole number.
>>>
>>> Ugh...does anyone get what I'm trying to articulate? :)
>>
>>
>> sample input/output cases are always useful.
>>
>> -Wayne
>>
>
>
>
> --
> Regards,
> Sithembewena Lloyd Dube
> http://www.lloyddube.com
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Rounding a Python float to the nearest half integer

2010-10-11 Thread Sithembewena Lloyd Dube
Thanks Shantanoo, finally got the hang of this.

2010/10/11 शंतनू (Shantanoo) 

> ===
> round(...)
> round(number[, ndigits]) -> floating point number
>
> Round a number to a given precision in decimal digits (default 0
> digits).
> This always returns a floating point number.  Precision may be
> negative.
> ===
>
> >>> round(1.23423,2)
> 1.23
> >>> round(1.23623,2)
> 1.24
>
>
> HTH.
>
> On Mon, Oct 11, 2010 at 13:51, Sithembewena Lloyd Dube 
> wrote:
>
>> Thanks everyone.
>>
>>
>> On Fri, Oct 8, 2010 at 11:44 PM, Wayne Werner wrote:
>>
>>> On Fri, Oct 8, 2010 at 7:58 AM, Sithembewena Lloyd Dube <
>>> zebr...@gmail.com> wrote:
>>>
 I realise that one cannot have a half integer :) I meant how would one
 round off to the first decimal nearest to either 0.5, or a whole number.

 Ugh...does anyone get what I'm trying to articulate? :)
>>>
>>>
>>> sample input/output cases are always useful.
>>>
>>> -Wayne
>>>
>>
>>
>>
>> --
>> Regards,
>> Sithembewena Lloyd Dube
>> http://www.lloyddube.com
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>


-- 
Regards,
Sithembewena Lloyd Dube
http://www.lloyddube.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dict question

2010-10-11 Thread Francesco Loffredo
Thank you, Alan and Dave, for your spotting this weak point in my 
understanding of Python!


On 11/10/2010 2.11, Dave Angel wrote:

On 2:59 PM, Alan Gauld wrote:


"Francesco Loffredo"  wrote


did, Roelof's code would work perfectly, and you could store in a list
all the subsequent changes of a dictionary without calling them with
different names.


You don;'t need dfifferent names. Provided the name creates a
new object inside the loop you can reuse the same name.
Roeloff's problem was that he only created one object, outside
his loop.

lst = []
for n in range(3):
obj = {}
I didn't know that this creates a new obj if obj already exists, I 
thought it would just update it. That's my mistake.

Does this mean that if I write:
obj = {}
obj = {}
obj = {}
then I'll create 3 different dictionaries, with the name obj referring 
to the third?



obj[n] = str(n)
lst.append(obj)

Creats a list of 3 distinct dictionaries but only uses one name - obj.

Ok, this does not lose too much in elegance.


I understand that if .append() stored a copy of the dict in the list,
you will end up with lots of copies and a huge amount of memory used by
your list, but that's exactly what will happen if you make those copies
yourself. But you wouldn't have to devise a way to generate a new name
for the dictionary every time you need to update it.


Python uses references throughout, what you are suggesting would
be a change to the normal way that Python uses names.
I needed a hint about what is "the normal way that Python uses names", 
thank you.





Probably more importantly, if a language only implemented copies, you
couldn't have references without some different syntax. On the other
hand, with Python, everything's a reference, and if you want a copy, you
make one when you need it. You never do for immutables, and only you
know when you need it for mutable objects.

DaveA
Thank you too, Dave. I thought that to make a copy you would have to 
create a different name, and this sounded too cumbersome for me...


Francesco
Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com
Versione: 9.0.862 / Database dei virus: 271.1.1/3188 -  Data di rilascio: 
10/10/10 08:34:00
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using contents of a document to change file names, (was Re: how to extract data only after a certain ...)

2010-10-11 Thread Josep M. Fontana
 Sorry about the confusion with the subject line. I was receiving messages
in digest mode and I copied and pasted the wrong heading in my previous
message. Now I have written the heading corresponding to my initial message.
I have also changed the settings for this list from the digest mode to the
default mode because it is easier to manage if you are participating in
threads.

OK, first thanks Emile and Bob for your help.

Both of you noticed that the following line of code returned a string
instead of a list as it would be expected from using .readlines():

open(r'/Volumes/DATA/Documents/workspace/GCA/CORPUS_TEXT_LATIN_1/FileNamesYears.txt').readlines()

returns --> ['A-01,1374\rA-02,1499\rA-05,1449\rA-06,1374\rA-09, ...']

Yes, I had not noticed it but this is what I get. You guessed correctly that
I am using a Mac. Just in case it might be useful, I'm also using PyDev in
Eclipse (I figured since I'm learning to program, I can start using an IDE
that will grow with my programming skills).

I tried your suggestion of using .split() to get around the problem but I
still cannot move forward. I don't know if my implementation of your
suggestion is the correct one but here's the problem I'm having. When I do
the following:

-

fileNameCentury = open(r
'/Volumes/DATA/Documents/workspace/GCA/CORPUS_TEXT_LATIN_1/FileNamesYears.txt'
.split('\r'))
dct = {}
for pair in fileNameCentury:
key,value = pair.split(',')
dct[key] = value
print dct
--

I get the following long error message:

---

pydev debugger: warning: psyco not available for speedups (the debugger will
still work correctly, but a bit slower)

pydev debugger: starting

Traceback (most recent call last):

  File
"/Applications/eclipse/plugins/org.python.pydev.debug_1.6.3.2010100513/pysrc/pydevd.py",
line 1145, in 

debugger.run(setup['file'], None, None)

  File
"/Applications/eclipse/plugins/org.python.pydev.debug_1.6.3.2010100513/pysrc/pydevd.py",
line 916, in run

execfile(file, globals, locals) #execute the script

  File "/Volumes/DATA/Documents/workspace/GCA/src/file_name_change.py", line
2,

in 

fileNameCentury =
open(r'/Volumes/DATA/Documents/workspace/GCA/CORPUS_TEXT_LATIN_1/FileNamesYears.txt'.split('\n'))

TypeError: coercing to Unicode: need string or buffer, list found


Before reporting this problem, I did some research on the newline problems
and I saw that you can set the mode in open() to 'U' to handle similar
problems. So I tried the following:

   >>>fileNameCentury = open(r
'/Volumes/DATA/Documents/workspace/GCA/CORPUS_TEXT_LATIN_1/FileNamesYears.txt',
"U")

   >>>output = fileNameCentury.readlines()

   >>>print output


Interestingly I get closer to the solution but with a little twist:

['A-01,1374\n', 'A-02,1499\n', 'A-05,1449\n', 'A-06,1374\n', 'A-09,1449\n',
'B-01,1299\n', 'B-02,1299\n', 'B-06,1349\n'...]

That is, now I do get a list but as you can see I get the newline character
as part of each one of the strings in the list. This is pretty weird. Is
this a general problem with Macs?


Josep M.



From: Emile van Sebille 
To: tutor@python.org

On 10/10/2010 12:35 PM Josep M. Fontana said...

>
> fileNameCentury = open(r
>
'/Volumes/DATA/Documents/workspace/GCA/CORPUS_TEXT_LATIN_1/FileNamesYears.txt'
> ).readlines()
>
> Where 'FileNamesYears.txt' is the document with the following info:
>
> A-01, 1278
> A-02, 1501
> ...
> N-09, 1384
>
> I get a list of the form
['A-01,1374\rA-02,1499\rA-05,1449\rA-06,1374\rA-09,
> ...]
>
> Would this be a good first step to creating a dictionary?

Hmmm... It looks like you got a single string -- is that the output from
read and not readlines?  I also see you're just getting \r which is the
Mac line terminator.  Are you on a Mac, or was 'FileNamesYears.txt'
created on a Mac?.  Python's readlines tries to be smart about which
line terminator to expect, so if there's a mismatch you could have
issues related to that.  I would have expected you'd get something more
like: ['A-01,1374\r','A-02,1499\r','A-05,1449\r','A-06,1374\r','A-09, ...]

In any case, as you're getting a single string, you can split a string
into pieces, for example, print "1\r2\r3\r4\r5".split("\r").  That way
you can force creation of a list of strings following the format
"X-NN," each of which can be further split with xxx.split(",").
Note as well that you can assign the results of split to variable names.
 For example, ky,val = "A-01, 1278".split(",") sets ky to A-01 and val
to 1278.  So, you should be able to create an empty dict, and for each
line in your file set the dict entry for that line.

Why don't you start there and show us what you get.

HTH,

Emile
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Basics

2010-10-11 Thread Francesco Loffredo

On 28/09/2010 12.05, Alan Gauld wrote:

If you are already fairly experienced you might find the Python Challenge
web site a fun way to learn too.


www.pythonchallenge.com

I didn't know of this site, it's VERY interesting and funny!

Thank you, Alan.
Francesco
Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com
Versione: 9.0.862 / Database dei virus: 271.1.1/3188 -  Data di rilascio: 
10/10/10 08:34:00
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using contents of a document to change file names, (was Re: how to extract data only after a certain ...)

2010-10-11 Thread Christian Witts

On 11/10/2010 13:46, Josep M. Fontana wrote:
I tried your suggestion of using .split() to get around the problem 
but I still cannot move forward. I don't know if my implementation of 
your suggestion is the correct one but here's the problem I'm having. 
When I do the following:


-

fileNameCentury = 
open(r'/Volumes/DATA/Documents/workspace/GCA/CORPUS_TEXT_LATIN_1/FileNamesYears.txt'.split('\r'))

dct = {}
for pair in fileNameCentury:
key,value = pair.split(',')
dct[key] = value
print dct

--

I get the following long error message:

fileNameCentury = 
open(r'/Volumes/DATA/Documents/workspace/GCA/CORPUS_TEXT_LATIN_1/FileNamesYears.txt'.split('\n')) 



TypeError: coercing to Unicode: need string or buffer, list found




What you should be doing is:

fileNameCentury = 
open('/Volumes/DATA/Documents/workspace/GCA/CORPUS_TEXT_LATIN_1/FileNamesYears.txt', 
'r')

dct = {}
for line in fileNameCentury: #File objects have built-in iteration
key, value = line.strip().split(',')
dct[key] = value

What you were doing originally was splitting the input filename for the 
open function (hence the error message stating `need string or buffer, 
list found`.  If you wish to read in the entire file and then split it 
on newline characters you would do fileObject.read().splitlines() but it 
is more efficient to create your file object and just iterate over it 
(that way there is only 1 line at a time stored in memory and you're not 
reading in the entire file first).


It's not a Mac problem, just a problem with how you were going about it.

Hope that helps.

--
Kind Regards,
Christian Witts

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] WRITING XLS FROM OS.WALK()

2010-10-11 Thread Susana Iraiis Delgado Rodriguez
Hello members!

Thank you all of you for taking the time to answer to my question. I didn´t
expect it will create the controversy we just had in this topic. I don't
mind for the comments of re-inventing the wheel, I'm new in python,
documentation is good but programmers' experience is even better.

The intention of using the os.walk() is because I'm creating a sort of
directory crawler to find every file with the extensions I'm looking for, so
am I in the rigth direction?
The other question is about the excel files management, if I want to
manipulate this data to work it in Excel should I look for an excel library
in python right?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] WRITING XLS FROM OS.WALK()

2010-10-11 Thread Joel Goldstick
On Mon, Oct 11, 2010 at 9:37 AM, Susana Iraiis Delgado Rodriguez <
susana.delgad...@utzmg.edu.mx> wrote:

> Hello members!
>
> Thank you all of you for taking the time to answer to my question. I didn´t
> expect it will create the controversy we just had in this topic. I don't
> mind for the comments of re-inventing the wheel, I'm new in python,
> documentation is good but programmers' experience is even better.
>
> The intention of using the os.walk() is because I'm creating a sort of
> directory crawler to find every file with the extensions I'm looking for, so
> am I in the rigth direction?
> The other question is about the excel files management, if I want to
> manipulate this data to work it in Excel should I look for an excel library
> in python right?
>
>
>
> I would write the file as csv.  Then, excel, or any other spreadsheet can
read the file.  Python offers csv support, its easy to understand, produces
small files, and being a text format, it is easy to debug problems.
-- 
Joel Goldstick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hiding Superclass Methods

2010-10-11 Thread Denis Gomes
Thank you both for your responses.  I do have one other question if I use
the method both of you describe. How do I go about implementing slicing and
indexing for an object in python?  A list object innately has them and that
is really why I wanted to use it.  I would appreciate it if you can point me
to something.

Denis

On Mon, Oct 11, 2010 at 4:13 AM, Alan Gauld wrote:

>
> "Denis Gomes"  wrote
>
>
>  I have a basic python question.  I am writing an n dimensional vector
>> class by inheriting from the builtin python list object.  I want to be
>> able to hide the parent object's methods in the derived class instances.
>>
>
> Doing so would break the Liskofff Substitution Principle which says
> you should be able to use your subclass anywhere that the parent
> class can be used. This is a very bad thing!
>
> If you want to expose a reduced set of operations, rather than an
> extended set, then inheritance is the wriong solution. You should
> consider using delegation instead. Create a list indside your class
> and forward any requests for the operations you do want to the
> list object.
>
> The only snag with delegation in this scenartio is that you have
> to write an awful lot of one-liner methods. To get round that
> you can use setattr() and getattr() combined with a list of allowed
> operation names. Check the operation is in the list and then
> forward the request by name. That can save a lot of coding!
>
> HTH,
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hiding Superclass Methods

2010-10-11 Thread Adam Bark

On 11/10/10 15:29, Denis Gomes wrote:
Thank you both for your responses.  I do have one other question if I 
use the method both of you describe. How do I go about implementing 
slicing and indexing for an object in python?  A list object innately 
has them and that is really why I wanted to use it.  I would 
appreciate it if you can point me to something.

Denis
You can use __getslice__, __setslice__ etc. methods. They're detailed in 
the list docstrings. Here's an example of using __getslice__


>>> dir([])
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', 
'__delslice__', '__doc__', '__eq__', '__format__', '__ge__', 
'__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', 
'__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', 
'__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', 
'__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 
'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

>>> print [].__getslice__.__doc__
x.__getslice__(i, j) <==> x[i:j]

   Use of negative indices is not supported.
>>> print [].__setslice__.__doc__
x.__setslice__(i, j, y) <==> x[i:j]=y

   Use  of negative indices is not supported.
>>> class TestSlice(object):
... def __getslice__(self, i, j):
... print i, j
...
>>> t = TestSlice()
>>> t[2:3]
2 3

HTH,
Adam.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Ide To use? Other extras to install?

2010-10-11 Thread Dave Kuhlman
On Mon, Oct 11, 2010 at 09:06:14AM +0100, Alan Gauld wrote:
> 

> "Jorge Biquez"  wrote
> 
> >I am in the process of leaving Windows as my environment and moving 
> >to Ubuntu or a Mac. For a few months I will have to continue working 
> >under windows until I finish my moving process. Anyway, I would like 
> >to start using and IDE that I can install at least in Windows and 
> >Linux .
> >
> >What would be the IDE you recommend me to install that would be 
> >almost transparent to be using in both platforms?
> 
> See the recent thread on IDEs.

Here is a comparison of Python IDEs:

http://www.infoworld.com/d/developer-world/infoworld-review-nine-fine-python-development-tools-374

This is a multi-page article.  The subsequence pages give some
details about each IDE.

- Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hiding Superclass Methods

2010-10-11 Thread Dave Kuhlman
On Mon, Oct 11, 2010 at 08:25:24AM +0200, Knacktus wrote:
> 
> Am 11.10.2010 06:24, schrieb Denis Gomes:
> >Hi Everyone,
> >
> >I have a basic python question.  I am writing an n dimensional vector
> >class by inheriting from the builtin python list object.  I want to be
> >able to hide the parent object's methods in the derived class instances.
> Why inheriting then?
> Another approach to reusing exisiting methods is to wrap them into your 
> newly defined methods. Here you would not inherit from a list, but 
> create a list in your class (composition). E.g.
> 
> class MyVector(object):
> 
> def __init__(self):
> self.data = []
> 
> def append_data(self, new_data):
> self.data.append(new_data)
> 
> Actually I use this all the time. And I used this before I knew about 
> inheritance.

It's a good technique.  And, it's called delegation.  For more on
delegation, see this:

http://en.wikipedia.org/wiki/Delegation_(programming)

Also see Alan's message in this same thread.

- Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hiding Superclass Methods

2010-10-11 Thread Walter Prins
On 11 October 2010 15:55, Adam Bark  wrote:

> You can use __getslice__, __setslice__ etc. methods. They're detailed in
> the list docstrings. Here's an example of using __getslice__
>
> >>> dir([])
> ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
> '__delslice__', '__doc__', '__eq__', '__format__', '__ge__',
> '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__',
> '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__',
> '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
> '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__',
> '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append',
> 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
> >>> print [].__getslice__.__doc__
> x.__getslice__(i, j) <==> x[i:j]
>

Just to add, you might try using "help()" on the various objects and methods
(also objects) to see more contextual and/or formatted information, e.g.

help([])

or help([].__getslice__)

etc.

Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] WRITING XLS FROM OS.WALK()

2010-10-11 Thread Walter Prins
On 11 October 2010 14:37, Susana Iraiis Delgado Rodriguez <
susana.delgad...@utzmg.edu.mx> wrote:

> The other question is about the excel files management, if I want to
> manipulate this data to work it in Excel should I look for an excel library
> in python right?
>
>
Yes. I already mentioned one (in my view good) option in my original reply
to you.   The xlwt module works quite well for generating Excel files (with
expectable limitations) from any platform that Python's available on (e.g.
including non-Windows.)  and thus does not require Excel to be available on
the machine you're producing the file on.

If however you are running on Windows and have Excel installed, you could
consider driving the real Excel via COM automation, which will guarantee you
get desired results including formatting, charts etc, and will ensure you
have full access to all the functionality Excel exposes via its COM object
model.

If your requirements on the other hand simple enough then Joel's suggestion
to use CSV is probably preferable.  (The KISS principle: "Keep It Small &
Simple")

There's also the possibility to look into generating .xlsx files (e.g. XML
based Office format files.)  Theoretically you should be able to generate
the correctly structured XML independent of Excel and have it open in
Excel.  I suspect that may be rather painful though (have never tried this
myself) andam almost reluctant to even mention this option, so caveat
emptor.

Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hiding Superclass Methods

2010-10-11 Thread Denis Gomes
I understand where to go from here. Thanks to all who responded.  Appreciate
it.

Denis
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Ide To use? Other extras to install?

2010-10-11 Thread Jed Smith
On Sun, Oct 10, 2010 at 9:31 PM, Jorge Biquez  wrote:

> What would be the IDE you recommend me to install that would be almost
> transparent to be using in both platforms?

For transparency on multiple platforms, I need to reiterate the
suggestion to use the "traditional" IDE - editor, interactive,
testing. You're not going to find a comfortable experience, in my
opinion, on multiple platforms. Something is always compromised out to
make the product platform-agnostic.

On Mac OS X, I've been extremely pleased with TextMate, simply for its
rsync+ssh bundle (which I have bound to Shift+Cmd+S). I still have the
interactive IPython and testing terminal, but when I'm ready to send
code up to the server, Shift+Cmd+S. I don't use much else from
TextMate.

TextMate also has a save-when-I-lose-focus feature which is quite useful.

> What extras do you recommend me to install? (plug ins, libraries, etc)

IPython. Very, very IPython.

-- 
Jed Smith
j...@jedsmith.org
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Help installing HLS Player

2010-10-11 Thread p4ddy

Hi,

I have a HLS Player written in python but whenever I try to install it, I
get this error

"ImportError: No module named setuptools"

So I downloaded setuptools-0.6c11.zip and tried to install it, again i got
this error

"ImportError: No module named distutils.util"

So I went back and downloaded python2.4-devel-2.4-1pydotorg.i386.rpm and
installed it.

I have python2.4 installed in the machine (linux) but apparently
python2.4-devel didn't find it and gave dependency error. So I installed it
using

"rpm -i --nodeps python2.4-devel-2.4-1pydotorg.i386.rpm"

and it got installed. Now when i went back to install setuptools, i m
getting the same problem :(

I m pretty new to python, so can anybody help me on this? I'm pretty
frustrated already !!
-- 
View this message in context: 
http://old.nabble.com/Help-installing-HLS-Player-tp29933359p29933359.html
Sent from the Python - tutor mailing list archive at Nabble.com.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help installing HLS Player

2010-10-11 Thread Wayne Werner
On Mon, Oct 11, 2010 at 6:56 AM, p4ddy  wrote:

>
> Hi,
>
> I have a HLS Player written in python but whenever I try to install it, I
> get this error
>
> "ImportError: No module named setuptools"
>
> So I downloaded setuptools-0.6c11.zip and tried to install it, again i got
> this error
>
> "ImportError: No module named distutils.util"
>
> So I went back and downloaded python2.4-devel-2.4-1pydotorg.i386.rpm and
> installed it.
>
> I have python2.4 installed in the machine (linux) but apparently
> python2.4-devel didn't find it and gave dependency error. So I installed it
> using 


What version of linux are you using? Python 2.4 is insanely old, and you
should have some type of package manager. There is very little reason to be
manually installing from rpm and zip file.

That being said, this question has *very* little to do with Python and
almost everything to do with linux, and even though many of us are familiar
with it, you'll probably have more success asking your local Linux Users
Group (LUG): http://www.linux.org/groups/

HTH,
Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] If/else in Python 2.6.5 vs. Python 2.4.3

2010-10-11 Thread aeneas24

Hi,

I have code that works fine when I run it on Python 2.6.5, but I get an 
"invalid syntax" error in Python 2.4.3. I'm hoping you can help me fix it.

The line in question splits a chunk of semi-colon separated words into separate 
elements.

rgenre = re.split(r';', rf.info["genre"] if "genre" in rf.info else []

I get a syntax error at "if" in 2.4.3. 

I tried doing the following but it doesn't work (I don't understand why). 



if "genre" in rf.info:
  rgenre = re.split(r';', rf.info["genre"])
else:
  []


And I tried this, too: 


if "genre" in rf.info:
  rgenre = re.split(r';', rf.info["genre"])
if "genre" not in rf.info:
  []

Both of these cause problems later on in the program, specifically 
"UnboundLocalError: local variable 'rgenre' referenced before assignment", 
about this line in the code (where each of these is one of the 30 possible 
genres):

rg1, rg2, rg3, rg4, rg5, rg6, rg7, rg8, rg9, rg10, rg11, rg12, rg13, rg14, 
rg15, rg16, rg17, rg18, rg19, rg20, rg21, rg22, rg23, rg24, rg25, rg26, rg27, 
rg28, rg29, rg30= rgenre + ["NA"]*(30-len(rgenre[:30]))

Thanks for any help--I gave a little extra information, but I'm hoping there's 
a simple rewrite of the first line I gave that'll work in Python 2.4.3.

Thanks,

Tyler



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] WRITING XLS FROM OS.WALK()

2010-10-11 Thread Susana Iraiis Delgado Rodriguez
Hello Walter and members:

I'm working with csv to handle excel, my other was useful to do my new cvs
file. When I open the output file, it has all the information I need, but
all of my lines have the filepath separate by comes, even though it's
supposed to be a complete string; for example: C,:,\,i,n,d,i,c,e,.,s,h,p all
the others have the same format.
Besides I need a row to put in each cell the column names, with:
 
c.writerow(["Archivo","x_min","x_max","y_min","y_max","geometria","num_ele","prj","estructura
bd","extent","fecha_modificacion","maquina_host"]). But all tha names gather
in the same row and I want my pathfile to place under the "Archivo" column,
but I couldn't do it.



2010/10/11 Walter Prins 

>
>
> On 11 October 2010 14:37, Susana Iraiis Delgado Rodriguez <
> susana.delgad...@utzmg.edu.mx> wrote:
>
>> The other question is about the excel files management, if I want to
>> manipulate this data to work it in Excel should I look for an excel library
>> in python right?
>>
>>
> Yes. I already mentioned one (in my view good) option in my original reply
> to you.   The xlwt module works quite well for generating Excel files (with
> expectable limitations) from any platform that Python's available on (e.g.
> including non-Windows.)  and thus does not require Excel to be available on
> the machine you're producing the file on.
>
> If however you are running on Windows and have Excel installed, you could
> consider driving the real Excel via COM automation, which will guarantee you
> get desired results including formatting, charts etc, and will ensure you
> have full access to all the functionality Excel exposes via its COM object
> model.
>
> If your requirements on the other hand simple enough then Joel's suggestion
> to use CSV is probably preferable.  (The KISS principle: "Keep It Small &
> Simple")
>
> There's also the possibility to look into generating .xlsx files (e.g. XML
> based Office format files.)  Theoretically you should be able to generate
> the correctly structured XML independent of Excel and have it open in
> Excel.  I suspect that may be rather painful though (have never tried this
> myself) andam almost reluctant to even mention this option, so caveat
> emptor.
>
> Walter
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using contents of a document to change file names, (was Re: how to extract data only after a certain ...)

2010-10-11 Thread Alan Gauld


"Josep M. Fontana"  wrote

I tried your suggestion of using .split() to get around the problem 
but I

still cannot move forward.




fileNameCentury = open(r
'/Volumes/DATA/Documents/workspace/GCA/CORPUS_TEXT_LATIN_1/FileNamesYears.txt'
.split('\r'))


You are trying to split the filename not the contents of the file!


Interestingly I get closer to the solution but with a little twist:

['A-01,1374\n', 'A-02,1499\n', 'A-05,1449\n', 'A-06,1374\n', 
'A-09,1449\n',

'B-01,1299\n', 'B-02,1299\n', 'B-06,1349\n'...]

That is, now I do get a list but as you can see I get the newline 
character
as part of each one of the strings in the list. This is pretty 
weird. Is

this a general problem with Macs?


No, this is what you would expect. Reading from a file will give you 
the \n

character, you can use strip() (or rstrip()) to remove it.

HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dict question

2010-10-11 Thread Alan Gauld


"Francesco Loffredo"  wrote


lst = []
for n in range(3):
obj = {}

I didn't know that this creates a new obj if obj already exists, I
thought it would just update it. That's my mistake.


Yes you have to remember that in Python, unlike C etc,
names are not aliases for memory locations. They are keys
into a namespace dictionary. So the value that the dictionary
refers to can change for any given name - even the type of
object can change.


Does this mean that if I write:
obj = {}
obj = {}
obj = {}
then I'll create 3 different dictionaries, with the name obj 
referring

to the third?


Yes and the first and second will be garbage collected since
there is nothing referring to them now.


obj[n] = str(n)
lst.append(obj)

Creats a list of 3 distinct dictionaries but only uses one name - 
obj.

Ok, this does not lose too much in elegance.


Yes and I could have made it even more elegant with:

lst = []
for n in range(3):
lst.append({n:str(n)})  # no explicit object name needed at all!

And even more tight with:

lst = [ {n:str(n)} for n in range(3)]

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] If/else in Python 2.6.5 vs. Python 2.4.3

2010-10-11 Thread Wayne Werner
On Mon, Oct 11, 2010 at 12:10 PM,  wrote:

>  
>
> rgenre = re.split(r';', rf.info["genre"] if "genre" in rf.info else []
>
> I get a syntax error at "if" in 2.4.3.
>

That's because you're using the ternary operator that was not available in
2.4: http://www.python.org/dev/peps/pep-0308/


>
> I tried doing the following but it doesn't work (I don't understand why).
>
> if "genre" in rf.info:
>   rgenre = re.split(r';', rf.info["genre"])
> else:
>   []
>
>
> And I tried this, too:
>
>
> if "genre" in rf.info:
>   rgenre = re.split(r';', rf.info["genre"])
> if "genre" not in rf.info:
>   []
>
> Both of these cause problems later on in the program, specifically
> "UnboundLocalError: local variable 'rgenre' referenced before assignment",
> about this line in the code (where each of these is one of the 30 possible
> genres):
>

The problem isn't with your logic expression - it's because on the else case
you never assign anything to rgenre, you simply state 'empty list' - not
'set rgenre to be an empty list'.

if 'genre' in rf.info:
rgenre = re.split(r';', rf.info['genre'])
else:
rgenre = []

will work on all(?) versions of python - and 2.4 certainly.

HTH,
Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Attempt to overwrite excel cell Python

2010-10-11 Thread Susana Iraiis Delgado Rodriguez
Hello members:

I'm using xlwt from python to work with excel, I'm developing some sort of
system crawler to look for all the files ending with .shp, I took a look to
csv, but I didn't understand it. Now, I have to create a .xls where people
can save information from shp files, but first I have to create the excel
and add a row for column names:

import os
from xlwt import Workbook
wb = Workbook()
ws = wb.add_sheet('shp')
ws.row(0).write(0,'archivo')
ws.row(0).write(1,'x_min')
ws.row(0).write(2,'y_min')
ws.row(0).write(3,'x_max')
ws.row(0).write(4,'y_max')
ws.row(0).write(5,'geometria')
ws.row(0).write(6,'num_elem')
ws.row(0).write(7,'prj')
ws.row(0).write(8,'estrutura bd')
ws.row(0).write(9,'extent')
ws.row(0).write(10,'fecha_modificacion')
ws.row(0).write(11,'maquina_host')

Then I have to do the crawler part to have the directory I want:
allfiles = [] #store all files found
for root,dir,files in os.walk("C:\\"):
 filelist = [ os.path.join(root,fi) for fi in files if fi.endswith(".shp") ]
 for f in filelist:
  allfiles.append(f)

Now I want to get the name of the file and write it uder the column
"Archivo", the variable i has the name of each file:
for i in allfiles:
 print i
ws.row(1).write(0,i)
wb.save('shp.xls')

But when I run it, it throws me the error:
*Exception*: *Attempt to overwrite cell*: sheetname='shp' rowx=1 colx=0,
don't know what is wrong
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dictionary and more

2010-10-11 Thread Jack Uretsky

Hi-
	I apologize for the size of the attached file, but the question 
would make little sense if I made substantial deletions.

The program gives the following error:
Traceback (most recent call last):
  File "/Javastuff/python/Glau_Is.py", line 131, in 
Adestin[state]()
TypeError: 'NoneType' object is not callable
	This is after the RETA prinout from function A_1, so that seems to 
be called correctly.  The black screen is not part of the problem, I am 
not including the .jpeg files.  Line 131 is the one that reads

Adestin[state]()
and the program prints (correctly) state=1 before the traceback.
Thanks in advance for any insights.
JLU

"Trust me.  I have a lot of experience at this."
General Custer's unremembered message to his men,
just before leading them into the Little Big Horn Valley



 
import pygame
from pygame.locals import *
from sys import exit
import time
import random
from math import *
global gamma
gamma = .25
global RET
RET = [0,0]
global state
global r
def A_1():
state =1
r = 1 - gamma
f = random.randrange(3)
g = f+2  #destination
RET = (g,r)
print "RETA!=", RET
def A_2():
state = 2
global r2
r2 = 1. + gamma
f = random.randrange(3)
if f == 0:
g = 1 #destination
elif f == 1:
g,r2 = 7,1.
elif f == 2:
g,r2 = 6,1
else:
print "alarm 2"
RET = [g,r2]
def A_3():
state =3
global r3
r3 = 1. + gamma
f = random.randrange(3)
if f == 1:
g = 1
elif f == 0:
g,r3 = 7, 1.
elif f == 2:
g, r3 = 5, 1
else:
print "alarm 3"
RET = [g, r3]
def A_4():
state = 4
global r4
r4 = 1. + gamma
f = random.randrange(3)
if f == 2:
g = 1
elif f == 0:
g,r4 = 6,1
elif f == 1:
g,r4 = 5,1
else:
print "alarm 4" 
RET = [g, r4]
def A_5():
state =5
global r5
r5 = 1. + gamma
f = random.randrange(3)
if f == 0:
g = 8
elif f == 1:
g,r5 = 4,1
elif f == 2:
g,r5 = 3,1
else:
print "alarm 5"
RET = [g, r5]
def A_6():
state = 6
global r6
r6 = 1. + gamma
f= random.randrange(3)
if f == 1:
g = 8
elif f == 0:
g,r6 = 4,1
elif f == 2:
g,r6 = 3,1
else:
print "alarm 6"
RET = [g, r6]
def A_7():
state = 7
global r7
r7 = 1. + gamma
f = random.randrange(3)
if f == 2:
g = 8
elif f == 0:
g,r7 = 3,1
elif f == 1:
g,r7 = 2,1
else:
print "alarm 7"
RET = [g, r7]
def A_8():
state = 8
global r8
r8 = 1. - gamma
f = random.randrange(3)
g = f + 5
RET = [g, r8]
#dictionaries
Adestin = {1: A_1(), 2 : A_2(), 3 : A_3(), 4: A_4(),5 : A_5(), 6 : A_6(), 7: 
A_7(), 8 :
 A_8()}
apics = {1: 'a_1.jpg', 2: 'a_2.jpg', 3 : 'a_3.jpg', 4: 'a_4.jpg',
 5: 'a_5.jpg', 6: 'a_6.jpg', 7 : 'a_7.jpg', 8 : 'a_8.jpg'}
state = 1 #set initial state
pygame.init()
screen = pygame.display.set_mode((640,480), 0, 32)
pygame.event.pump()
back1 =apics[state]
back = pygame.image.load(back1).convert()
screen.blit(back, (0,0))
pygame.display.update()
RET=(1,1-gamma)
k=0
while k <= 5:
k = k+1
back1 = apics[state]
print "state=", state
Adestin[state]()   
print RET, k
destin = RET[0]
pois = RET[1]
back = pygame.image.load(back1).convert()
screen.blit(back, (0,0))
pygame.display.update()
state = destin
print "state=",destin
time.sleep(5)
print "end"
   
 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dictionary and more

2010-10-11 Thread Alan Gauld


"Jack Uretsky"  wrote 

Please do not reply to an existing thread when starting a new topic. 
This messes up threaded newsreaders and several archives. 
Start a new topic with a newmessage.


 I apologize for the size of the attached file, but the question 
would make little sense if I made substantial deletions.

 The program gives the following error:
Traceback (most recent call last):
  File "/Javastuff/python/Glau_Is.py", line 131, in 
Adestin[state]()
TypeError: 'NoneType' object is not callable


This says that Adestin[state] is None. 
So lets see how Adestin gets initialised

Its a function call, which returns None. So Python is correct.
You want to store the function names (more accurately the 
function objects) so you do not want the () after the name 
when you initialise the dictionary.


Here is an example:

def f1(): print 'f1'

def f2(): print 'f2'

dct = {'1': f1, '2': f2}  # notice no parens, only a reference

for key in dct:
   dct[key]() # use the parens here to call the func


HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dictionary and more

2010-10-11 Thread Emile van Sebille

On 10/11/2010 9:19 AM Jack Uretsky said...

Hi-
I apologize for the size of the attached file, but the question would
make little sense if I made substantial deletions.
The program gives the following error:
Traceback (most recent call last):
File "/Javastuff/python/Glau_Is.py", line 131, in 
Adestin[state]()
TypeError: 'NoneType' object is not callable
This is after the RETA prinout from function A_1, so that seems to be
called correctly. The black screen is not part of the problem, I am not
including the .jpeg files. Line 131 is the one that reads
Adestin[state]()
and the program prints (correctly) state=1 before the traceback.


Then Adestin[1] is None causing TypeError: 'NoneType' object is not 
callable.  You can verify that by printing Adestin[1] where you're 
currently printing state.


Then you'd discover that when you're building Adestin you're assigning 
the _results_ of the functions to your dictionary.  You probably want to 
leave off the parens when declaring the functions.  Further, your 
functions probably need to return something -- add return statements if 
you want the results.


HTH,

Emile

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] If/else in Python 2.6.5 vs. Python 2.4.3

2010-10-11 Thread Dave Angel


On 2:59 PM, aenea...@priest.com wrote:

Hi,

I have code that works fine when I run it on Python 2.6.5, but I get an "invalid 
syntax" error in Python 2.4.3. I'm hoping you can help me fix it.

The line in question splits a chunk of semi-colon separated words into separate 
elements.

rgenre = re.split(r';', rf.info["genre"] if "genre" in rf.info else []

I get a syntax error at "if" in 2.4.3.

I tried doing the following but it doesn't work (I don't understand why).



if "genre" in rf.info:
   rgenre = re.split(r';', rf.info["genre"])
else:
   []



close.  The else clause should read:
 rgenre = []

And I tried this, too:


if "genre" in rf.info:
   rgenre = re.split(r';', rf.info["genre"])
if "genre" not in rf.info:
   []

Both of these cause problems later on in the program, specifically 
"UnboundLocalError: local variable 'rgenre' referenced before assignment", 
about this line in the code (where each of these is one of the 30 possible genres):

rg1, rg2, rg3, rg4, rg5, rg6, rg7, rg8, rg9, rg10, rg11, rg12, rg13, rg14, rg15, rg16, 
rg17, rg18, rg19, rg20, rg21, rg22, rg23, rg24, rg25, rg26, rg27, rg28, rg29, rg30= 
rgenre + ["NA"]*(30-len(rgenre[:30]))

Thanks for any help--I gave a little extra information, but I'm hoping there's 
a simple rewrite of the first line I gave that'll work in Python 2.4.3.

Thanks,

Tyler


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Attempt to overwrite excel cell Python

2010-10-11 Thread Steven D'Aprano
On Tue, 12 Oct 2010 07:08:15 am Susana Iraiis Delgado Rodriguez wrote:

> But when I run it, it throws me the error:
> *Exception*: *Attempt to overwrite cell*: sheetname='shp' rowx=1
> colx=0, don't know what is wrong

Please don't summarise the error. Copy and paste the exact error 
message, including the full traceback.

I suspect that you might need to read the documentation of the xlwt 
project and see what it says. Perhaps the cell you are trying to 
overwrite is locked?

-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dictionary and more

2010-10-11 Thread Steven D'Aprano
On Tue, 12 Oct 2010 03:19:22 am Jack Uretsky wrote:
> Hi-
>   I apologize for the size of the attached file, but the question
> would make little sense if I made substantial deletions.
>   The program gives the following error:
> Traceback (most recent call last):
>File "/Javastuff/python/Glau_Is.py", line 131, in 
>  Adestin[state]()
> TypeError: 'NoneType' object is not callable

The question makes perfect sense without even looking at the attached 
file. Adestin[state] returns None, which you attempt to call as a 
function. The questions you should be asking yourself are:

- what value am I expecting it to contain?
- where in my code should that value be set?
- why is it setting None instead?

Armed with these three questions, you now know how to debug the problem 
yourself.



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hiding Superclass Methods

2010-10-11 Thread Steven D'Aprano
On Tue, 12 Oct 2010 01:55:10 am Adam Bark wrote:
> On 11/10/10 15:29, Denis Gomes wrote:
> > Thank you both for your responses.  I do have one other question if
> > I use the method both of you describe. How do I go about
> > implementing slicing and indexing for an object in python?  A list
> > object innately has them and that is really why I wanted to use it.
> >  I would appreciate it if you can point me to something.
> > Denis
>
> You can use __getslice__, __setslice__ etc. methods. They're detailed
> in the list docstrings. Here's an example of using __getslice__

__getslice __setslice__ and __delslice__ have been deprecated since 
version 2.0, seven versions ago.

http://docs.python.org/reference/datamodel.html#object.__getslice__

You should use __getitem__ __setitem__ and __delitem__, and detect if 
your argument is an integer or a slice object, and behave accordingly.

http://docs.python.org/reference/datamodel.html#object.__getitem__

-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Multiple regex replacements, lists and for.

2010-10-11 Thread Will Geary
Hello all,

I'm new to python and inexperienced in programming but I'm trying hard.
I have a shell script that I'm converting over to python.
Part of the script replaces some lines of text.
I can do this in python, and get the output I want, but so far only using sed.
Here's an example script:

import subprocess, re
list = ['Apples the color red', 'Skyi am the blue color', 'Grassthe
colour green is here', 'Sky i am the blue color']

def oldway():
sed_replacements = """
s/\(^\w*\).*red/\\1:RED/
s/\(^\w*\).*blue.*/\\1:BLUE/"""
sed = subprocess.Popen(['sed', sed_replacements],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
data = sed.communicate("\n".join(list))[:-1]
for x in data:
print x
oldway();

""" This produces:

>>>Apples:RED
>>>Sky:BLUE
>>>Grassthe colour green is here
>>>Sky:BLUE

Which is what I want"""

print "---"

def withoutsed():
replacements = [
(r'.*red', 'RED'),
(r'.*blue.*', 'BLUE')]
for z in list:
for x,y in replacements:
if re.match(x, z):
print re.sub(x,y,z)
break
else:
print z
withoutsed();

""" Produces:

>>>RED
>>>Sky  i am the blue color
>>>BLUE
>>>Grassthe colour green is here
>>>Grassthe colour green is here
>>>Sky  i am the blue color
>>>BLUE

Duplicate printing + other mess = I went wrong"""

I understand that it's doing what I tell it to, and that my for and if
statements are wrong.
What I want to do is replace matching lines and print them, and also
print the non-matching lines.
Can somebody please point me in the right direction?

Any other python pointers or help much appreciated,

Will.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Networking

2010-10-11 Thread Chris King

 On 10/3/2010 7:20 PM, Chris King wrote:

 On 10/2/2010 3:40 PM, Evert Rol wrote:

Dear Tutors,
 I have attached my 2 programs for networking. It uses socket 
and SocketServer, but it just simplifies it even more. The problem 
is it won't work. The Client raises the error, (with trace back)

Traceback (most recent call last):
   File "G:\My Dropbox\My Dropbox\Chris\Not done\client.py", line 
34, in

 print client.recv()
   File "G:\My Dropbox\My Dropbox\Chris\Not done\client.py", line 
16, in recv

 return self.__sock.recv(1024)
error: [Errno 10053] An established connection was aborted by the 
software in your host machine
The server seems to get an error of some sort, but also seems to 
catch and print it. It prints


Exception happened during processing of request from ('127.0.0.1', 
1424)

Traceback (most recent call last):
   File "C:\Python26\lib\SocketServer.py", line 281, in 
_handle_request_noblock

 self.process_request(request, client_address)
   File "C:\Python26\lib\SocketServer.py", line 307, in process_request
 self.finish_request(request, client_address)
   File "C:\Python26\lib\SocketServer.py", line 320, in finish_request
 self.RequestHandlerClass(request, client_address, self)
TypeError: 'NoneType' object is not callable

I look at both of the documentations of socket and SocketServer, but 
I couldn't firgue it out. I don't know much about networking. Please 
Help
I don't know much about networking, less so about it on Windows; 
also, I've only scanned quickly through the server script, but I 
notice your create_handler() function doesn't return anything. I 
guess it needs to return the Handler class.
The example in the Python docs doesn't use a factory function, but 
instead directly puts the class as the second argument to TCPServer.
So the second argument needs to be a class, but since your 
create_handler() function returns nothing, you presumably get this 
NoneType exception.


   Evert


Yeah, that could be a problem. It should return the class.

Now it won't send more than once. The Error the clients raises is:
Traceback (most recent call last):
  File "G:\My Dropbox\My Dropbox\Chris\Not done\client.py", line 34, in 


print client.recv()
  File "G:\My Dropbox\My Dropbox\Chris\Not done\client.py", line 16, in 
recv

return self.__sock.recv(1024)
error: [Errno 10053] An established connection was aborted by the 
software in your host machine
The server is blissfully unaware of its crashing clients, and keeps on 
going to help more clients to there dooms. The client can receive data 
multiple times, but just can send twice. Please help.
import SocketServer

def echo(self): #the default handling function
print 'Recieved %s from %s. Echoing back.' % (self.data, self.client)
self.client.send(self.data) #echo

class BreakOutError(Exception): pass #an error for breaking out

def create_handler(handle_func=echo): #creates an handler

class Handler(SocketServer.BaseRequestHandler): #the handler
'''A handler which calls %s in the handle method.'''%handle_func
def handle(self): #the handle method
self.data = self.request.recv(1024) #the data
self.client = self.request #the client
handle_func(self) #call the handle method giving self

def shut_down(self): #if you want to stop server
'''End server loop'''
self.server.shut_self_down = True #set shut down to true
raise BreakOutError #raise error

return Handler

class EB_Server(SocketServer.TCPServer):
'''Error Breakout Server
When you use server.shutdown, it waits for the handle to end, but this is the only place to do stuff.
So the error breakout server uses error to break out of a server loop, which will be caught outside.'''

def __init__(self, address, handler):
'''Init, set self.shutdown to False'''
SocketServer.TCPServer.__init__(self, address, handler) #make a handler from a function
self.shut_self_down = False #When an error is raised and handle_error catches it, it will check if its an breakout error

def handle_error(self, request, address):
'''Test to see if shutting down.'''
if self.shut_self_down: raise BreakOutError #if shutdown, raise breakout error
else: SocketServer.TCPServer.handle_error(self, request, address) #If not, do normal error handling

def run(handle_func = echo, host='localhost', port=1024): #init function
try: EB_Server((host, port), create_handler(handle_func)).serve_forever() #serve forever
except BreakOutError: pass #If it tries to break out, catch it before it destroys us at the main level

if __name__ == '__main__': run() #if run directly, run server
import socket

class Client(object): #client object
def __init__(self, host = 'localhost', port = 1024, timeout = None):
  

Re: [Tutor] Hiding Superclass Methods

2010-10-11 Thread Adam Bark

On 11/10/10 23:52, Steven D'Aprano wrote:

On Tue, 12 Oct 2010 01:55:10 am Adam Bark wrote:
   

On 11/10/10 15:29, Denis Gomes wrote:
 

Thank you both for your responses.  I do have one other question if
I use the method both of you describe. How do I go about
implementing slicing and indexing for an object in python?  A list
object innately has them and that is really why I wanted to use it.
  I would appreciate it if you can point me to something.
Denis
   

You can use __getslice__, __setslice__ etc. methods. They're detailed
in the list docstrings. Here's an example of using __getslice__
 

__getslice __setslice__ and __delslice__ have been deprecated since
version 2.0, seven versions ago.

http://docs.python.org/reference/datamodel.html#object.__getslice__

You should use __getitem__ __setitem__ and __delitem__, and detect if
your argument is an integer or a slice object, and behave accordingly.

http://docs.python.org/reference/datamodel.html#object.__getitem__

   

Oh right, 2.6 doesn't say anything about it in the docstrings.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Attempt to overwrite excel cell Python

2010-10-11 Thread Walter Prins
Hi Susana,

On 11 October 2010 21:08, Susana Iraiis Delgado Rodriguez <
susana.delgad...@utzmg.edu.mx> wrote:

>
> *Exception*: *Attempt to overwrite cell*: sheetname='shp' rowx=1 colx=0,
> don't know what is wrong
>
>
This is a default of xlwt behaviour for writing Excel files.  It assumes it
would generally be an unintended mistake to write a cell then overwrite it
later with something else hence it by default raises an exception when this
happens.

Anyway, you can override this behaviour and enable cell overwriting by
adding the parameter "cell_overwrite_ok=True" when you create a worksheet.
However I think you probably are just accidentally (and erroneously)
overwriting the same row accidentally, so the error is probably meaningful
in your case.

Wahtever the case, I've taken the liberty to knock what you posted into
shape a bi -- The following script now works (well it finds files and
doesn't generate the error you reported.)  I've also tidied up the structure
and formatting as you'll see:

http://pastebin.com/Kc9N3DAC

Hope that helps,

Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor