[Tutor] MySQLdb.converters.escape() type error

2006-05-28 Thread Jan Eden
Hi,

after upgrading to MySQL 5 and MySQLdb 1.2.1_p2, I have the following problem:

self.db=MySQLdb.connect(host=host, user=user, passwd=passwd, db=db, 
cursorclass=MySQLdb.cursors.DictCursor)
stringel = 'Some string'
stringel = self.db.escape(stringel)

  File ./test.py, line 12, in ?
stringel = self.db.escape(stringel)
TypeError: no default type converter defined

I checked the documentation for MySQLdb.converters and saw that the escape() 
function takes a dictionary as an obligatory second argument.

This is odd, because I have always been using escape(string) without a problem.

The changes in MySQLdb 1.2.1_p2 list:

Mapped a lot of new 4.1 and 5.0 error codes to Python exceptions

Could someone point me to the problem in the MySQL side? Thanks in advance!

- Jan
--  
Any technology which is distinguishable from magic is insufficiently advanced.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Webprogramming with the MVC pattern

2006-03-23 Thread Jan Eden
Hi,

I am about to build my first web application using the MVC pattern. Now I am 
wondering which might be the best way to initialize both a model and a 
presenter based on the model and its state.

My controller should look like this:

#
model = Models.ModelFactory(cgi_parameters)
view = Views.ViewFactory(model)
view.Display()
#

The factory method ModelFactory would check the parameters and return an 
appropriate model:


def ModelFactory(params):
valid_models = dict(location=Location, prices=Prices, booking=Booking)
return valid_models[params['type']](**params)

class Location:
...
class Prices:
...
class Booking:
...


But I am stuck with the ViewFactory method. Since the appropriate view depends 
on both the model's class (type) and state, I am not sure how to implement 
this. I could do it the ugly way:


def ViewFactory(model):
if (model.__class__ == 'Booking' and model.state == 'new'):
view = new NewBooking()
elsif (model.__class__ == 'Booking' and model.state == 'review'):
view = new BookingReview()
...
return view

class LocationView:
...
class NewBooking:
...
class BookingReview:
...
class BookingConfirmation:
...


But there must be a better way. Could you give me a hint?

Thanks,

Jan
-- 
A common mistake that people make when trying to design something completely 
foolproof is to underestimate the ingenuity of complete fools.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] XSLT module

2005-12-09 Thread Jan Eden
Hi,

I intend to use an XSLT processor, and found various modules (4suite, Sab-Pyth) 
on the web. Could anyone recommend a specific module for transforming XML files?

Thanks,

Jan
-- 
It's overkill, of course. But you can never have too much overkill.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Exception repeated in a loop

2005-12-06 Thread Jan Eden
Hi,

I use the following loop to parse some HTML code:

for record in data:
try:
parser.feed(record['content'])
except HTMLParseError, (msg):
print !!!Parsing error in, record['page_id'], : , msg

Now after HTMLParser encounters a parse error in one record, it repeats to 
execute the except statement for all following records - why is that?

!!!Parsing error in 8832 :  bad end tag: '/em b', at line 56568, column 
1647999
!!!Parsing error in 8833 :  bad end tag: '/em b', at line 56568, column 
1651394
!!!Parsing error in 8834 :  bad end tag: '/em b', at line 56568, column 
1654789
!!!Parsing error in 8835 :  bad end tag: '/em b', at line 56568, column 
1658184

Thanks.

Jan
-- 
Hanlon's Razor: Never attribute to malice that which can be adequately 
explained by stupidity.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Exception repeated in a loop

2005-12-06 Thread Jan Eden
Hi Pawel,

Pawel Kraszewski wrote on 06.12.2005:

Dnia wtorek, 6 grudnia 2005 16:29, Jan Eden napisa?:
 Hi,

 I use the following loop to parse some HTML code:

 for record in data:
 try:
 parser.feed(record['content'])
 except HTMLParseError, (msg):
 print !!!Parsing error in, record['page_id'], : , msg

 Now after HTMLParser encounters a parse error in one record, it repeats to
 execute the except statement for all following records - why is that?

Short answer: because you told Python to do so...

Long answer:

My hint for students having such problems is to execute their code with a 
pencil on a hardcopy. They read aloud what the program currently does  - 
usually they spot the error during the first reading.

Your code being read loud

1. begin loop
2.  attempt to execute parser.feed
3.   abort attempt if it fails, showing the error
4. take next loop

So - you take next loop regardless of the failure or not. There are two ways 
out of here. I wrote them aloud, to transcribe into python as an excersize:

(Notice the difference between this and your original)

I)

1. attempt to 
2.  begin loop
3.   abort attempt if it fails, showing the error
4.  take next loop

II)
1. begin loop
2.  attempt to execute parser.feed
3.   abort attempt if it fails, showing the error AND breaking the loop
4. take next loop

Thanks, I tested your suggestion, which works fine. But I don't understand the 
problem with my original code.

If the parser raises an exception for a certain record, it should print the 
error message and move on to the next record in the loop. Why would I need the 
break statement? What's more - if the break statement is executed, all 
following records will never be parsed.

I still don't understand why failure of a single record affects the other 
records.

Thanks,

Jan
-- 
There's no place like ~/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Exception repeated in a loop

2005-12-06 Thread Jan Eden
Hi,

Nelson, Scott wrote on 06.12.2005:

An unhandled exception immediately stops the execution of your code.

A handled exception (try/except) does not stop code execution (unless
you explicitly tell it to).

This shows how a handled exception does not stop code execution:

try:
   raise Exception
except:
   print 'caught exception'
print 'fell through'

This is exactly what I need Python to do: Raise the exception for a certain 
record and go on with the following records.

I just do not see why the same loop is raised over and over again - obviously 
because of the same malformed HTML tag.

Adding a break statement causes Python to skip all following records, which is 
not what I need.

Thanks,

Jan
-- 
There are two major products that come out of Berkeley: LSD and UNIX. We don't 
believe this to be a coincidence. - Jeremy S. Anderson
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Exception repeated in a loop

2005-12-06 Thread Jan Eden
Kent Johnson wrote on 06.12.2005:

The parser processes up to the error. It never recovers from the
error. HTMLParser has an internal buffer and buffer pointer that is
never advanced when an error is detected; each time you call feed()
it tries to parse the remaining data and gets the same error again.
Take a look at HTMLParser.goahead() in Lib/HTMLParser.py if you are
interested in the details.

Aha! That's what I needed to know. Thanks to all who answered.

- Jan
-- 
I'd never join any club that would have the likes of me as a member. - Groucho 
Marx
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Malformed CSV

2005-12-02 Thread Jan Eden
Hi,

I need to parse a CSV file using the csv module:

hotel,9,463,95,1.00
hotels,7,033,73,1.04
hotels hamburg,2,312,73,3.16
hotel hamburg,2,708,42,1.55
Hotels,2,854,41,1.44
hotel berlin,2,614,31,1.19

The idea is to use each single keyword (field 1) as a dictionary key and sum up 
the clicks (field 2) and transactions (field 3):

try:
keywords[keyword]['clicks'] += clicks
keywords[keyword]['transactions'] += transactions
# if the keyword has not been found yet...
except KeyError:
keywords[keyword] = { 'clicks' : clicks, 'transactions' : 
transactions }

Unfortunately, the quote characters are not properly escaped within fields:

hotel,hamburg,1,0,0
hotel,billig, in berlin tegel,1,0,0
hotel+wien,1,0,0
hotel+nürnberg,1,0,0
hotel+london,1,0,0
hotel budapest billig,1,0,0

which leads to the following output (example):

hotel9,463hamburgbillig951 in berlin tegel

As you can see, Python added 'hamburg' and 'billig' to the first 'hotel' 
row's click value (9,463), and '1' as well as ' in berlin tegel' to the 
transactions (95). I am aware that I need to convert real clicks/transactions 
to integers before adding them, but I first wanted to sort out the parsing 
problem.

Is there a way to deal with the incorrect quoting automatically?

Thanks,

Jan
-- 
I was gratified to be able to answer promptly, and I did. I said I didn't know. 
- Mark Twain
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Malformed CSV

2005-12-02 Thread Jan Eden
Kent Johnson wrote on 02.12.2005:

I'm not entirely sure how you want to interpret the data above. One
possibility is to just change the double  to single  before
processing with csv. For example:

# data is the raw data from the whole file
data = '''hotel,hamburg,1,0,0
hotel,billig, in berlin tegel,1,0,0
hotel+wien,1,0,0
hotel+nurnberg,1,0,0
hotel+london,1,0,0
hotel budapest billig,1,0,0'''

data = data.replace('', '')
data = data.splitlines()

import csv

for line in csv.reader(data):
print line

Output is 
['hotel,hamburg', '1', '0', '0']
['hotel,billig, in berlin tegel', '1', '0', '0']
['hotel+wien', '1', '0', '0']
['hotel+nurnberg', '1', '0', '0']
['hotel+london', '1', '0', '0']
['hotel budapest billig', '1', '0', '0']

which looks pretty reasonable except for the last line, and I don't
really know what you would consider correct there.

Exactly, the last line is the problem. With correct (Excel-style) quoting, it 
would look like this

hotel budapest billig,1,0,0

i.e. each quote within a field would be doubled, and the output would be

['hotel budapest billig', '1', '0', '0']

i.e. the quoting of the original search string

hotel budapest billig

would be preserved (and this is important). I guess I need to notify the 
engineer responsible for the CSV output and have the quoting corrected.

Thanks,

Jan
-- 
Any sufficiently advanced technology is indistinguishable from a Perl script. - 
Programming Perl
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Malformed CSV

2005-12-02 Thread Jan Eden
Kent Johnson wrote on 02.12.2005:

Jan Eden wrote:
I guess I need to notify the engineer responsible for the CSV
output and have the quoting corrected.

If that is possible it is a much better solution. I hate to hack
around bad data - much better to correct the source of the data if
possible.

Right.

In fact you may have little choice if you want to use the CSV module
- for example what if the first field has commas and quotes? Could
you have a line like this? hotel, budapest,
billig,1,0,0
[...]

BTW do you really have doubled quotes in all the hotel fields, or
just the one with quotes? The data in your original post is
inconsistent.

Yes, and that's the source of my problem: The data is based on user input to 
Google, which tends to be extremely inconsistent. Users seem to use any kind of 
absurd quoting, like

hotel miami
miami,hotel

Thanks again,

Jan
-- 
Life's unfair - but root password helps!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dynamic inheritance?

2005-11-22 Thread Jan Eden
Hi,

Kent Johnson wrote on 20.11.2005:

Use getattr() to access attributes by name. SiteA is an attribute of
Templates and Page is an attribute of SiteA so you can get use
getattr() twice to get what you want:

site = getattr(Templates, self.site_name) self.template =
getattr(site, self.template_type)


Unfortunately, this does not seem to work if Templates is a package, not a 
module. Python complains:

AttributeError: 'module' object has no attribute 'SiteA' 
  args = ('module' object has no attribute 'SiteA',)

even though there is a module SiteA within package Templates. When manually 
importing SiteA from Templates, everything is good.

From your previous message, I read that modules are treated just like classes 
or any other attribute - did I misinterpret your advice?

Thanks,

Jan
-- 
I was gratified to be able to answer promptly, and I did. I said I didn't know. 
- Mark Twain
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dynamic inheritance?

2005-11-22 Thread Jan Eden
Hi,

Jan Eden wrote on 22.11.2005:

Hi,

Kent Johnson wrote on 20.11.2005:

Use getattr() to access attributes by name. SiteA is an attribute
of Templates and Page is an attribute of SiteA so you can get use
getattr() twice to get what you want:

site = getattr(Templates, self.site_name) self.template =
getattr(site, self.template_type)


Unfortunately, this does not seem to work if Templates is a package,
not a module. Python complains:

AttributeError: 'module' object has no attribute 'SiteA'
  args = ('module' object has no attribute 'SiteA',)

even though there is a module SiteA within package Templates. When
manually importing SiteA from Templates, everything is good.

Found a solution:

import Templates
#...
def GetTemplates(self):
__import__('Templates.', globals(), locals(), [self.identifier])
site = getattr(Templates, self.identifier)
self.template = getattr(site, self.template_type)

works.

Thanks,

Jan
-- 
He who would give up a little liberty in return for a little security deserves 
neither liberty nor security. - Benjamin Franklin
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dynamic inheritance?

2005-11-20 Thread Jan Eden
Kent Johnson wrote on 20.11.2005:

Use getattr() to access attributes by name. SiteA is an attribute of Templates 
and Page is an attribute of SiteA so you can get use getattr() twice to get 
what 
you want:

site = getattr(Templates, self.site_name)
self.template = getattr(site, self.template_type)


Thank you! I did not take into account that modules and classes can be treated 
just like data attributes.

- Jan
-- 
Remember: use logout to logout.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Dynamic inheritance?

2005-11-19 Thread Jan Eden
Hi,

I have a number of classes, each of which should inherit from a related 
superclass in another module:

class A(Super.A):
...

class B(Super.B):
...

class C(Super.C):
...

Is there a way to dynamically determine the value of Super at runtime? 
Background: Depending on certain object attributes which are set during the 
object initialization, I need to use a different set of templates for the 
respective object.

Example: If a page object belongs to site A, it needs to inherit from the 
template class SiteA.Page, a gallery object belonging to site B should inherit 
from SiteB.Gallery etc.

The problem is that the template classes are not self contained, i.e. 
SiteB.Gallery inherits from SiteB.List, SiteB.Base etc.

Thanks in advance,

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


Re: [Tutor] Dynamic inheritance?

2005-11-19 Thread Jan Eden
Hi Kent,

Kent Johnson wrote on 19.11.2005:

Jan Eden wrote:

 Is there a way to dynamically determine the value of Super at
 runtime? Background: Depending on certain object attributes which are
 set during the object initialization, I need to use a different set
 of templates for the respective object.

Sure, just import the correct template module conditionally and give it a new 
name:

if site == 'siteA':
  import SiteA as Super
else
  import SiteB as Super

class A(Super.A):

etc.

If you need to do the import based on a string use the __import__() function:
http://www.python.org/doc/current/lib/built-in-funcs.html

Excellent. This is exactly what I need. I was not aware of the fact that you 
can rename modules upon importing them.

 The problem is that the template classes are not self contained, i.e.
 SiteB.Gallery inherits from SiteB.List, SiteB.Base etc. 
 Thanks in advance,

I don't see why that is a problem?

Please disregard the last statement in my first message: There is indeed no 
problem with this requirement.

Thanks for your help,

Jan
-- 
Common sense is what tells you that the world is flat.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dynamic inheritance?

2005-11-19 Thread Jan Eden
Kent Johnson wrote on 19.11.2005:

Danny Yoo wrote:
Here's a small example that shows how classes can be treated just
like any other value in Python:
 
 #
 def makeYa(superclass):
 class Ya(superclass):
 def sayHi(self):
 superclass.sayHi(self)
 print ya
 return Ya
 
 class ValleyPerson:
 def sayHi(self):
 print like, so, oh my gosh, hi?
 
 FrankensteinClass = makeYa(ValleyPerson)
 instance = FrankensteinClass()
 instance.sayHi()
 #

Yeah, that'll work too :-) Or even

def makeAB(moduleContainingSuperClass):
  class A(moduleContainingSuperClass.A):
pass
  class B(moduleContainingSuperClass.B)
pass
  return A, B

A, B = makeAB(siteA)
 
So there's no need to do trickery with conditional imports; Python
treats classes as first-class objects that can be passed around.

Trickery? ;) It's just using modules as first-class objects that are
bound to names same as anything else. Which solution is better
depends on whether you want to choose at the module level or with
finer control.

Hm, sounds like there's more than one way to do it. ;-) Thanks a lot for your 
examples.

I hate to confess that I incorrectly described my requirements. It turns out 
that I am better off with a (variant of the) state design pattern. But I am 
stuck there, too.

The situation is this:

For every object, two string attributes are determined during initialization 
(one being read from a database, the other inherited as a superclass 
attribute). The first contains the site name, the second the object type. I'd 
like to set the template attribute to the proper class:

import Templates

self.site_name = 'SiteA'
self.template_type = 'Page'

self.template = ???

self.template should refer to Templates.SiteA.Page in this case (where SiteA is 
a module of package Templates, and Page is a class within that module). Danny 
already said that classes can be treated just like any other object - but how 
do I get from a string to a class or module name?

Thanks for all your help, and sorry for my ignorance,

Jan
-- 
Any sufficiently advanced technology is indistinguishable from a Perl script. - 
Programming Perl
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Class attributes not overriding parameters

2005-11-05 Thread Jan Eden
Hi,

I use the following construction to make sure the data attribute site_id is set 
only once for each object:

def GetSiteID(self):
return self._site_id

def SetSiteID(self, value):
if not (hasattr(self, '_site_id') and self._site_id): self._site_id = value

site_id = property(GetSiteID, SetSiteID)

site_id is supposed to be set either through a parameter, derived from the 
server name (the default case) or via a class attribute:

class SiteList(Lists):
site_id = 1

The latter case does not work: the site_id is still derived from the server 
name for objects of class SiteList. Why is that? How can I make Python check 
the superclasses for a class attribute before applying the SiteMode() method?

Thanks,

Jan
-- 
How many Microsoft engineers does it take to screw in a lightbulb? None. They 
just redefine dark as the new standard.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Subclassing data attributes

2005-11-03 Thread Jan Eden
Hi,

the module Data.py stores a number of data attributes. I'd like to structure 
the storage of these attributes, either in subclasses or in dictionaries.

My first attempt was this:

class A:
templates['attr1'] = 'string'
queries['children'] = ...

class B(A):
templates['attr2'] = 4
queries['children'] = ...

class C(B):
templates['attr3'] = 939.121
queries['populate'] = ...

Python obviously complains about unknown names 'templates' and 'queries'.

So I thought about realizing this with classes:

class A:
class Templates:
attr1 = 'string'

 ...
 
The problem here is that once an object uses class C.Templates to lookup attr3, 
it will not consult class A.Templates for attr1.

How can I avoid a complete inheritance mess and structure all my data 
attributes at the same time?

Thanks,

Jan
-- 
I'd never join any club that would have the likes of me as a member. - Groucho 
Marx
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newbie Question - Python vs Perl

2005-10-31 Thread Jan Eden
Hi Scott,

Scott Clausen wrote on 30.10.2005:

As a newbie to Python I'd like to know if someone can tell me some
strengths and weaknesses of this language. The reason I'm asking is
a friend told me I should learn Perl over Python as it's more
prevalent.  I'm going to be using it on a Mac.

I'd appreciate hearing any views on this topic. My own view is that
it's always good to learn new things as you then have more tools to
use in your daily programming.

I started learning Python approx. 4 months ago. I had been using Perl for about 
4 years at that time. (BTW, I work on a Mac, too)

The motivation for trying Python came when a certain project needed an OOP 
overhaul. While I was able to code an OOP version of the program, the result 
was rather slow and ugly. This was only partly because of my own deficiencies - 
Perl does not really invite you to produce clean code on larger projects (IMHO).

When I re-coded the very same project in Python, I achieved a much better 
(faster, more readable) result within weeks.

Most comparisons of Perl and Python also highlight Python's cleaner syntax, I 
can second that (although I got used to Perl's @$% syntax after a while).

Cheers,

Jan
-- 
Common sense is what tells you that the world is flat.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Transforming object into subclass instance

2005-10-30 Thread Jan Eden
Hi,

my program uses an initial switch statement to create an object:

valid_types = dict(
pages=Show.Page,
syndicated=Show.Syndicated,
authors=Show.Author,
author_list=Show.AuthorList,
galleries=Show.Gallery,
pictures=Show.Picture,
slideshow=Show.SlidePicture,
tex=Show.Tex,
blogs=Show.Blog,
blogentries=Show.BlogEntry,
search=Show.Search,
search_author=Show.SearchAuthor,
not_found=Show.NotFound
)
# ... code ommitted...

page = valid_types[type]]()

For a certain class, it is only during the execution of the __ini__ method that 
I can distinguish between two subtypes (subclasses). The subclasses define two 
different versions of method A.

Now my question is: How can I turn an object of class X into an object of 
either class Y or Z while (retaining all the attributes defined so far).

I know I could solve the problem by using another switch statement - but is 
there consistent OOP solution for this problem?

Thanks,

Jan
-- 
Hanlon's Razor: Never attribute to malice that which can be adequately 
explained by stupidity.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] New-style classes

2005-09-29 Thread Jan Eden
Hi,

after updating a program to use new-style classes, I am a bit confused. My 
setup looks like this (simplified):

#Show.py

import Data

class Base(object):
...

class Page(Data.Page, Base):
...

class Author(Data.Author, Base):
...

#Data.py

class Base:
...

class Page(Base):
...

class Author(Base):
...

The module Show.py provides methods, Data.py provides data attributes. I use 
the property method in Data.Base for a certain attribute - but why does this 
work?

Data.Base has no base classes, so it is not based on a built-in type: How can 
it be a new-style class?

Thanks for any hints,

Jan
-- 
There are 10 kinds of people:  those who understand binary, and those who don't
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] New-style classes

2005-09-29 Thread Jan Eden
Hi Kent,

Kent Johnson wrote on 29.09.2005:

Data.Base has no base classes, so it is not based on a built-in
type: How can it be a new-style class?

Data.Base is not a new-style class, but the classes in Show are. And
properties may appear to work in old-style classes. This document
http://www.python.org/2.2.3/descrintro.html#property says,
Properties do not work for classic classes, but you don't get a
clear error when you try this. Your get method will be called, so it
appears to work, but upon attribute assignment, a classic class
instance will simply set the value in its __dict__ without calling
the property's set method, and after that, the property's get method
won't be called either.

Thanks for your quick reply. I read the document you mentioned before, that's 
why I was confused.

My actual code looks like this:

class Base:
def GetOwnType(self):
try: return self._own_type
except: return self.child_type

def SetOwnType(self, value):
self._own_type = value

own_type = property(GetOwnType, SetOwnType)

For some of the subclasses of Base, the attribute own_type is defined, the 
others should use child_type.

For both groups of subclasses, this works fine - if own_type has not been set 
somewhere else, self.child_type is returned when calling self.own_type.

When checking Data.Base.__mro__, I get an error, so it is not a new-style class 
by itself.

On the other hand, every time I use the own_type attribute, I do so via 
instances of new-style classes (Show.Page, Show.Author etc).

Could it be that the nature of these classes makes the code in Data.Base behave 
according to the new-style rules?

Thanks,

Jan
-- 
I'd never join any club that would have the likes of me as a member. - Groucho 
Marx
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Simulating case statement

2005-09-27 Thread Jan Eden
Hi,

I used to use an extended if...elif sequence to instantiate an object and call 
this object's display method afterwards:

if safe['type'] == pages:
page = Show.Page(id=safe['id'], start=safe['start'] ...),
elif safe['type'] == pages:
author = Show.Author(id=safe['id']...)
 ...

page.Display()
 

To improve readability, I changed this code to use a dictionary:


valid_types = dict(
pages=Show.Page,
authors=Show.Author,
...
)

page = valid_types[safe_parameters['type']](safe_parameters)
page.Display()


The problem is that the __init__ methods of the respective classes take a 
different number of parameters - this is why I pass the whole safe_parameters 
dictionary.

This has a number of drawbacks when instantiating an object in other situations 
because I cannot use a default for some parameters while passing some others.

So I'd like to do pass the parameters individually, based on the class. I know 
I would need to expand the valid_types dictionary to include the parameters - 
but how can I pass these one by one?

What I came up with is a monster (which does not work anyway):

valid_types = dict(
pages=dict(klasse=Show.Page, parameters=dict(id=safe['id'], 
start=safe['start'] ...))
authors=dict(klasse=Show.Author, ...)
...
)

page = valid_types[safe_parameters['type']]['klasse'](valid_types['parameters'])

page.Display()

How can I circumvent the if...elif sequence and have the parameters passed 
individually at the same time?

Thanks for any suggestions,

Jan
-- 
Common sense is what tells you that the world is flat.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simulating case statement

2005-09-27 Thread Jan Eden
Kent Johnson wrote on 27.09.2005:

Jan Eden wrote:

The problem is that the __init__ methods of the respective classes
take a different number of parameters - this is why I pass the
whole safe_parameters dictionary.

I think if you pass the dictionary as keyword arguments rather than
as a single dict you will get what you want.

page =
valid_types[safe_parameters['type']](**safe_parameters)

This syntax means, use safe_parameters to populate the keyword
arguments of the function. Any parameters which are not in
safe_parameters will be set to their default values, and in other
calls you can set the parameters as you like. Here is a simple
example:

I see. I did not know that I can use a formal parameter **param in calls - 
thought I could only do so in function definitions:

def func(**param):
...

 func(id=1, stuff='blah')
 
 Thanks for that!
 
 Jan
-- 
Mac OS X. Because making Unix user-friendly is easier than debugging Windows.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] __getattr__ causes TypeError

2005-09-25 Thread Jan Eden
Hi,

I experienced a strange side effect using a custom __getattr__ method.

For a certain attribute, I'd like to return the value of another attribute if 
the former is not present. So I wrote:

def __getattr__(self, attrname):
if attrname == 'own_type': return self.child_type
else: AttributeError, attrname

But if I include this in my base class, I get a TypeError somewhere else:

  File /Users/jan/Sites/janeden/cgi-bin/Pythonsite/Show.py, line 24, in 
Populate
   self.page_head = re.sub('%%author%%', self.first_name+' '+self.last_name, 
self.page_head)
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

How can this possibly be related? I am clueless.

Best,

Jan
-- 
If all else fails read the instructions. - Donald Knuth
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Using superclass __init__ method

2005-09-22 Thread Jan Eden
Hi,

I just noticed that in the following environment:

class Base:
def __init__(self):
...

class Child(Base):
pass

the following statement:

child = Child()

would automatically execute the superclass __init__ method. This is exactly 
what I was looking for - but in the Cookbook, I found several suggestions on 
how to actively force the invocation of the superclass __init__.

Is this behvaiour documented?

Thanks,

Jan
-- 
There are 10 kinds of people:  those who understand binary, and those who don't
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using superclass __init__ method

2005-09-22 Thread Jan Eden
Kent Johnson wrote on 22.09.2005:

This is standard behavior for any class attribute - if it's not
defined in the derived class, the base class is checked. It's not
special for __init__.

I can't find a comprehensive reference for the way attribute lookup
works - anyone else?

Well, I did know that any attribute used explicitly with a class instance is 
looked up in the class, then the base class etc:

class Base:
variable = 1

class Child(Base):
pass

child = Child()
print child.variable
1

What I did not know was that the __init__ method behaves the same way - i.e. 
that Python looks for __init__ upon instantiation until it finds one.

Thanks,

Jan
-- 
A good programmer is someone who looks both ways before crossing a one-way 
street. - Doug Linder
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using superclass __init__ method

2005-09-22 Thread Jan Eden
Hi,

paul brian wrote on 22.09.2005:


class Base:
   def __init__(self):
   print hello

class Child(Base):
   def __init__(self):
   Base.__init__(self)


This is how I did it so far. But in my program, I have 10 subclasses with 
identical __init__ methods, so I can simplify the setup a lot.

Thanks for your help,

Jan
-- 
Alcohol and calculus don't mix - PLEASE don't drink and derive.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] List of class instances

2005-09-20 Thread Jan Eden
Hi,

I'd like to form a list of class instances. The following does not work 
(TextfieldLong, Textarea, TextfieldShort etc being class names):

fields = [
TextfieldLong(name='title', label='Seitentitel', value=''),
Textarea(name='content', label='Inhalt', value=''),
ShortField(name='mother_id', label='MotherID', value=1)
]

Is there a way to create such a list?

Thanks in advance,

Jan
-- 
Any sufficiently advanced technology is indistinguishable from a Perl script. - 
Programming Perl
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List of class instances

2005-09-20 Thread Jan Eden
Hi,

Jan Eden wrote on 20.09.2005:

Hi,

I'd like to form a list of class instances. The following does not work 
(TextfieldLong, Textarea, TextfieldShort etc being class names):

fields = [
TextfieldLong(name='title', label='Seitentitel', value=''),
Textarea(name='content', label='Inhalt', value=''),
ShortField(name='mother_id', label='MotherID', value=1)
]


Just found that it *does* work, but that I have to define the classes above the 
list assignment. Why is that? Why would Python not find the classes within the 
same file?

TIA,

Jan
-- 
Life's unfair - but root password helps!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List of class instances

2005-09-20 Thread Jan Eden
Hi,

Orri Ganel wrote on 20.09.2005:

As a side-note, unless you're okay with only being able to access
those instance variables through the fields list (ie fields[0],
fields[1], fields[2]), you may want to actually name them first.

Yes, I am fine with that - I actually prefer to have a sorted list instead of a 
dictionary. I'll always access them like

for field in fields:
...

Thanks,

Jan
-- 
I'd never join any club that would have the likes of me as a member. - Groucho 
Marx
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] mod_python on OS X

2005-09-05 Thread Jan Eden
Hi Danny,

Danny Yoo wrote on 05.09.2005:


On Mon, 5 Sep 2005, Jan Eden wrote:

[Sat Sep 03 23:01:52 2005] [notice] child pid 2334 exit signal Bus
error (10) [Sat Sep 03 23:01:53 2005] [notice] child pid 2333 exit
signal Bus error (10)

It looks that you have a locally customized verison of Python on
your system.  (As far as I know, Apple doesn't package Python 2.4
yet)  Did you make sure to install mod_python by using that
customized Python, rather than the system default?

I did.

The folks on the mod_python mailing list will probably know more
about this, so I'd strongly recommend asking them:

Yes, it is probably the best thing to do, but I wanted to avoid getting 
involved with yet another mailing list. *sigh*

Many thanks,

Jan
-- 
Unix is user friendly - it's just picky about it's friends.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PYTHON????

2005-09-01 Thread Jan Eden
[EMAIL PROTECTED] wrote on 29.08.2005:

Dear Python,
 How does a calculator multiply? I want to create a computer software that can 
multiply. How do I program the computer to multiply? 

Could this be a spammer aiming at mailing lists?

- Jan
-- 
The day Microsoft makes something that doesn't suck is the day they start 
selling vacuum cleaners.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Instance attribute as a parameter's default value

2005-08-26 Thread Jan Eden
Hi,

Jan Eden wrote on 26.08.2005:

Hi,

I need to use an instance attribute as the default value for a parameter to a 
method.

This obviously won't work:

page.Children()

def Children(self, id=self.id, level=2):

How can I get the id parameter to use the attribute page.id? I know I could 
simply use the method call

page.Children(id=page.id)

but I thought it is much more elegant to use a default value here.

Is it possible?

Addition: I do use

def Children(self, id=0, level=2):
if not id: id = self.id

right now. But still - there has to be a smarter way.

Thanks,

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


Re: [Tutor] Default class in module

2005-08-12 Thread Jan Eden
Hi Kent,

Kent Johnson wrote on 11.08.2005:

I don't know of any way to do exactly what you ask. However you can
use the __init__.py module of the package to promote classes to
package level visibility.


Nice - that's a good start.

Thank you,

Jan
-- 
Common sense is what tells you that the world is flat.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Untainting CGI parameters

2005-08-11 Thread Jan Eden
Hi Kent, hi Alan,

Kent Johnson wrote on 10.08.2005:

OK, I don't know much Perl but I don't think these two snippets do
the same thing. For one thing the regexes are different, second in
the Python you need to check if the match succeeds.

my $type = ($parameters{type}  ($parameters{type} =~ /^(\w+)$/)) ?
$1 : 'page';


Ok, you got me - the regexes were indeed not identical, and only the Perl code 
included a check if the match was successful.

Alan G wrote on 10.08.2005:

I would like to untaint all parameters with which my CGI script is
called. Example:

Can you explain 'untaint'??? Not a term I'm familiar with...

Untainting CGI parameters is derived from Perl's taint mode - turning on this 
mode makes Perl assume that all input coming from the user of a script is 
probably evil and needs to be hand-checked before using it for anything outside 
the script itself (e.g. calling external programs, removing files, sending mail 
etc.)

if parameters.has_key('type'): match = re.search('\w+',
parameters['type'].value) type = match.group() else: type = 'page'

I Python it's better to ask forgiveness than permission so...

try: type = re.search('\w+', parameters['type'].value).group() except
KeyError: type = 'page'

Thank you - that wraps up two lines in one, just as I intended to. I tried it 
before but most have mixed up something when calling the group() method on the 
object returned by the search method immediately.

I will combine Kent's and your suggestion, because he included a check for an 
AttributeError:

try:
type = re.search('\w+', parameters['type'].value).group() except
except KeyError, AttributeError:
type = 'page'

Thank you both,

Jan
-- 
Remember: use logout to logout.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Untainting CGI parameters

2005-08-11 Thread Jan Eden
Hi Alan,

Alan G wrote on 11.08.2005:

 I will combine Kent's and your suggestion, because he included a 
 check for an AttributeError:


OK, as a slightly more perl-ish solution to the no Attribute problem
you could also do this:

try:
type = re.search('\w+', parameters['type'].value).group() or 
'page'
except KeyError:
type = 'page'

Are you sure?

 a = 'abcd'
 import re
 type = re.search('\d+',a).group() or 'page'
Traceback (most recent call last):
  File stdin, line 1, in ?
AttributeError: 'NoneType' object has no attribute 'group'

If the search does not succeed, the returned object has the value None, which 
has no attribute group.

Thanks,

Jan
-- 
There are two major products that come out of Berkeley: LSD and UNIX. We don't 
believe this to be a coincidence. - Jeremy S. Anderson
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Untainting CGI parameters

2005-08-10 Thread Jan Eden
Hi,

I would like to untaint all parameters with which my CGI script is called. 
Example:

if parameters.has_key('type'):
match = re.search('\w+', parameters['type'].value)
type = match.group()
else: type = 'page'

In Perl, I used the ternary operator to write it like this:

my $type = ($parameters{type}  ($parameters{type} =~ /^(\w+)$/)) ? $1 : 
'page';

While this is not the most beautiful code to look at, I have a weakness for 
compact programs - so can I shorten the Python equivalent somehow?

Thanks,

Jan
-- 
A good programmer is someone who looks both ways before crossing a one-way 
street. - Doug Linder
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fetching dictionaries using MySQLdb

2005-08-08 Thread Jan Eden
Hi,

in Perl's DBI, I used fetchrow_hashref() to receive a database row as a 
dictionary, with the field names being the dictionary keys.

MySQLdb's fetchone() returns a tuple Unfortunately, I have a dictionary of SQL 
queries which return rows of different lengths (read: with a varying number of 
fields).

The documentation for MySQLdb says that fetchoneDict() is deprecated and the 
usage of fetchone() is suggested.

Is there a recommended way to receive the results of an SQL query in the form I 
need? Or do I have to create a dictionary of fieldname tuples which can be 
zipped with the query result tuple?

Thanks,

Jan
-- 
Any sufficiently advanced technology is indistinguishable from a Perl script. - 
Programming Perl
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fetching dictionaries using MySQLdb

2005-08-08 Thread Jan Eden
Kent Johnson wrote on 08.08.2005:

Jan Eden wrote:

The documentation for MySQLdb says that fetchoneDict() is
deprecated and the usage of fetchone() is suggested.

You could just use fetchoneDict(); deprecated isn't the same as
gone...

I tend to avoid deprecated functions/methods - I would need another method 
sooner or later anyway.

Is there a recommended way to receive the results of an SQL query
in the form I need? Or do I have to create a dictionary of
fieldname tuples which can be zipped with the query result tuple?

You can create a list of field names from the cursor.description
attribute. But if the number of fields in the result varies how do
you know which field goes with which description?

That works, thank you. I will use the cursor.description attribute immediately 
after executing a query, so it will contain the correct field descriptions 
whenever I need them. The rest of my program uses the type attribute to decide 
which fields are present and which are not.

All this is part of a port from Perl to Python - I will publish a log of 
everything I encountered in a couple of weeks.

Cheers,

Jan
-- 
There's no place like ~/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fetching dictionaries using MySQLdb

2005-08-08 Thread Jan Eden
Hi Danny,

Danny Yoo wrote on 08.08.2005:

On Mon, 8 Aug 2005, Jan Eden wrote:

Is there a recommended way to receive the results of an SQL query
in the form I need? Or do I have to create a dictionary of
fieldname tuples which can be zipped with the query result tuple?


Hi Jan,

MySQLdb supports the concept of customized cursor types.  They have
a particular cursor class that returns dictionary objects:

Great! I found the pydoc for MySQLdb a bit confusing and would probably have 
taken quite a while to figure that out - thanks a lot.

- Jan
--  
Any technology which is distinguishable from magic is insufficiently advanced.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Class instantiation parameters

2005-08-07 Thread Jan Eden
Hi,

after using Perl for some years for simple scripting tasks, one of my programs 
reached a size where an OO design is appropriate. So I rewrote the program 
using OO techniques in Perl. Because I am not entirely satisfied with the 
implementation, I decided port the program to Python.

The first thing I'd like to sort out are the parameters on class invocation. In 
Perl, I did (... for lines left out):

my $page = Show-new(type = $type, id = $id);

package Show;
...
sub new {
my $class = shift;
my $self = { @_ };
...
bless $self, $class;
return $self;
}

making use of the relatively liquid border between hashes (dictionaries) and 
arrays (lists).

In Python, I would do:

page = Show(type=type, id=id)

class Show:
def __init__(self, type, id):
self.id = id
self.type = type
...
return self

For two parameters, this is relatively simple. But if I have for example 10 
parameters on instantiation, assigning each value the the class object manually 
will be really clumsy.

So how can I add the values of all the paramaters to my class instance in one 
step?

Thanks in advance,

Jan
-- 
Imagine if every Thursday your shoes exploded if you tied them the usual way. 
This happens to us all the time with computers, and nobody thinks of 
complaining. - Jeff Raskin
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Class instantiation parameters

2005-08-07 Thread Jan Eden
Hi,

Jan Eden wrote on 07.08.2005:

So how can I add the values of all the paramaters to my class
instance in one step?

apologies for replying to my own post: I just discovered the **args formal 
parameter.

Thanks,

Jan
-- 
I was gratified to be able to answer promptly, and I did. I said I didn't know. 
- Mark Twain
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Class instantiation parameters

2005-08-07 Thread Jan Eden
Hi Kent,

Kent Johnson wrote on 07.08.2005:

So how can I add the values of all the paramaters to my class
instance in one step?

There was recently a long discussion of this on comp.lang.python.
http://groups.google.com/group/comp.lang.python/browse_frm/thread/
7346ad00a14e821a/9dc993d295475cac?q=locals()rnum=15hl=en#
9dc993d295475cac

Thanks for this. I thought I could do it with the help of **args, but maybe I 
still think too much in Perl terms. It's a bit unexpected that this task asks 
for such an indirect approach.

In Perl, where my class instances are usually nothing but (blessed) hash 
references, a more verbose version of my actual method would read:

package NewClass;
...
sub new {
my $self = shift;
my $parameters = { @_ };
for (keys %$parameters) { $self-{$_} = $parameters-{$_};
}

My idea was to transfer the same technique to Python like this:

class NewClass:
def __init__(self, **parameters):
for i in parameters.keys(): self.i = parameters[i]

But the assignment in the for loop obviously does not work with instance 
attributes. I will have to read up some more about instance attributes.

Thanks again,

Jan
-- 
Bad spellers of the world Untie!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Class instantiation parameters

2005-08-07 Thread Jan Eden
Jan Eden wrote on 07.08.2005:

But the assignment in the for loop obviously does not work with
instance attributes. I will have to read up some more about instance
attributes.

Ok... so this works:

class NewClass:
def __init__(self, **parameters):
self.data = {}
for i in parameters.keys(): self.data[i] = parameters[i]

self = NewClass(arg1='Value', arg2='Another value', arg3='Yet another value')
print self.data

It seems that I need to add a dictionary as a data attribute to my instance 
object to do what I wanted to.

This is unfortunate, because it complicates my syntax: Instead of self.type, I 
need to use self.data['type'].

- Jan
-- 
I'd never join any club that would have the likes of me as a member. - Groucho 
Marx
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Class instantiation parameters

2005-08-07 Thread Jan Eden
Hi Kent, hi Alan,

Alan G wrote on 07.08.2005:

 page = Show(type=type, id=id)

 class Show:
 def __init__(self, type, id):
 self.id = id
 ...
return self

First a couple of comments.
You don't need to return self from __init__.
You can only instantiate Show *after* you've defined it.

Right - I still think along the lines of Perl subroutines used as methods.

**args is indeed the solution to this so you may have 
figured it all out already, but your terminology is
slightly confusing (because while it is strictly valid 
in what it says, but so unlikely in its meaning, that 
I suspect you are getting some of your terms mixed up?)

The idea is to pass keyword arguments to an instantiation function and 
automatically create instance attributes for each keyword argument. My 
apologies if I still mix up some well-defined terms in Python.

Kent Johnson wrote on 07.08.2005:

for i in parameters.keys(): setattr(self, i, parameters[i])

or for k, v in parameters.items(): setattr(self, k, v)

The problem with this approach is that the function can be called
with any number of arguments - you lose the limited type safety you
get from declaring the arguments in the def - and it only works with
keyword arguments, not positional arguments.

Thanks! The setattr function is exactly what I was looking for. I should not 
need to worry about type safety, because the instance is instantiated from 
within a script after making sure that id is an integer and type is a string 
from a predefined set of strings.

Now I'll see if I understand the practical difference between items() and 
iteritems() - the Python tutorial uses iteritems() in such a context.

If you really just want a dictionary, maybe you should just use one?
If you want the syntactic sugar of attribute access instead of
dictionary lookup you could make a dict subclass that supports that.

I do not really want a dictionary - I just want to pass some named parameters 
and turn them into attributes. But I will check out the recipes anyway.

This is a really friendly and helpful list. Thanks again for all your help.

- Jan
-- 
Mac OS X. Because making Unix user-friendly is easier than debugging Windows.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor