Re: [Tutor] Import package module problem

2009-05-12 Thread spir
Le Mon, 11 May 2009 21:44:09 +0100 (BST),
man...@themacaque.com s'exprima ainsi:

> Hello there,
> 
> I have just started working with python and I have some issues
> understanding how I should be importing modules from packages. Curretly I
> have the following tree structure:
> 
> general/
> __init__.py
> address_book.py
> groups/
> __init__.py
> contact_group.py
> 
> where groups and general are in the same level and all the __init__.py
> files are empty.
> 
> In address_book.py I want to import the ContactGroup which is at
> contact_group.py. I have try the following posibilities:
> 
> from ..groups.contact_group import ContactGroup
> from groups.contact_group import ContactGroups
> from groups.contact_group import *
> 
> But I cannot get it working. I know that the third option will not work
> because I have not set up __all__ but I do not understand why it does not
> work. I have read books and tutorials about it, but I cannot get it.
> 
> Am I doing something wrong? I would really appreciate a hand or pointer to
> s step by step example.

Not sure at all, 'cause python packaging is still rather unclear for me, but I 
guess you should have module (or other names thingies) imported inside 
__init__.py; and that's precisely their main purpose (in addition to possibly 
running startup code). If I'm right, simply writing in groups/__init__.py
   import contact_group
or
   from contact_group import ContactGroups
should do the job. Actually, python does *not* automatically populate 
(sub-)packages' dict of names with the files in the directory (as I would also 
have expected).

[The reason why I still do not understand what python packaging, esp. the use 
of __init__ files, is supposed to bring to the developper and/or the user. I've 
read several docs several times, but they all say the same, even using the same 
examples, and none points to the actual purpose. Having a 'normal' py file 
importing names intended to be exported would do the same job. Anyone?]

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


--
la vita e estrany
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Import package module problem

2009-05-12 Thread A.T.Hofkamp

man...@themacaque.com wrote:

Hello there,

I have just started working with python and I have some issues
understanding how I should be importing modules from packages. Curretly I
have the following tree structure:

general/
__init__.py
address_book.py
groups/
__init__.py
contact_group.py

where groups and general are in the same level and all the __init__.py
files are empty.


You seem to need a common starting point:

%  ls -R
.:
general  groups  main.py

./general:
gen.py  __init__.py

./groups:
grp.py  __init__.py

The same setup as you have, except my names are less nice, and I have a 
./main.py added


The latter file is the starting point:

%  cat main.py
from general import gen

The general/gen file imports the groups/grp file, and then prints some text:

%  cat general/gen.py
from groups import grp
print "inside gen.py"

Finally, the groups/grp.py file outputs only some text:

%  cat groups/grp.py
print "inside grp.py"

When I run this code, I get the following output:

%  python main.py
inside grp.py
inside gen.py


By starting from main.py, the Python interpreter uses the current "." 
directory as starting point for imports. That starting point is then used to 
refer to other files (possibly in another package).



Sincerely,
Albert

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


Re: [Tutor] Import package module problem

2009-05-12 Thread mandel
> Le Mon, 11 May 2009 21:44:09 +0100 (BST),
> man...@themacaque.com s'exprima ainsi:
>
>> Hello there,
>>
>> I have just started working with python and I have some issues
>> understanding how I should be importing modules from packages. Curretly
>> I
>> have the following tree structure:
>>
>> general/
>> __init__.py
>> address_book.py
>> groups/
>> __init__.py
>> contact_group.py
>>
>> where groups and general are in the same level and all the __init__.py
>> files are empty.
>>
>> In address_book.py I want to import the ContactGroup which is at
>> contact_group.py. I have try the following posibilities:
>>
>> from ..groups.contact_group import ContactGroup
>> from groups.contact_group import ContactGroups
>> from groups.contact_group import *
>>
>> But I cannot get it working. I know that the third option will not work
>> because I have not set up __all__ but I do not understand why it does
>> not
>> work. I have read books and tutorials about it, but I cannot get it.
>>
>> Am I doing something wrong? I would really appreciate a hand or pointer
>> to
>> s step by step example.
>
> Not sure at all, 'cause python packaging is still rather unclear for me,
> but I guess you should have module (or other names thingies) imported
> inside __init__.py; and that's precisely their main purpose (in addition
> to possibly running startup code). If I'm right, simply writing in
> groups/__init__.py
>import contact_group
> or
>from contact_group import ContactGroups
> should do the job. Actually, python does *not* automatically populate
> (sub-)packages' dict of names with the files in the directory (as I would
> also have expected).
>

Lets see if I understand what you mean, in my example I should add an
import inside __init__.py to be able to use relative imports:

/general
   __init__.py >> from address_book import AddressBook
   address_book.py
/groups
   __init__.py >> from contact_group import ContactGroup
   contact_group.py

Lets say I have the above, would I be able to use the following?

from ..groups.contact_group import ContactGroup

I'm trying to use this type of import to be able to bundle my unit tests
with my code and let devels work with it. I have read somewhere that
__all__ can do the trick   but it did not say how.

> [The reason why I still do not understand what python packaging, esp. the
> use of __init__ files, is supposed to bring to the developper and/or the
> user. I've read several docs several times, but they all say the same,
> even using the same examples, and none points to the actual purpose.
> Having a 'normal' py file importing names intended to be exported would do
> the same job. Anyone?]
>
> Denis
>
>> Kr,
>>
>> Manuel
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
> --
> la vita e estrany
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



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


Re: [Tutor] Import package module problem

2009-05-12 Thread mandel
> man...@themacaque.com wrote:
>> Hello there,
>>
>> I have just started working with python and I have some issues
>> understanding how I should be importing modules from packages. Curretly
>> I
>> have the following tree structure:
>>
>> general/
>> __init__.py
>> address_book.py
>> groups/
>> __init__.py
>> contact_group.py
>>
>> where groups and general are in the same level and all the __init__.py
>> files are empty.
>
> You seem to need a common starting point:
>
> %  ls -R
> .:
> general  groups  main.py
>
> ./general:
> gen.py  __init__.py
>
> ./groups:
> grp.py  __init__.py
>
> The same setup as you have, except my names are less nice, and I have a
> ./main.py added
>
> The latter file is the starting point:
>
> %  cat main.py
> from general import gen
>
> The general/gen file imports the groups/grp file, and then prints some
> text:
>
> %  cat general/gen.py
> from groups import grp
> print "inside gen.py"
>
> Finally, the groups/grp.py file outputs only some text:
>
> %  cat groups/grp.py
> print "inside grp.py"
>
> When I run this code, I get the following output:
>
> %  python main.py
> inside grp.py
> inside gen.py
>
>
> By starting from main.py, the Python interpreter uses the current "."
> directory as starting point for imports. That starting point is then used
> to
> refer to other files (possibly in another package).
>
>
> Sincerely,
> Albert
>
>

I have actually rearranged my code to have such hierarchy which obviously
works. The problem is that I want ot be able to perform unit tests withinn
 the package of the code. I keep having the problem with

from ..groups.contact_group import ContactGroup

I have read that the notation is correct, but how do you get it too work?
I can alway move all the tests one level up, but I really would prefer not
to have to do it.

Kr,

Manuel

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


Re: [Tutor] Alternative for Shelve

2009-05-12 Thread Timo

Alan Gauld schreef:

"Timo"  wrote

I have an issue with the Shelve module. It works great for my needs, 
the only problem is that a file made with Shelve isn't interchangable 
between different computers.


I thought it would be.
What kind of computers are you having issues with?
And what kind of issues?

Currently only tested between Ubuntu and Windows on the same computer.
This is the end of the traceback:
bsddb.db.DBInvalidArgError: (22, 'Invalid argument -- 
: unsupported hash version: 9')





Does someone have an alternative to Shelve?
It must be able to contain keys and values, and the values are a list 
of dictionaries.


A SqlLite database?
With record  where the fields correspond to your dictionary entries.

ID:Date:Location

1234567 = [{'date' : '2009-05-11', 'location' : 'Germany'}, {'date' : 
'2009-05-04', 'location' : 'France'}]
7654321 = [{'date' : '2009-03-12', 'location' : 'Belgium'}, {'date' : 
'2009-04-23', 'location' : 'Spain'}]


populating your dictionary becomes a matter of extracting the data:

SELECT DATE, LOCATION FROM DATA WHERE ID = key

SQLite has the advantage that the atabase is a single file and
it is portable across platforms provided they have Sqlite installed.
And its part of the Python standard library.


Examples of using Sqlite in the databases topic of my tutorial.

Thank you. I will check the tutorial.

Timo



HTH,




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


Re: [Tutor] How to set up an Array?

2009-05-12 Thread spir
Le Mon, 11 May 2009 19:09:30 -0700 (PDT),
nickel flipper  s'exprima ainsi:

> 
> Hello,
> Just getting started with Python, and have had some early, although trivial
> success. It looks like just the ticket to parse a data file.  Total noob at
> this, but really kind of overwhelmed by all the options.  Looking for some
> direction on which modules, librarys, or ? to accomplish the goal.
> 
> To date have been using conditional type statement to tease out
> information.  Now I need to match some strings, put them in an array or
> list? and read them back after X number of lines.  The linesplits are in a
> predictable pattern and padded by '-' to get eight values or arrays that
> will be joined together after a set condition is no longer true.
> 
> So from the data set below, will be looking to print out:
> RA7,OSC1,CLKI
> RA6,OSC2
> RA5,AN4,nSS1,LVDIN,RCV,RP2
> ETC.
> 
> Any tips greatly appreciated.  Thanks.
> 
> 
> sfr (key=PORTA addr=0xf80 size=1 access='rw rw rw u rw rw rw rw')
> reset (por='' mclr='')
> bit (names='RA7 RA6 RA5 - RA3 RA2 RA1 RA0' width='1 1 1 1 1 1 1 1')
> bit (tag=scl names='RA' width='8')
> bit (names='OSC1 OSC2 AN4 - AN3 AN2 AN1 AN0' width='1 1 1 1 1 1 1 1')
> bit (names='CLKI CLKO nSS1 - VREF_PLUS VREF_MINUS C2INA C1INA' width='1
> 1 1 1 1 1 1 1') bit (names='- - LVDIN - C1INB CVREF_MINUS PMPA7 PMPA6'
> width='1 1 1 1 1 1 1 1') bit (names='- - RCV - - C2INB RP1 RP0' width='1 1
> 1 1 1 1 1 1') bit (names='- - RP2 - - - - -' width='1 1 1 1 1 1 1 1')
> 
> Here is some noob code used to pick out the RA7, RA6, RA5 etc.  Comments
> welcome.
> 
> if line.startswith ( "bit (names='R" ):
> (a, pin7, pin6, pin5, pin4, pin3, pin2, pin1, pin0) = (line.split()
> + ["", ""])[:9] startpin = pin7[8:3]
> if startpin.startswith == "RA" or "RB" or "RC" or "RD" or "RE" or
> "RF" or "RG" or "RH" or "RJ": print pin7[8:] + "," + pin6 + "," + pin5 +
> "," + pin4 + "," + pin3 + "," + pin2 + "," + pin1 + "," + pin0[:3] + "\n"
> else: pass

Hem, rather complicated. I would use a regex for once in this precise case. But 
forget it if you're not used to regexes, rather take the opportunity to learn 
python builtin strings methods better.

Anyway, as a step on the regex path, the following code

s = """\
sfr (key=PORTA addr=0xf80 size=1 access='rw rw rw u rw rw rw rw')
reset (por='' mclr='')
bit (names='RA7 RA6 RA5 - RA3 RA2 RA1 RA0' width='1 1 1 1 1 1 1 1')
bit (tag=scl names='RA' width='8')
bit (names='OSC1 OSC2 AN4 - AN3 AN2 AN1 AN0' width='1 1 1 1 1 1 1 1')
bit (names='CLKI CLKO nSS1 - VREF_PLUS VREF_MINUS C2INA C1INA' width='1 1 1 
1 1 1 1 1')
bit (names='- - LVDIN - C1INB CVREF_MINUS PMPA7 PMPA6' width='1 1 1 1 1 1 1 
1')
bit (names='- - RCV - - C2INB RP1 RP0' width='1 1 1 1 1 1 1 1')
bit (names='- - RP2 - - - - -' width='1 1 1 1 1 1 1 1')"""
from re import compile as Pattern
p = Pattern(r"names='((?:(?:\w+|-) ?){8})'")
r = p.findall(s)
print r

outputs

['RA7 RA6 RA5 - RA3 RA2 RA1 RA0', 'OSC1 OSC2 AN4 - AN3 AN2 AN1 AN0', 'CLKI CLKO 
nSS1 - VREF_PLUS VREF_MINUS C2INA C1INA', '- - LVDIN - C1INB CVREF_MINUS PMPA7 
PMPA6', '- - RCV - - C2INB RP1 RP0', '- - RP2 - - - - -']

As you see the pattern is hardly legible. It matches a sequence of 8 'things' 
inside "names='...'. Each 'thing' is either an alphanumeric string or '-', 
possibly followed by a space. (Actually it's not fully correct.) We have to use 
twice so-called non-grouping parentheses "(?:...)". What is actually captured 
is inside simple (...).

Denis
--
la vita e estrany
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Alternative for Shelve

2009-05-12 Thread Timo

Kent Johnson schreef:

On Mon, May 11, 2009 at 1:39 PM, Timo  wrote:
  

Hello all,

I have an issue with the Shelve module. It works great for my needs, the
only problem is that a file made with Shelve isn't interchangable between
different computers. I want my data to be exchanged between users.

Does someone have an alternative to Shelve?
It must be able to contain keys and values, and the values are a list of
dictionaries.



Try the pickle module.

Kent
  
I went from Pickle to Shelve because I couldn't store my wanted list of 
dictionaries in Pickle.


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


[Tutor] Calling method in parent class

2009-05-12 Thread The Green Tea Leaf
Hi,
I've started to learn Python and I'm a bit confused over how to call a
method in a parent class. Assume I have:

class Parent(object):
def somemethod( self, bla ):
print 'Parent',bla

I then create a child class that want to call somemethod. As I
understand it I can either do it like this

class Child(Parent):
def somemethod( self, bla ):
Parent.somemethod(self,bla)

or like this

class Child(Parent):
def somemethod( self, bla ):
super(Child,self).somemethod(bla)

The first version seem to have the obvious disadvantage that I need to
know the name of the parent class when I write the call, so I thought
that the second version was the "proper" way of doing it. But when
doing some research on the web it seem like the second version also
have some problems.

My question is simple: what is the "best" way of doing this and why?
Or should I mix both these approaches?

--
The Green Tea Leaf   thegreenteal...@gmail.com   thegreentealeaf.blogspot.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to set up an Array?

2009-05-12 Thread nickel
John Fouhy  fouhy.net> writes:

> Hmm, hairy!
> 

Thank you John for your quick reply.  It looks like its going to take a bit to
digest what you have written.  Back to the Python 2.6 docs and the net.  Had
actually read the expressions section earlier in the day, but did not see how to
apply to said problem.  Will post progress ASAP.

P.S. will take a gander at the parsers too.



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


[Tutor] Considering translating bash script to Python to learn

2009-05-12 Thread Dotan Cohen
I am considering translating a homegrown bash script to Python to
learn the language. The script grabs different specific pages of
either a ODF or PDF file (I can use either as the input file, based on
Python's abilities), combines it with an HTML file, rotates,
rearranges, then sends the whole thing to the printer. However, I seem
to depend on many bash-specific functions (os programs) and I cannot
find Python equivalents. Here are some lines of the script, and the
relevant questions:

gnome-web-print --mode=print --files $FILE /tmp/weeklyCalendar.pdf
Here, I am converting an HTML file to PDF. I rely on the external
program gnome-web-print to do the conversion. Does Python have a
native way to handle this, or would I just wind up calling
gnome-web-print from within python?

pdftops -f 2 -l 2 $HOME/.bin/todo/todo.odf.pdf /tmp/weeklyTodo.ps
Here I am exporting the second page of a PDF file as a PS file.
Actually, the file in question is a hybrid ODF-PDF file and if Python
has a way of exporting a specific page of a ODF file that is fine too.
I could export to PDF as well, the important bit is too isolate a
single page of either an ODF or PDF file and have it as either a PS or
PDF.

gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite
-sOutputFile=/tmp/weeklyCalendarPrintMe.pdf
$HOME/.bin/todo/weeklyCalendar-blank.pdf /tmp/weeklyCalendar.pdf
/tmp/weeklyTodo.ps $HOME/.bin/todo/weeklyCalendar-blank.pdf
Here, I am combining several PDF and PS files as a single PDf file.
Can Python do this?

lpr -P printer -o number-up=2 /tmp/weeklyCalendarPrintMe.pdf
Here I am sending the final file to the printer, and having it print 2
pages on each page. Again, is this something that Python can handle
internally?

Thanks for the help. I know that Python is not specifically designed
to manipulate PDF files, but as the script is getting more complex and
performs logic in other sections (not shown here) I would like to take
advantage of other Python properties.

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Import package module problem

2009-05-12 Thread mandel
> Le Tue, 12 May 2009 08:37:27 +0100 (BST),
> man...@themacaque.com s'exprima ainsi:
>
>> Lets see if I understand what you mean, in my example I should add an
>> import inside __init__.py to be able to use relative imports:
>>
>> /general
>>__init__.py >> from address_book import AddressBook
>>address_book.py
>> /groups
>>__init__.py >> from contact_group import ContactGroup
>>contact_group.py
>>
>> Lets say I have the above, would I be able to use the following?
>>
>> from ..groups.contact_group import ContactGroup
>>
>> I'm trying to use this type of import to be able to bundle my unit tests
>> with my code and let devels work with it. I have read somewhere that
>> __all__ can do the trick   but it did not say how.
>
> Have you tried it?
>
> Denis
> --
> la vita e estrany
>

Yes I have tried and I keep getting the following ValueError:

ValueError: Attempted relative import in non-package

I have tried with my code, do you have an example or yours that works that
way? I might have not done it worng (I hope I haven't)

Kr,

Manuel


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


Re: [Tutor] Calling method in parent class

2009-05-12 Thread Jeremiah Dodds
On Tue, May 12, 2009 at 9:05 AM, The Green Tea Leaf <
thegreenteal...@gmail.com> wrote:

> Hi,
> I've started to learn Python and I'm a bit confused over how to call a
> method in a parent class. Assume I have:
>
> class Parent(object):
>def somemethod( self, bla ):
>print 'Parent',bla
>
> I then create a child class that want to call somemethod. As I
> understand it I can either do it like this
>
> class Child(Parent):
>def somemethod( self, bla ):
>Parent.somemethod(self,bla)
>
> or like this
>
> class Child(Parent):
>def somemethod( self, bla ):
>super(Child,self).somemethod(bla)
>
> The first version seem to have the obvious disadvantage that I need to
> know the name of the parent class when I write the call, so I thought
> that the second version was the "proper" way of doing it. But when
> doing some research on the web it seem like the second version also
> have some problems.
>
> My question is simple: what is the "best" way of doing this and why?
> Or should I mix both these approaches?
>
> --
>

Assuming you don't have the same method in Child, just use self.somemethod:


In [2]: class Parent(object):
   ...: def foo(self):
   ...: print "in parent foo"
   ...:

In [3]: class Child(Parent):
   ...: pass
   ...:

In [4]: x = Child()

In [5]: x.foo
Out[5]: >

In [6]: x.foo()
in parent foo

In [7]: class Child(Parent):
   ...: def bar(self):
   ...: self.foo()
   ...: print "in child bar"
   ...:

In [8]: x = Child()

In [9]: x.bar()
in parent foo
in child bar
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Calling method in parent class

2009-05-12 Thread The Green Tea Leaf
OK, bad example. But assume I have the same method in both classes and
want to call the method in the parent.

On Tue, May 12, 2009 at 10:26, Jeremiah Dodds  wrote:
>
>
> On Tue, May 12, 2009 at 9:05 AM, The Green Tea Leaf
>  wrote:
>>
>> Hi,
>> I've started to learn Python and I'm a bit confused over how to call a
>> method in a parent class. Assume I have:
>>
>> class Parent(object):
>>    def somemethod( self, bla ):
>>        print 'Parent',bla
>>
>> I then create a child class that want to call somemethod. As I
>> understand it I can either do it like this
>>
>> class Child(Parent):
>>    def somemethod( self, bla ):
>>        Parent.somemethod(self,bla)
>>
>> or like this
>>
>> class Child(Parent):
>>    def somemethod( self, bla ):
>>        super(Child,self).somemethod(bla)
>>
>> The first version seem to have the obvious disadvantage that I need to
>> know the name of the parent class when I write the call, so I thought
>> that the second version was the "proper" way of doing it. But when
>> doing some research on the web it seem like the second version also
>> have some problems.
>>
>> My question is simple: what is the "best" way of doing this and why?
>> Or should I mix both these approaches?
>>
>> --
>
> Assuming you don't have the same method in Child, just use self.somemethod:
>
>
> In [2]: class Parent(object):
>    ...: def foo(self):
>    ...: print "in parent foo"
>    ...:
>
> In [3]: class Child(Parent):
>    ...: pass
>    ...:
>
> In [4]: x = Child()
>
> In [5]: x.foo
> Out[5]: >
>
> In [6]: x.foo()
> in parent foo
>
> In [7]: class Child(Parent):
>    ...: def bar(self):
>    ...: self.foo()
>    ...: print "in child bar"
>    ...:
>
> In [8]: x = Child()
>
> In [9]: x.bar()
> in parent foo
> in child bar
>
>
>
> ___
> Tutor maillist  -  tu...@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 
The Green Tea Leaf   thegreenteal...@gmail.com   thegreentealeaf.blogspot.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Calling method in parent class

2009-05-12 Thread Jeremiah Dodds
On Tue, May 12, 2009 at 9:55 AM, The Green Tea Leaf <
thegreenteal...@gmail.com> wrote:

> OK, bad example. But assume I have the same method in both classes and
> want to call the method in the parent.
>
>
Can you give a concrete example of _why_ you would want to do this? You can
use super, if you really want to, but it can get ugly (I do not fully
understand all of supers caveats). I can't think of a case off the top of my
head where you would want to call a parent class's method that a child
instance has overriden, but I'm sure it happens sometimes.

My guess is that you probably want to re-organize your classes, or not use
inheritance in this instance, or rename the method in the child class. It's
hard to tell without knowing what exactly you're trying to do in your code.
(I mean on the end-result level, not on the "I'm trying to call a parent
classes method" level.

Sorry if this doesn't seem helpful, and I could be wrong here myself, but I
don't think that this is something that should happen very often at all, and
is probably a pretty rank code smell.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Considering translating bash script to Python to learn

2009-05-12 Thread spir
Le Tue, 12 May 2009 11:26:00 +0300,
Dotan Cohen  s'exprima ainsi:

> I am considering translating a homegrown bash script to Python to
> learn the language. The script grabs different specific pages of
> either a ODF or PDF file (I can use either as the input file, based on
> Python's abilities), combines it with an HTML file, rotates,
> rearranges, then sends the whole thing to the printer. However, I seem
> to depend on many bash-specific functions (os programs) and I cannot
> find Python equivalents. Here are some lines of the script, and the
> relevant questions:
> 
[...]
I think you should first keep these very pdf-specific tasks the way they are. 
Use the subprocess module to launch os commands. So that you can concentrate on 
translating the overall logic into python, which should not be too hard, 
probably.
> 
> Thanks for the help. I know that Python is not specifically designed
> to manipulate PDF files, but as the script is getting more complex and
> performs logic in other sections (not shown here) I would like to take
> advantage of other Python properties.
> 
Yes, I think it's a sensible thing to do. Python will provide a clearer process 
logic on a higher-level, and numerous side-advantages such as builtin or 
library toolsets.

Denis
--
la vita e estrany
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Calling method in parent class

2009-05-12 Thread The Green Tea Leaf
I just want to know what is the best way to do this.

As for an example, I would say the __init__ method where the parent
class do some initialization, to be sure that everything is set up
correctly I would call the parents class __init__ method before doing
something else.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Calling method in parent class

2009-05-12 Thread spir
Le Tue, 12 May 2009 10:55:18 +0200,
The Green Tea Leaf  s'exprima ainsi:

> OK, bad example. But assume I have the same method in both classes and
> want to call the method in the parent.

That should not happen! Basic contract is: same name = same meaning.

Either you implement a method in a parent class to let all instances of child 
classes use it; with possible overriding in specific child classes. Or you have 
two different methods with different names that implement different semantics.

Having two methods with the name that both need two be used on the same object 
is clearly a design flaw. What do you think?

The only case is when the parent method performs a part of what child class 
methods have to do. E.g a common case for __init__:

class Parent(object):
def __init__(self,arg0):
self.arg0 = arg0

class OneChild(Parent):
def __init__(self,arg0,arg1):
Parent.__init__(self,arg0)
self.arg1 = arg1

one = OneChild(0,1)
print one.arg0,one.arg1

==>
0 1

Denis
--
la vita e estrany
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Calling method in parent class

2009-05-12 Thread The Green Tea Leaf
> That should not happen! Basic contract is: same name = same meaning.

Same meaning yes, but that doesn't mean that I can't/shouldn't reuse
code that address a part of the problem.

> Having two methods with the name that both need two be used on the same 
> object is clearly a design flaw. What do you think?

It think that it depends, as you write yourself if I have a method
that does something that needs/should be done I think it's perfectly
OK to do it (in fact that it should be done).

> The only case is when the parent method performs a part of what child class 
> methods have to do. E.g a common case for __init__:

Exacly, this is the prime example (and I can't come up with another
right now without inventing some convoluted example that would be
really silly)

> class OneChild(Parent):
>        def __init__(self,arg0,arg1):
>                Parent.__init__(self,arg0)
>                self.arg1 = arg1

So this is the preferred way? Not super(OneChild, self).__init__ ?

-- 
The Green Tea Leaf   thegreenteal...@gmail.com   thegreentealeaf.blogspot.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Calling method in parent class

2009-05-12 Thread Jeremiah Dodds
On Tue, May 12, 2009 at 11:02 AM, The Green Tea Leaf <
thegreenteal...@gmail.com> wrote:

> > That should not happen! Basic contract is: same name = same meaning.
>
> Same meaning yes, but that doesn't mean that I can't/shouldn't reuse
> code that address a part of the problem.
>
>
>
If your superclass has a method with the same name (other than __init__
here), that contains some logic that a subclass that overrides the method
needs, it's written wrong in python. In this case, use different method
names, or factor out the parent class methods functionality into (probably)
a decorator. Code reuse should be strived for, but that's not the only
purpose of inheritance. If you need to override a method in a subclass, and
still need to call the parents method in that subclass, you're almost
definately using inheritance wrong, with the special exception of __init__.

In the case of __init__, you probably want to use Parent.__init__, and not
super, if only because of all the weird edge cases with super.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Retrieving Data from Pmw.EntryFeild

2009-05-12 Thread Sampath Girish
Hi friendThis is Sam, a python learner. I have got some
problem in retrieving data from a grid of Pmw.EntryFields. Now i have
developed a grid of size 3X3 using two for loops. One for row and other for
column. Now i Have 9 entry fields in the form of a matrix. I need to get all
the entered data in the form of list one by one as soon as i press 'Submit'
button. Please help me in this.

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


Re: [Tutor] Calling method in parent class

2009-05-12 Thread The Green Tea Leaf
> If your superclass has a method with the same name (other than __init__
> here), that contains some logic that a subclass that overrides the method
> needs, it's written wrong in python. In this case, use different method
> names, or factor out the parent class methods functionality into (probably)
> a decorator. Code reuse should be strived for, but that's not the only
> purpose of inheritance. If you need to override a method in a subclass, and
> still need to call the parents method in that subclass, you're almost
> definately using inheritance wrong, with the special exception of __init__.

I think we agree on this, I can imagine that there are cases where
it's desirable to have this ... but I can't come up with a good
counter example so I assume this mean that we agree :)

> In the case of __init__, you probably want to use Parent.__init__, and not
> super, if only because of all the weird edge cases with super.

Yes, it was those edge cases that I was worried about.


-- 
The Green Tea Leaf   thegreenteal...@gmail.com   thegreentealeaf.blogspot.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Alternative for Shelve

2009-05-12 Thread Kent Johnson
On Tue, May 12, 2009 at 3:59 AM, Timo  wrote:
> Alan Gauld schreef:
>>
>> "Timo"  wrote
>>
>>> I have an issue with the Shelve module. It works great for my needs, the
>>> only problem is that a file made with Shelve isn't interchangable between
>>> different computers.
>>
>> I thought it would be.
>> What kind of computers are you having issues with?
>> And what kind of issues?
>
> Currently only tested between Ubuntu and Windows on the same computer.
> This is the end of the traceback:
> bsddb.db.DBInvalidArgError: (22, 'Invalid argument -- :
> unsupported hash version: 9')

shelve relies on the anydbm module for storage. anydbm may use any one
of several actual database implementations (dbhash, gdbm, dbm or
dumbdbm) depending on what is available. I guess you have different
modules available on the two machines. You can find out which module
is being used like this:

In [7]: import anydbm
In [8]: anydbm._defaultmod
Out[8]: 

You could force the use of a common db module by opening the file
explicitly. For example, to use dumbdbm, which is slow, simple and
guaranteed to be available, something like this (untested) should
work:

import dumbdbm
from shelve import Shelf

shelf = Shelf(dumbdbm.open('myfile', 'c'))

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


Re: [Tutor] Alternative for Shelve

2009-05-12 Thread Kent Johnson
On Tue, May 12, 2009 at 4:00 AM, Timo  wrote:
> Kent Johnson schreef:
>> Try the pickle module.
>
> I went from Pickle to Shelve because I couldn't store my wanted list of
> dictionaries in Pickle.

What was the problem? You should be able to create a dict whose values
are lists of dicts. This would correspond to the dict-like object you
get from shelve. Then the whole dict could be pickled. For example:

In [10]: import pickle

In [11]: d=dict()

In [12]: d[1234567] = [{'date' : '2009-05-11', 'location' :
'Germany'}, {'date' : '2009-05-04', 'location' : 'France'}]

In [13]: d[7654321] = [{'date' : '2009-03-12', 'location' :
'Belgium'}, {'date' : '2009-04-23', 'location' : 'Spain'}]

In [14]: s = pickle.dumps(d)

In [15]: s
Out[15]: 
"(dp0\nI7654321\n(lp1\n(dp2\nS'date'\np3\nS'2009-03-12'\np4\nsS'location'\np5\nS'Belgium'\np6\nsa(dp7\ng3\nS'2009-04-23'\np8\nsg5\nS'Spain'\np9\nsasI1234567\n(lp10\n(dp11\ng3\nS'2009-05-11'\np12\nsg5\nS'Germany'\np13\nsa(dp14\ng3\nS'2009-05-04'\np15\nsg5\nS'France'\np16\nsas."

In [16]: d2 = pickle.loads(s)

In [17]: d2
Out[17]:
{1234567: [{'date': '2009-05-11', 'location': 'Germany'},
   {'date': '2009-05-04', 'location': 'France'}],
 7654321: [{'date': '2009-03-12', 'location': 'Belgium'},
   {'date': '2009-04-23', 'location': 'Spain'}]}

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


Re: [Tutor] Calling method in parent class

2009-05-12 Thread Kent Johnson
On Tue, May 12, 2009 at 6:32 AM, Jeremiah Dodds
 wrote:

> If your superclass has a method with the same name (other than __init__
> here), that contains some logic that a subclass that overrides the method
> needs, it's written wrong in python. In this case, use different method
> names, or factor out the parent class methods functionality into (probably)
> a decorator. Code reuse should be strived for, but that's not the only
> purpose of inheritance. If you need to override a method in a subclass, and
> still need to call the parents method in that subclass, you're almost
> definately using inheritance wrong, with the special exception of __init__.

I don't agree with this at all. It's not at all unusual for a derived
class to override a base class method in order to add additional
functionality to it, then to call the base class method to complete
the implementation. __init__() is the most common example but not the
only one. I don't consider this a design flaw at all. Another way to
do this is for the base class method to call a hook method that
subclasses can define but IMO that is often more trouble than it is
worth.

I don't see how you would use a decorator to do this.

> In the case of __init__, you probably want to use Parent.__init__, and not
> super, if only because of all the weird edge cases with super.

super() is intended to solve problems that arise when using multiple
inheritance. It has to be used carefully and consistently. Personally
I use the Parent.method(self) style.

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


Re: [Tutor] Retrieving Data from Pmw.EntryFeild

2009-05-12 Thread Kent Johnson
On Tue, May 12, 2009 at 3:28 AM, Sampath Girish
 wrote:
> Hi friend
>                 This is Sam, a python learner. I have got some problem in
> retrieving data from a grid of Pmw.EntryFields. Now i have developed a grid
> of size 3X3 using two for loops. One for row and other for column. Now i
> Have 9 entry fields in the form of a matrix. I need to get all the entered
> data in the form of list one by one as soon as i press 'Submit' button.
> Please help me in this.

You can use two for loops again. I can't be specific without seeing
your code but something like this:

result = []
for i in range(3):
  for j in range(3):
value = 
result.append(value)

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


Re: [Tutor] How to set up an Array?

2009-05-12 Thread Kent Johnson
On Tue, May 12, 2009 at 3:59 AM, spir  wrote:
> Le Mon, 11 May 2009 19:09:30 -0700 (PDT),
> nickel flipper  s'exprima ainsi:

>> So from the data set below, will be looking to print out:
>> RA7,OSC1,CLKI
>> RA6,OSC2
>> RA5,AN4,nSS1,LVDIN,RCV,RP2
>> ETC.
>>
>> Any tips greatly appreciated.  Thanks.
>>
>>
>> sfr (key=PORTA addr=0xf80 size=1 access='rw rw rw u rw rw rw rw')
>>     reset (por='' mclr='')
>>     bit (names='RA7 RA6 RA5 - RA3 RA2 RA1 RA0' width='1 1 1 1 1 1 1 1')
>>     bit (tag=scl names='RA' width='8')
>>     bit (names='OSC1 OSC2 AN4 - AN3 AN2 AN1 AN0' width='1 1 1 1 1 1 1 1')
>>     bit (names='CLKI CLKO nSS1 - VREF_PLUS VREF_MINUS C2INA C1INA' width='1
>> 1 1 1 1 1 1 1') bit (names='- - LVDIN - C1INB CVREF_MINUS PMPA7 PMPA6'
>> width='1 1 1 1 1 1 1 1') bit (names='- - RCV - - C2INB RP1 RP0' width='1 1
>> 1 1 1 1 1 1') bit (names='- - RP2 - - - - -' width='1 1 1 1 1 1 1 1')


> Hem, rather complicated. I would use a regex for once in this precise case. 
> But forget it if you're not used to regexes, rather take the opportunity to 
> learn python builtin strings methods better.

> from re import compile as Pattern
> p = Pattern(r"names='((?:(?:\w+|-) ?){8})'")

That is quite a bit more complicated than needed. You want to match a
string that starts with "bit (names='" and ends with the next '. You
can do that like this:

In [18]: s = """\
   : sfr (key=PORTA addr=0xf80 size=1 access='rw rw rw u rw rw rw rw')
   :reset (por='' mclr='')
   :bit (names='RA7 RA6 RA5 - RA3 RA2 RA1 RA0' width='1 1 1 1 1 1 1 1')
   :bit (tag=scl names='RA' width='8')
   :bit (names='OSC1 OSC2 AN4 - AN3 AN2 AN1 AN0' width='1 1 1
1 1 1 1 1')
   :bit (names='CLKI CLKO nSS1 - VREF_PLUS VREF_MINUS C2INA
C1INA' width='1 1 1 1 1 1 1 1')
   :bit (names='- - LVDIN - C1INB CVREF_MINUS PMPA7 PMPA6'
width='1 1 1 1 1 1 1 1')
   :bit (names='- - RCV - - C2INB RP1 RP0' width='1 1 1 1 1 1 1 1')
   :bit (names='- - RP2 - - - - -' width='1 1 1 1 1 1 1 1')"""

In [19]: import re

In [23]: p = re.compile(r"bit \(names='([^']+)'")

In [24]: r = p.findall(s)

In [25]: r
Out[25]:
['RA7 RA6 RA5 - RA3 RA2 RA1 RA0',
 'OSC1 OSC2 AN4 - AN3 AN2 AN1 AN0',
 'CLKI CLKO nSS1 - VREF_PLUS VREF_MINUS C2INA C1INA',
 '- - LVDIN - C1INB CVREF_MINUS PMPA7 PMPA6',
 '- - RCV - - C2INB RP1 RP0',
 '- - RP2 - - - - -']

Now split the matches into individual words:
In [26]: r = [ i.split() for i in r ]

In [27]: r
Out[27]:
[['RA7', 'RA6', 'RA5', '-', 'RA3', 'RA2', 'RA1', 'RA0'],
 ['OSC1', 'OSC2', 'AN4', '-', 'AN3', 'AN2', 'AN1', 'AN0'],
 ['CLKI', 'CLKO', 'nSS1', '-', 'VREF_PLUS', 'VREF_MINUS', 'C2INA', 'C1INA'],
 ['-', '-', 'LVDIN', '-', 'C1INB', 'CVREF_MINUS', 'PMPA7', 'PMPA6'],
 ['-', '-', 'RCV', '-', '-', 'C2INB', 'RP1', 'RP0'],
 ['-', '-', 'RP2', '-', '-', '-', '-', '-']]

Transpose the list of lists:
In [28]: r = zip(*r)

In [29]: r
Out[29]:
[('RA7', 'OSC1', 'CLKI', '-', '-', '-'),
 ('RA6', 'OSC2', 'CLKO', '-', '-', '-'),
 ('RA5', 'AN4', 'nSS1', 'LVDIN', 'RCV', 'RP2'),
 ('-', '-', '-', '-', '-', '-'),
 ('RA3', 'AN3', 'VREF_PLUS', 'C1INB', '-', '-'),
 ('RA2', 'AN2', 'VREF_MINUS', 'CVREF_MINUS', 'C2INB', '-'),
 ('RA1', 'AN1', 'C2INA', 'PMPA7', 'RP1', '-'),
 ('RA0', 'AN0', 'C1INA', 'PMPA6', 'RP0', '-')]

Filter out the '-' entries
In [30]: r = [ [ t for t in i if t!='-' ] for i in r ]

In [31]: r
Out[31]:
[['RA7', 'OSC1', 'CLKI'],
 ['RA6', 'OSC2', 'CLKO'],
 ['RA5', 'AN4', 'nSS1', 'LVDIN', 'RCV', 'RP2'],
 [],
 ['RA3', 'AN3', 'VREF_PLUS', 'C1INB'],
 ['RA2', 'AN2', 'VREF_MINUS', 'CVREF_MINUS', 'C2INB'],
 ['RA1', 'AN1', 'C2INA', 'PMPA7', 'RP1'],
 ['RA0', 'AN0', 'C1INA', 'PMPA6', 'RP0']]

And print:
In [32]: for i in r:
   : print ','.join(i)

RA7,OSC1,CLKI
RA6,OSC2,CLKO
RA5,AN4,nSS1,LVDIN,RCV,RP2

RA3,AN3,VREF_PLUS,C1INB
RA2,AN2,VREF_MINUS,CVREF_MINUS,C2INB
RA1,AN1,C2INA,PMPA7,RP1
RA0,AN0,C1INA,PMPA6,RP0

Other than the blank line, this is what was wanted. You can even make
it a one-liner if you want to make it really obscure ;-)

In [39]: rr = [ ','.join(t for t in i if t!='-') for i in zip(*(
i.split() for i in p.findall(s) )) ]

In [40]: rr
Out[40]:
['RA7,OSC1,CLKI',
 'RA6,OSC2,CLKO',
 'RA5,AN4,nSS1,LVDIN,RCV,RP2',
 '',
 'RA3,AN3,VREF_PLUS,C1INB',
 'RA2,AN2,VREF_MINUS,CVREF_MINUS,C2INB',
 'RA1,AN1,C2INA,PMPA7,RP1',
 'RA0,AN0,C1INA,PMPA6,RP0']

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


Re: [Tutor] Calling method in parent class

2009-05-12 Thread Jeremiah Dodds
On Tue, May 12, 2009 at 12:27 PM, Kent Johnson  wrote:

> On Tue, May 12, 2009 at 6:32 AM, Jeremiah Dodds
>  wrote:
>
> > If your superclass has a method with the same name (other than __init__
> > here), that contains some logic that a subclass that overrides the method
> > needs, it's written wrong in python. In this case, use different method
> > names, or factor out the parent class methods functionality into
> (probably)
> > a decorator. Code reuse should be strived for, but that's not the only
> > purpose of inheritance. If you need to override a method in a subclass,
> and
> > still need to call the parents method in that subclass, you're almost
> > definately using inheritance wrong, with the special exception of
> __init__.
>
> I don't agree with this at all. It's not at all unusual for a derived
> class to override a base class method in order to add additional
> functionality to it, then to call the base class method to complete
> the implementation. __init__() is the most common example but not the
> only one. I don't consider this a design flaw at all. Another way to
> do this is for the base class method to call a hook method that
> subclasses can define but IMO that is often more trouble than it is
> worth.
>
> I don't see how you would use a decorator to do this.
>

Can you give an example? I've never seen this done, outside of __init__, in
a way where it wouldn't be clearer if the base class's methodname was just
named something else, and then have the Parent class's eventually overriden
method just call the renamed method. Put the common functionality in a
method that's not overriden.

Generally, I see subclasses adding methods to base classes and entirely
overriding methods, and nothing more.

Depending on what you need to do, you can pull out what would normally be in
the base classes method into a decorator that calls the subclassess method
and then does what it needs to do. I don't see this too often.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] The use of leading underscore in names

2009-05-12 Thread The Green Tea Leaf
The Python style guide says

"Use one leading underscore only for non-public methods and instance variables."

Have I understood correctly if I say that this is purely a convention
and there is nothing in the language that says that it should be this
way and that nothing special happens (except that it affects the 'from
X import *'). And no I don't intend to break this, I just want to
check that I've understood correctly.

(I understand the name mangling feature of double underscore)

-- 
The Green Tea Leaf   thegreenteal...@gmail.com   thegreentealeaf.blogspot.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Calling method in parent class

2009-05-12 Thread Kent Johnson
On Tue, May 12, 2009 at 8:44 AM, Jeremiah Dodds
 wrote:
> On Tue, May 12, 2009 at 12:27 PM, Kent Johnson  wrote:

>> I don't agree with this at all. It's not at all unusual for a derived
>> class to override a base class method in order to add additional
>> functionality to it, then to call the base class method to complete
>> the implementation. __init__() is the most common example but not the
>> only one. I don't consider this a design flaw at all. Another way to
>> do this is for the base class method to call a hook method that
>> subclasses can define but IMO that is often more trouble than it is
>> worth.
>>
>> I don't see how you would use a decorator to do this.
>
> Can you give an example?

Sure, here are real world examples from my current work project, in C#...

Many classes define
  protected override void Dispose(bool disposing)
and call
  base.Dispose(disposing)
in the implementation. This is a fine example; the derived class has
to implement some extra Dispose() functionality and also must ensure
that the base class Dispose() is called. There are 55 examples of this
in my project so I would have to say it is common :-)

GUI classes with custom painting or resizing behaviour call the base
class method to get the common behaviour, then add their particular
extra bit such as drawing a custom highlight.

I have a class that overrides ToString() (the C# equivalent of
__str__) to provide additional output. It calls base.ToString() to get
the base class representation.

Classes with serialization methods call the base class methods to
serialize base class fields, then serialize their own fields.

etc...

> I've never seen this done, outside of __init__, in
> a way where it wouldn't be clearer if the base class's methodname was just
> named something else, and then have the Parent class's eventually overriden
> method just call the renamed method. Put the common functionality in a
> method that's not overriden.

Sure, you can write

class Base(object):
  def someMethod(self):
self._someMethodImpl()

  def _someMethodImpl(self):
# do something

class Derived(Base):
  def someMethod(self):
self._someMethodImpl()
# do something else

but I don't see that that gives any advantage over the simpler

class Base(object):
  def someMethod(self):
# do something

class Derived(Base):
  def someMethod(self):
Base.someMethod(self)
# do something else

and if you don't have control over the code for Base (perhaps it is
part of a GUI framework or other third-party code) then you don't have
a choice to use the first option.

> Depending on what you need to do, you can pull out what would normally be in
> the base classes method into a decorator that calls the subclassess method
> and then does what it needs to do. I don't see this too often.

Can you give an example? I still don't see how that would work or why
it would be preferable to simply calling the base class method as in
my second option above.

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


Re: [Tutor] The use of leading underscore in names

2009-05-12 Thread Kent Johnson
On Tue, May 12, 2009 at 9:24 AM, The Green Tea Leaf
 wrote:
> The Python style guide says
>
> "Use one leading underscore only for non-public methods and instance 
> variables."
>
> Have I understood correctly if I say that this is purely a convention
> and there is nothing in the language that says that it should be this
> way and that nothing special happens (except that it affects the 'from
> X import *'). And no I don't intend to break this, I just want to
> check that I've understood correctly.

Yes, that is correct.

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


Re: [Tutor] The use of leading underscore in names

2009-05-12 Thread The Green Tea Leaf
Thank you
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Calling method in parent class

2009-05-12 Thread Jeremiah Dodds
On Tue, May 12, 2009 at 2:27 PM, Kent Johnson  wrote:

> On Tue, May 12, 2009 at 8:44 AM, Jeremiah Dodds
>  wrote:
> > On Tue, May 12, 2009 at 12:27 PM, Kent Johnson  wrote:
>
> >> I don't agree with this at all. It's not at all unusual for a derived
> >> class to override a base class method in order to add additional
> >> functionality to it, then to call the base class method to complete
> >> the implementation. __init__() is the most common example but not the
> >> only one. I don't consider this a design flaw at all. Another way to
> >> do this is for the base class method to call a hook method that
> >> subclasses can define but IMO that is often more trouble than it is
> >> worth.
> >>
> >> I don't see how you would use a decorator to do this.
> >
> > Can you give an example?
>
> Sure, here are real world examples from my current work project, in C#...
>
> Many classes define
>  protected override void Dispose(bool disposing)
> and call
>  base.Dispose(disposing)
> in the implementation. This is a fine example; the derived class has
> to implement some extra Dispose() functionality and also must ensure
> that the base class Dispose() is called. There are 55 examples of this
> in my project so I would have to say it is common :-)
>
> GUI classes with custom painting or resizing behaviour call the base
> class method to get the common behaviour, then add their particular
> extra bit such as drawing a custom highlight.
>
> I have a class that overrides ToString() (the C# equivalent of
> __str__) to provide additional output. It calls base.ToString() to get
> the base class representation.
>
> Classes with serialization methods call the base class methods to
> serialize base class fields, then serialize their own fields.
>
> etc...
>

Ahh, I stand corrected. Perhaps because the shop I work in is primarily
python, and because we strongly favor composition over inheritance, I never
see (python) classes being used this way.


>
> > I've never seen this done, outside of __init__, in
> > a way where it wouldn't be clearer if the base class's methodname was
> just
> > named something else, and then have the Parent class's eventually
> overriden
> > method just call the renamed method. Put the common functionality in a
> > method that's not overriden.
>
> Sure, you can write
>
> class Base(object):
>  def someMethod(self):
>self._someMethodImpl()
>
>  def _someMethodImpl(self):
># do something
>
> class Derived(Base):
>  def someMethod(self):
>self._someMethodImpl()
># do something else
>
> but I don't see that that gives any advantage over the simpler
>
> class Base(object):
>  def someMethod(self):
># do something
>
> class Derived(Base):
>  def someMethod(self):
>Base.someMethod(self)
># do something else
>
> and if you don't have control over the code for Base (perhaps it is
> part of a GUI framework or other third-party code) then you don't have
> a choice to use the first option.
>

Yes, if you don't have control over the code for Base, you don't really have
a choice.

Most of the time, when I see inheritance used in python, it's pretty much
just classes being used as containers for common functionality. If there are
two methods, one in the Base, and one in a Child, that share the same name,
but not all the functionality, it will be written like so:

class Base(object):
def common(self):
#do common stuff here
def overridden(self):
#do base-specific-stuff here
self.common()

class Child(Base):
def overriden(self):
#do child-specific-stuff here
self.common()

>
> > Depending on what you need to do, you can pull out what would normally be
> in
> > the base classes method into a decorator that calls the subclassess
> method
> > and then does what it needs to do. I don't see this too often.
>
> Can you give an example? I still don't see how that would work or why
> it would be preferable to simply calling the base class method as in
> my second option above.
>
> Kent
>

Yes, but again, it's not something that I see commonly done. We have a bunch
of python objects that communicate with a bunch of legacy apps via (and this
is something of a simplification) HTTP.  Sometimes, we need to enforce a
specific delay in between POSTs or GETs for a specific app, and it turned
out that there are other parts in our suite that benefit from having a delay
imposed, for various reasons. Instead of putting the delay functionality
into the Base class for these apps, we pulled it out into a decorator that
sits in a utility module.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Retrieving Data from Pmw.EntryFeild

2009-05-12 Thread Kent Johnson
On Tue, May 12, 2009 at 9:48 AM, Sampath Girish
 wrote:
> Thank you Mr Kent for giving me reply. I've done with that this afternoon.
> Now i got one more hurdle to cross. I need to take that data row wise and
> add it to a grid of same size.
>          For example i retrieved the entire data into a list as you said.
> Now i have to add it in the form of a grid(Its widget format is
> Tkinter.Label). i.e., I have to retrieve it from EntryField and place it in
> Tkinter.Label.
>          I got stuck at that step. Hope u got my bug and be helpful to reach
> this step. So my part would be great here.

This should be just another nested for loop. Inside the loop you can
read from the EntryField and write to the Label.

Kent

PS Please Reply All to reply to the list.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Import package module problem

2009-05-12 Thread Eike Welk
Hello Manuel!

On Tuesday 12 May 2009, man...@themacaque.com wrote:
> I have actually rearranged my code to have such hierarchy which
> obviously works. The problem is that I want ot be able to perform
> unit tests withinn the package of the code. I keep having the
> problem 

Use a test discovery program like py.test or nose. These programs 
start the test scripts with the right sys.path so that they can find 
their libraries.
py.test: http://codespeak.net/py/dist/test/test.html
nose:http://code.google.com/p/python-nose/

I've had similar problems with executing tests, and I have posted a 
short description how to use py.test to this list.
http://www.nabble.com/testing-framework-td23196352.html

Kind regards,
Eike.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Considering translating bash script to Python to learn

2009-05-12 Thread Dotan Cohen
> I think you should first keep these very pdf-specific tasks the way
> they are. Use the subprocess module to launch os commands. So
> that you can concentrate on translating the overall logic into python,
> which should not be too hard, probably.

This is what I thought, thanks.

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Alternative for Shelve

2009-05-12 Thread Timo

Kent Johnson schreef:

On Tue, May 12, 2009 at 3:59 AM, Timo  wrote:
  

Alan Gauld schreef:


"Timo"  wrote

  

I have an issue with the Shelve module. It works great for my needs, the
only problem is that a file made with Shelve isn't interchangable between
different computers.


I thought it would be.
What kind of computers are you having issues with?
And what kind of issues?
  

Currently only tested between Ubuntu and Windows on the same computer.
This is the end of the traceback:
bsddb.db.DBInvalidArgError: (22, 'Invalid argument -- :
unsupported hash version: 9')



shelve relies on the anydbm module for storage. anydbm may use any one
of several actual database implementations (dbhash, gdbm, dbm or
dumbdbm) depending on what is available. I guess you have different
modules available on the two machines. You can find out which module
is being used like this:

In [7]: import anydbm
In [8]: anydbm._defaultmod
Out[8]: 
  
I get the same result, only I have Python 2.6 on my Ubuntu installation 
and 2.5 on Windows. Maybe that is the problem. But still, then the user 
can't upgrade without breaking their database.


Also tried:
>>> import whichdb
>>> whichdb.whichdb('mydb.db')
'dbhash'

Same result on both.

Timo


You could force the use of a common db module by opening the file
explicitly. For example, to use dumbdbm, which is slow, simple and
guaranteed to be available, something like this (untested) should
work:

import dumbdbm
from shelve import Shelf

shelf = Shelf(dumbdbm.open('myfile', 'c'))

Kent
  


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


Re: [Tutor] Alternative for Shelve

2009-05-12 Thread Timo

Kent Johnson schreef:

On Tue, May 12, 2009 at 4:00 AM, Timo  wrote:
  

Kent Johnson schreef:


Try the pickle module.
  

I went from Pickle to Shelve because I couldn't store my wanted list of
dictionaries in Pickle.



What was the problem? You should be able to create a dict whose values
are lists of dicts. This would correspond to the dict-like object you
get from shelve. Then the whole dict could be pickled. For example:

In [10]: import pickle

In [11]: d=dict()

In [12]: d[1234567] = [{'date' : '2009-05-11', 'location' :
'Germany'}, {'date' : '2009-05-04', 'location' : 'France'}]

In [13]: d[7654321] = [{'date' : '2009-03-12', 'location' :
'Belgium'}, {'date' : '2009-04-23', 'location' : 'Spain'}]

In [14]: s = pickle.dumps(d)

In [15]: s
Out[15]: 
"(dp0\nI7654321\n(lp1\n(dp2\nS'date'\np3\nS'2009-03-12'\np4\nsS'location'\np5\nS'Belgium'\np6\nsa(dp7\ng3\nS'2009-04-23'\np8\nsg5\nS'Spain'\np9\nsasI1234567\n(lp10\n(dp11\ng3\nS'2009-05-11'\np12\nsg5\nS'Germany'\np13\nsa(dp14\ng3\nS'2009-05-04'\np15\nsg5\nS'France'\np16\nsas."

In [16]: d2 = pickle.loads(s)

In [17]: d2
Out[17]:
{1234567: [{'date': '2009-05-11', 'location': 'Germany'},
   {'date': '2009-05-04', 'location': 'France'}],
 7654321: [{'date': '2009-03-12', 'location': 'Belgium'},
   {'date': '2009-04-23', 'location': 'Spain'}]}

Kent
  


Hmm, I apparently missed something when I was researching it. I got 
mislead by the thing that Pickle can only have one key, but if you do it 
like this, I can indeed store multiiple ID's.


I will check this out.

Thanks,
Timo



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


Re: [Tutor] Calling method in parent class

2009-05-12 Thread Alan Gauld
"The Green Tea Leaf"  wrote 


class Child(Parent):
   def somemethod( self, bla ):
   Parent.somemethod(self,bla)

or like this

class Child(Parent):
   def somemethod( self, bla ):
   super(Child,self).somemethod(bla)


The first version seem to have the obvious disadvantage that I need to
know the name of the parent class when I write the call, 


But since you know the name of the parent when you write the 
class thats seldom an issue.



that the second version was the "proper" way of doing it. But when
doing some research on the web it seem like the second version also
have some problems.


This has been much improved in Python v3 but the issues with super 
in v2 are such that I usually recommend the explicit call (option 1)



My question is simple: what is the "best" way of doing this and why?


The one that works for you. In my case its option 1 because 
its explicit and therefore clear what exactly I'm calling.



Or should I mix both these approaches?


No, do not mix them, that way leads to madness IMHO! :-)

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

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


Re: [Tutor] Calling method in parent class

2009-05-12 Thread Alan Gauld

"Jeremiah Dodds"  wrote

Can you give a concrete example of _why_ you would want to do this? You 
can

use super, if you really want to, but it can get ugly (I do not fully
understand all of supers caveats). I can't think of a case off the top of 
my

head where you would want to call a parent class's method that a child
instance has overriden, but I'm sure it happens sometimes.


Actually I'd say this was the normal case in good OO programming.
You should program the differences so that mostly you are writing either
some extra initialisation or some local post processing with the bulk
of the code in the base class.

__init__ is the obvious case where you simply call the base class
to initialise the inherited attributes then add on the local attributes
in the child class. This ripples all the way up the inheritance chain.

Another similar case is where you are serialising an object. The
child class calls the parent class to serialise all of the inherited
stuff and then tags on the child features at the end. To deserialize
simply reverse the process.

Lisp makes this explicit by having before and after methods which
are automatically called. Thus for method foo the order is

before_foo() # ripples up the tree calling all the precondition code
foo()  # executes all the core code, usually only in 1 or 2 
classes

after_foo()# ripples up tree calling all the post condition code

We can fake this in other languages with a naming convention
such as the one above but we still need to do a fair bit of explicit
coding. Lisp does it automagically. (You might be able to do
something like it in Python using decoratorsh.)

HTH,

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



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


Re: [Tutor] Calling method in parent class

2009-05-12 Thread spir
Le Tue, 12 May 2009 07:27:52 -0400,
Kent Johnson  s'exprima ainsi:

> I don't agree with this at all. It's not at all unusual for a derived
> class to override a base class method in order to add additional
> functionality to it, then to call the base class method to complete
> the implementation. __init__() is the most common example but not the
> only one. I don't consider this a design flaw at all. 

Aside __init__, it's also common when overloading operators. One often needs 
the logic implemented in the base class to process the operation on instances 
of sub classes.
There's also the case of delegation.

Denis
--
la vita e estrany
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Calling method in parent class

2009-05-12 Thread Alan Gauld


"spir"  wrote



OK, bad example. But assume I have the same method in both classes and
want to call the method in the parent.


That should not happen! Basic contract is: same name = same meaning.


Nope, its called polymorphism.

The semantics may be the same but the implementation detail may differ 
and more specifically  the child implementation is likely to be a slight 
change on the parent. Its the calling of the parent code that keeps the 
essential semantics consistent.



Either you implement a method in a parent class to let all instances 
of child classes use it; 


Thats what he is doing, except that in the overriding metjod he wants 
to reuse the inherited functionality.


Having two methods with the name that both need two be used 
on the same object is clearly a design flaw. What do you think?


Two methods only one message. It is what polymorphism is all about.

The only case is when the parent method performs a part of 
what child class methods have to do. 


Exactly and in my experience of OO inheritance thats what happens 
most of the time.


Think:

foo.draw(), save(), write(), print(), copy(), read(), move(), etc

All of these operations will likely use the superclass functionality
and add a little bit of local processing for any attributes in the 
child class.


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


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


Re: [Tutor] Calling method in parent class

2009-05-12 Thread Alan Gauld


"Jeremiah Dodds"  wrote


> That should not happen! Basic contract is: same name = same meaning.

Same meaning yes, but that doesn't mean that I can't/shouldn't reuse
code that address a part of the problem.


If your superclass has a method with the same name (other than __init__
here), that contains some logic that a subclass that overrides the method
needs, it's written wrong in python.


No its not, this is standard OOP design in any OO language.
Polymorphism is where the power of OOP reallly comes into play.
If you have to write all of the code for every overridden method
then I'd say that was bad design.


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



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


Re: [Tutor] Calling method in parent class

2009-05-12 Thread Alan Gauld


"Jeremiah Dodds"  wrote


Ahh, I stand corrected. Perhaps because the shop I work in is primarily
python, and because we strongly favor composition over inheritance, I 
never

see (python) classes being used this way.


Composition over inheritance has now become so overused it
is losing one of the biggest adbvantages of OOP. That concept
was introduced because in the early days of OOP adoption
(early 90s) people were grossly abusing inheritance to reduce
coding but then causing horrible problems with maintenance
and reuse.

But inheritance is still the best mechanism when the "is-a"
relationship test is valid. Widgets in a GUI heirarchy are good
examples, as are bank acounts, data streams, etc


Most of the time, when I see inheritance used in python, it's pretty much
just classes being used as containers for common functionality.


Sadly thats often the case but its not really OO programming, its
just programming with objects! The hysteria over abuse of inheritance
has kind of thrown the baby out with the bathwater IMHO!


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



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


Re: [Tutor] Considering translating bash script to Python to learn

2009-05-12 Thread Alan Gauld


"Dotan Cohen"  wrote


I am considering translating a homegrown bash script to Python to
learn the language. 


Thats rarely a good approach. While you can replace bash 
with Python you will just wind up calling a bunch of external 
programs and thats what shell scripts are best at. The only 
time its worthwhile is where the bash code is structurally 
complex with lots of loops and conditionals and local state.




rearranges, then sends the whole thing to the printer. However, I seem
to depend on many bash-specific functions (os programs) and I cannot
find Python equivalents. Here are some lines of the script, and the
relevant questions:


The key is what you say here. The core code depends on os 
programs (not bash functions!). Python can probably replace 
some of those os programs but why bother unless you need to 
retire them or are paying money for them?



gnome-web-print --mode=print --files $FILE /tmp/weeklyCalendar.pdf
Here, I am converting an HTML file to PDF. I rely on the external
program gnome-web-print to do the conversion. Does Python have a
native way to handle this, or would I just wind up calling
gnome-web-print from within python?


You could write a program to do this in python but it would be 
bigger than your entire bash script replacement.



pdftops -f 2 -l 2 $HOME/.bin/todo/todo.odf.pdf /tmp/weeklyTodo.ps
Here I am exporting the second page of a PDF file as a PS file.
Actually, the file in question is a hybrid ODF-PDF file and if Python
has a way of exporting a specific page of a ODF file that is fine too.
I could export to PDF as well, the important bit is too isolate a
single page of either an ODF or PDF file and have it as either a PS or
PDF.


Same here although ReportLab (a non standard lib Python module) may 
have some helper functions for converting PDF to ps.



gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite
-sOutputFile=/tmp/weeklyCalendarPrintMe.pdf
$HOME/.bin/todo/weeklyCalendar-blank.pdf /tmp/weeklyCalendar.pdf
/tmp/weeklyTodo.ps $HOME/.bin/todo/weeklyCalendar-blank.pdf
Here, I am combining several PDF and PS files as a single PDf file.
Can Python do this?


Again you probably could since PDF and PS are both text like formats
internally but it would be quite a lot of work.


lpr -P printer -o number-up=2 /tmp/weeklyCalendarPrintMe.pdf
Here I am sending the final file to the printer, and having it print 2
pages on each page. Again, is this something that Python can handle
internally?


This is so OS and local environment specific that Python 
usually just delegates this to lpr in my experience!



Thanks for the help. I know that Python is not specifically designed
to manipulate PDF files, but as the script is getting more complex and
performs logic in other sections (not shown here) I would like to take
advantage of other Python properties.


For PDF you should look at ReportLab. It is really designed for 
creating PDFs from non PDF data (eg out of a database or with 
graphics etc). Combined with a html parser such as Beautiful Soup

that aspect may be worth converting to Python.

HTH,


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

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


Re: [Tutor] Calling method in parent class

2009-05-12 Thread spir
Le Tue, 12 May 2009 17:43:24 +0100,
"Alan Gauld"  s'exprima ainsi:

> > Having two methods with the name that both need two be used 
> > on the same object is clearly a design flaw. What do you think?  
> 
> Two methods only one message. It is what polymorphism is all about.

Well, I do not want to argue. But this is not what I call polymorphism.
Not "on the same object". Polymorphism as I know it rather dispatches depending 
on the object (usually it's actual type).
The kind of exception beeing the case of one method calling the other (as I 
related later in the same post). But it still is not is calling 2 methods with 
the same name on the same object. It's rather one method reusing another.

Denis
--
la vita e estrany
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] simply moving files

2009-05-12 Thread Matt Herzog
On monday I posted the below code:

def schmove(src,dst):
... src = '/home/datasvcs/PIG/cjomeda_exp/'
... dst = '/home/datasvcs/PIG/cjomeda_exp_archive/'
... listOfFiles = os.listdir(src)
... for filez in listOfFiles:
... os.system("mv"+ " " + src + " " + dst)

David Angel replied to my post and I guess I accidentally deleted his response. 
Today I found his response posted on mail-archive.com and tried some 
variations. They all failed.

David said, "Just use os.rename() if the dest is a directory, it'll move the 
file there."

Example: If I use: "os.rename(src, dst)" where I had "os.system("mv"+ " " + src 
+ " " + dst)" no files are coppied.

os.renames happily renames the source directory, but that's not what I want.

Any other suggestions?

-- Matt



-- 
I fear you speak upon the rack,
Where men enforced do speak anything.

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


[Tutor] Toronto PyCamp 2009

2009-05-12 Thread Chris Calloway
For beginners, this ultra-low-cost Python Boot Camp developed by the 
Triangle Zope and Python Users Group makes you productive so you can get 
your work done quickly. PyCamp emphasizes the features which make Python 
a simpler and more efficient language. Following along by example speeds 
your learning process in a modern high-tech classroom. Become a 
self-sufficient Python developer in just five days at PyCamp!


The University or Toronto Department of Physics brings PyCamp to 
Toronto, July 13-17, 2009.


Register today at http://trizpug.org/boot-camp/pycamp-toronto-2009/

--
Sincerely,

Chris Calloway
http://www.secoora.org
office: 332 Chapman Hall   phone: (919) 599-3530
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599



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


Re: [Tutor] simply moving files]

2009-05-12 Thread David

David wrote:




Subject:
[Tutor] simply moving files
From:
Matt Herzog 
Date:
Tue, 12 May 2009 13:51:36 -0400
To:
Python List 

To:
Python List 


On monday I posted the below code:

def schmove(src,dst):
... src = '/home/datasvcs/PIG/cjomeda_exp/'
... dst = '/home/datasvcs/PIG/cjomeda_exp_archive/'
... listOfFiles = os.listdir(src)
... for filez in listOfFiles:
... os.system("mv"+ " " + src + " " + dst)

David Angel replied to my post and I guess I accidentally deleted his response. 
Today I found his response posted on mail-archive.com and tried some 
variations. They all failed.

David said, "Just use os.rename() if the dest is a directory, it'll move the file 
there."

Example: If I use: "os.rename(src, dst)" where I had "os.system("mv"+ " " + src + " 
" + dst)" no files are coppied.

os.renames happily renames the source directory, but that's not what I want.

Any other suggestions?

-- Matt




I did not try Davids example but Kents works fine here;

#!/usr/bin/python
#Python 2.6.2
import os
src = '/home/david/test_src/'
dst = '/home/david/test/'
listofFiles = os.listdir(src)
for fnames in listofFiles:
os.system("mv %s/%s %s" % (src, fnames, dst))
results = os.listdir(dst)
print results

[results]
david [03:37 PM] opteron ~ $ ./tutor_mv.py
['fruit_loops.py', 'numberList.py', 'sumList.py']
david [03:42 PM] opteron ~ $ ls /home/david/test
fruit_loops.py  numberList.py  sumList.py


--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Considering translating bash script to Python to learn

2009-05-12 Thread Dotan Cohen
> Thats rarely a good approach. While you can replace bash with Python you
> will just wind up calling a bunch of external programs and thats what shell
> scripts are best at.

That is why is has been a bash script until now.

> The only time its worthwhile is where the bash code is
> structurally complex with lots of loops and conditionals and local state.
>

That's where it is going, I am starting to have date-dependant
functions and such. The bash is getting messy.

>> rearranges, then sends the whole thing to the printer. However, I seem
>> to depend on many bash-specific functions (os programs) and I cannot
>> find Python equivalents. Here are some lines of the script, and the
>> relevant questions:
>
> The key is what you say here. The core code depends on os programs (not bash
> functions!). Python can probably replace some of those os programs but why
> bother unless you need to retire them or are paying money for them?

Because the direction of the script is getting complex. But I still
have my reservations.

>> gnome-web-print --mode=print --files $FILE /tmp/weeklyCalendar.pdf
>> Here, I am converting an HTML file to PDF. I rely on the external
>> program gnome-web-print to do the conversion. Does Python have a
>> native way to handle this, or would I just wind up calling
>> gnome-web-print from within python?
>
> You could write a program to do this in python but it would be bigger than
> your entire bash script replacement.
>

I see!

>> pdftops -f 2 -l 2 $HOME/.bin/todo/todo.odf.pdf /tmp/weeklyTodo.ps
>> Here I am exporting the second page of a PDF file as a PS file.
>> Actually, the file in question is a hybrid ODF-PDF file and if Python
>> has a way of exporting a specific page of a ODF file that is fine too.
>> I could export to PDF as well, the important bit is too isolate a
>> single page of either an ODF or PDF file and have it as either a PS or
>> PDF.
>
> Same here although ReportLab (a non standard lib Python module) may have
> some helper functions for converting PDF to ps.
>

Thanks, I did see that mentioned today while googling.

>> gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite
>> -sOutputFile=/tmp/weeklyCalendarPrintMe.pdf
>> $HOME/.bin/todo/weeklyCalendar-blank.pdf /tmp/weeklyCalendar.pdf
>> /tmp/weeklyTodo.ps $HOME/.bin/todo/weeklyCalendar-blank.pdf
>> Here, I am combining several PDF and PS files as a single PDf file.
>> Can Python do this?
>
> Again you probably could since PDF and PS are both text like formats
> internally but it would be quite a lot of work.
>

The intention was to have a library function to use, not to code a
parser myself.

>> lpr -P printer -o number-up=2 /tmp/weeklyCalendarPrintMe.pdf
>> Here I am sending the final file to the printer, and having it print 2
>> pages on each page. Again, is this something that Python can handle
>> internally?
>
> This is so OS and local environment specific that Python usually just
> delegates this to lpr in my experience!
>

That is logical and what I expected to hear.

>> Thanks for the help. I know that Python is not specifically designed
>> to manipulate PDF files, but as the script is getting more complex and
>> performs logic in other sections (not shown here) I would like to take
>> advantage of other Python properties.
>
> For PDF you should look at ReportLab. It is really designed for creating
> PDFs from non PDF data (eg out of a database or with graphics etc). Combined
> with a html parser such as Beautiful Soup
> that aspect may be worth converting to Python.
>

Thanks.

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] simply moving files

2009-05-12 Thread Kent Johnson
On Tue, May 12, 2009 at 1:51 PM, Matt Herzog  wrote:
> On monday I posted the below code:
>
> def schmove(src,dst):
> ...         src = '/home/datasvcs/PIG/cjomeda_exp/'
> ...         dst = '/home/datasvcs/PIG/cjomeda_exp_archive/'
> ...         listOfFiles = os.listdir(src)
> ...         for filez in listOfFiles:
> ...             os.system("mv"+ " " + src + " " + dst)
>
> David Angel replied to my post and I guess I accidentally deleted his 
> response. Today I found his response posted on mail-archive.com and tried 
> some variations. They all failed.
>
> David said, "Just use os.rename() if the dest is a directory, it'll move the 
> file there."
>
> Example: If I use: "os.rename(src, dst)" where I had "os.system("mv"+ " " + 
> src + " " + dst)" no files are coppied.
>
> os.renames happily renames the source directory, but that's not what I want.

You are still not using the actual file name in your command. src is a
directory, so os.rename(src, dst) renames the directory. Try
os.rename(os.path.join(src, filez), os.path.join(dst, filez))

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


Re: [Tutor] How to set up an Array?

2009-05-12 Thread nickel
Kent Johnson  tds.net> writes:

> In [39]: rr = [ ','.join(t for t in i if t!='-') for i in zip(*(
> i.split() for i in p.findall(s) )) ]
> 
> In [40]: rr
> Out[40]:
> ['RA7,OSC1,CLKI',
>  'RA6,OSC2,CLKO',
>  'RA5,AN4,nSS1,LVDIN,RCV,RP2',
>  '',
>  'RA3,AN3,VREF_PLUS,C1INB',
>  'RA2,AN2,VREF_MINUS,CVREF_MINUS,C2INB',
>  'RA1,AN1,C2INA,PMPA7,RP1',
>  'RA0,AN0,C1INA,PMPA6,RP0']
> 
> Kent

Wow, really impressed with the reply's so far.  Have compiled
them all, and much to learn from each point of view.  No 'one
liners' for me (at the moment)
though..haha:-).

Seeing the Python functions, library's, syntax etc. on a real
problem isinspirational to me.  Much to learn and digest.  With 
some additional conditions, Python will let me slice through
the target 68k text file in no time.

Thanks to all.  Any future posts will be given due consideration, 
thanks in advance.

Kent
(yes, there is another one)





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


Re: [Tutor] Calling method in parent class

2009-05-12 Thread Alan Gauld


"spir"  wrote


Two methods only one message. It is what polymorphism is all about.


Well, I do not want to argue. But this is not what I call polymorphism.
Not "on the same object". Polymorphism as I know it rather dispatches 
depending on the object (usually it's actual type).


Yes, the two methiods are in different classes.

But it is totally normal for a polymorphic method to call the code in 
the base class for that same method. In my experience that is more 
common than not doing it. It would be very suspicious to me to be 
overriding a method and *not* calling the base class (unless the base 
class was a pure abstract class - aka an interface)  since that would 
imply that the methods were semantically different.


The kind of exception beeing the case of one method calling 
the other (as I related later in the same post). But it still is not is 
calling 2 methods with the same name on the same object. 
It's rather one method reusing another.


Yes, that would be self messaging which is a different thing altogether
But calling the method of a superclass from the same method is very, 
very common. 

Bjarne Stroustrup describes this practice in "The C++ Programming 
Language" as: 
-- quote ---
"The cleanest solution is for the derived class to use only the public 
members of its base class. For example


void Manager::print() const
{   Empoyee::print()  // print Employee info
cout << level;  // print Manager specific info
};

Note that :: must be used because print has been redefined in manager. 
SUCH REUSE OF NAMES IS TYPICAL 
--end quote--

(caps mine)

Although Python is not C++ it makes no difference in this case, 
the principle is the same.


And Grady Booch says in his OOAD book when discussing a 
method  defined as:


- quote --
void ElectricData::send() {
   TelemetryData::send()
   // transmit the electric data
}

Most OO languages permit the implementation of a subclass's 
method to invoke a method defined in some super class. As this 
exampler shows IT IS COMMON for the implementation  of a 
redefined method TO INVOKE THE METHOD OF THE 
SAME NAME DEFINED BY A PARENT CLASS.


...

In our experience, a developer USUALLY NEEDS TO INVOKE 
A SUPERCLASS METHOD EITHER JUST BEFORE OR 
AFTER DOING SOME OTHER ACTION. In this way subclass 
methods play a role in AUGMENTING THE BEHAVIOUR 
DEFINED IN THE SUPERCLASS.

- end quote --
(caps mine)

So at least two well known OOP authorities recognise that such 
is common practice.


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

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


Re: [Tutor] simply moving files

2009-05-12 Thread Alan Gauld


"Matt Herzog"  wrote

os.renames happily renames the source directory, but that's not what I 
want.


Any other suggestions?


You still haven't said why you can't use shutil.move()

move() uses rename if appropriate or copies/deletes if not.
It makes moving much more reliable and saves you a lot of
extra work checking whether the src and dst are on the same
filesystem etc.

You should justy be abloe to use shutil.move()
What is the probnlem with this (apart from Kent's point that
you were not passing filenames originally!)


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



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


[Tutor] [Fwd: Re: simply moving files]]

2009-05-12 Thread David

Forwarded to the list, I would also like to understand the forward slash;
os.system("mv %s/%s %s" % (src, fnames, dst))
--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
--- Begin Message ---
On Tue, May 12, 2009 at 03:50:00PM -0400, David wrote:
> David wrote:
> >
> >
> >
> >Subject:
> >[Tutor] simply moving files
> >From:
> >Matt Herzog 
> >Date:
> >Tue, 12 May 2009 13:51:36 -0400
> >To:
> >Python List 
> >
> >To:
> >Python List 
> >
> >
> >On monday I posted the below code:
> >
> >def schmove(src,dst):
> >... src = '/home/datasvcs/PIG/cjomeda_exp/'
> >... dst = '/home/datasvcs/PIG/cjomeda_exp_archive/'
> >... listOfFiles = os.listdir(src)
> >... for filez in listOfFiles:
> >... os.system("mv"+ " " + src + " " + dst)
> >
> >David Angel replied to my post and I guess I accidentally deleted his 
> >response. Today I found his response posted on mail-archive.com and tried 
> >some variations. They all failed.
> >
> >David said, "Just use os.rename() if the dest is a directory, it'll move 
> >the file there."
> >
> >Example: If I use: "os.rename(src, dst)" where I had "os.system("mv"+ " " 
> >+ src + " " + dst)" no files are coppied.
> >
> >os.renames happily renames the source directory, but that's not what I 
> >want.
> >
> >Any other suggestions?
> >
> >-- Matt
> >
> >
> >
> I did not try Davids example but Kents works fine here;
> 
> #!/usr/bin/python
> #Python 2.6.2
> import os
> src = '/home/david/test_src/'
> dst = '/home/david/test/'
> listofFiles = os.listdir(src)
> for fnames in listofFiles:
> os.system("mv %s/%s %s" % (src, fnames, dst))
> results = os.listdir(dst)
> print results

Actually, the above does EXACTLY what I want. I hope I did not seem accusatory 
in my previous post. I'm just under some pressure and had become frustrated. 
Maybe on the weekend I'll have time to understand the line: 

os.system("mv %s/%s %s" % (src, fnames, dst)) 

Many thanks. 

-- Matt
> 
> [results]
> david [03:37 PM] opteron ~ $ ./tutor_mv.py
> ['fruit_loops.py', 'numberList.py', 'sumList.py']
> david [03:42 PM] opteron ~ $ ls /home/david/test
> fruit_loops.py  numberList.py  sumList.py
> 
> 
> -- 
> Powered by Gentoo GNU/Linux
> http://linuxcrazy.com

-- 
I fear you speak upon the rack,
Where men enforced do speak anything.

- William Shakespeare


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


Re: [Tutor] [Fwd: Re: simply moving files]]

2009-05-12 Thread sli1que
Dave
Slashes in linux indicate a directory path. You use them when trying to specify 
paths. You can also use them to specify a path to a file.
Sent from my Verizon Wireless BlackBerry

-Original Message-
From: David 

Date: Tue, 12 May 2009 20:07:10 
To: 
Subject: [Tutor] [Fwd: Re:  simply moving files]]


Forwarded to the list, I would also like to understand the forward slash;
os.system("mv %s/%s %s" % (src, fnames, dst))
-- 
Powered by Gentoo GNU/Linux
http://linuxcrazy.com



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