Re: [Tutor] [OT] Python Study Group

2010-01-29 Thread Serdar Tumgoren
Sounds like a cool idea David. Is this an online study group or do the folks who signed up live near each other geographically as well? On Fri, Jan 29, 2010 at 3:15 PM, David Abbott wrote: > A group of beginners and intermediate Pythonerrs and getting together to > study the book Core Python Pr

[Tutor] correcting an Active State Recipe for conversion to ordinal

2010-02-04 Thread Serdar Tumgoren
Hi folks, A few months back I posted my first (and only) "recipe" to ActiveState. It was just a little function to convert an integer or its string representation to an ordinal value: 1 to 1st, 2 to 2nd, etc. Not sure if this really qualifies as a recipe, per se, but it was a handy little functio

Re: [Tutor] correcting an Active State Recipe for conversion to ordinal

2010-02-04 Thread Serdar Tumgoren
> No time to search for the issue, but here are some trials (hole from 10 --> > 19): > for i in range(21): >        print "%s\t: %s" %(i,ordinal(i)) > for i in (-1,22,33,99,100,101,199,200,999,1000): >        print "%s\t: %s" %(i,ordinal(i)) > ==> > 0       : 0th > 1       : 1st > 2       : 2nd >

Re: [Tutor] correcting an Active State Recipe for conversion to ordinal

2010-02-04 Thread Serdar Tumgoren
> Perhaps the code on activestate is not a correct copy of what you are > running? The conditional at line 23 extends all the way to line 35 - > the end of the function - so if value % 100/10 == 1 no more code is > executed and None is returned. > Here is the code that I'm running locally (hopeful

Re: [Tutor] correcting an Active State Recipe for conversion to ordinal

2010-02-04 Thread Serdar Tumgoren
On Thu, Feb 4, 2010 at 1:21 PM, Serdar Tumgoren wrote: >> Perhaps the code on activestate is not a correct copy of what you are >> running? The conditional at line 23 extends all the way to line 35 - >> the end of the function - so if value % 100/10 == 1 no more code is >&

Re: [Tutor] correcting an Active State Recipe for conversion to ordinal

2010-02-04 Thread Serdar Tumgoren
> It now works ok but.. > > You should not use ord as variable as ord() is used by python already. > > Also this will fail in python 3 and 2 with import from future, it does > division differently. from __future__ import division 11 % 100 / 10 > 1.1001 > > So "if value % 100/1

Re: [Tutor] correcting an Active State Recipe for conversion to ordinal

2010-02-04 Thread Serdar Tumgoren
> If you want value % 100/10 to give the same result in Python 2.6 and > Python 3 you can use value % 100//10 which will always use integer > division. > Kent, thanks for anticipating this. I actually was struggling to figure out how to update the division and wasn't certain how. Below is the ful

Re: [Tutor] Tutor list as pair progamming plush toy

2010-02-12 Thread Serdar Tumgoren
In similar vein, I find that a concept suddenly makes more sense to me when I try to explain it to someone else (or I realize that I don't fully understand and need to do some more research). But with regard to the plush toy you mention, I just ran into that anecdote in Coders at Work. Can't recal

Re: [Tutor] Editing html using python

2010-02-15 Thread Serdar Tumgoren
In the few cases I had where BeautifulSoup couldn't handle poorly formed HTML, I've found that html5lib was able to get the job done. And of course, lxml is great too, but has a bit more overhead installation-wis. ___ Tutor maillist - Tutor@python.org T

Re: [Tutor] Where to find the article for comparing different Python Development Environment

2010-02-16 Thread Serdar Tumgoren
> Where to find the article for comparing different Python Development > Environment > > The Python wiki is a good place to start: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments ___ Tutor maillist - Tutor@python.org To unsubscribe or cha

[Tutor] Python-based address standardization script?

2010-02-24 Thread Serdar Tumgoren
Hey folks, Anyone know if there's a Python script floating out there to standardize U.S. addresses? I couldn't find anything on ActiveState or by Googling...I'm interested in something similar to this Perl module: http://search.cpan.org/~sderle/Geo-StreetAddress-US-0.99/US.pm Just curious if anyo

Re: [Tutor] Python-based address standardization script?

2010-02-24 Thread Serdar Tumgoren
> Hey folks, >> Anyone know if there's a Python script floating out there to standardize >> U.S. addresses? I couldn't find anything on ActiveState or by Googling...I'm >> interested in something similar to this Perl module: >> >> http://search.cpan.org/~sderle/Geo-StreetAddress-US-0.99/US.pm

Re: [Tutor] Python-based address standardization script?

2010-02-24 Thread Serdar Tumgoren
> Sure, just send me a link when it's up. I don't have any experience with > git but I've wanted to learn so go ahead and use that. > > Okay - the git repo is here: http://github.com/zstumgoren/python-addressparser You can clone it with the following shell command (assuming you've installed git):

[Tutor] Collaborative Comp Sci education using Python

2010-03-05 Thread Serdar Tumgoren
Hey everyone, A while back some folks said they were organizing an online study group to work through Wesley Chun's Core Python. I just stumbled into another online study group that might also be of interest: http://www.crunchcourse.com/class/mit-opencourseware-600-introduction/2010/jan/ The stud

Re: [Tutor] split a 5 chars word into 4 and 1

2010-03-09 Thread Serdar Tumgoren
> Hello, > > I'm trying to split 5 chars words (codes) into 2 variables. The first must > contain the first 4 characters. The second variable will only contain the > last character. I'm working in a loop pre-generated codes. > > Any magic command for this ? :-) > > Examples of codes : > 3cmvA > 3cm

Re: [Tutor] How do I find information about a Python object.

2010-03-30 Thread Serdar Tumgoren
You might want to check out the below chapter from Dive Into Python: http://diveintopython.org/power_of_introspection/index.html ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinf

Re: [Tutor] Django Book Recommendation

2010-04-07 Thread Serdar Tumgoren
There is lots of good information in the second edition of the official Django Book (though it appears it's only a partially complete Web preview): http://www.djangobook.com/en/2.0/ The Django google group is a great way to research specific questions and get help: http://groups.google.com/g

[Tutor] accessing Postgres db results by column name

2010-04-09 Thread Serdar Tumgoren
Hi folks, Does anyone know if there's native support in psycopg2 for accessing rows in a result-set by column name (rather than by index)? I'd like to be able to do something like below: cur.execute('select id, name from mytable') data = cur.fetchall() for row in data: print row['id'], row['

Re: [Tutor] accessing Postgres db results by column name

2010-04-09 Thread Serdar Tumgoren
> >>> class reg(object): > ... def __init__(self, cursor, registro): > ... for (attr, val) in zip((d[0] for d in cursor.description), > registro) : > ... setattr(self, attr, val) > > >>> for row in cursor.fetchall() : > ... r = reg(cursor, row) > ... print r.CosCPrd,

Re: [Tutor] accessing Postgres db results by column name

2010-04-09 Thread Serdar Tumgoren
Hey everyone, Ricardo was nice enough to post his solution as a recipe on ActiveState. For anyone interested in bookmarking it, here's the link: http://code.activestate.com/recipes/577186-accessing-cursors-by-field-name/ Serdar ___ Tutor maillist - T

Re: [Tutor] accessing Postgres db results by column name

2010-04-10 Thread Serdar Tumgoren
> I really like Ricardo's solution ... attribute access is a nice touch, > bookmarking it now. > > FWIW, it would seem that psycopg2 also has a DictCursor (and > DictConnection). > > http://initd.org/psycopg/docs/extras.html > > > Ah, yes, there it is. Thank you. This list rocks! __

Re: [Tutor] Move all files to top-level directory

2010-04-12 Thread Serdar Tumgoren
What fine manual should I be reading? I am not asking for > code, rather just a link to the right documentation. > You'll definitely want to explore the os module, part of Python's built-in standard library. http://docs.python.org/library/os.html http://docs.python.org/library/os.html#files-and

Re: [Tutor] accessing Postgres db results by column name

2010-04-12 Thread Serdar Tumgoren
Hey folks, Wanted to send along one more update about this topic. Steve Orr pointed out in a comment on Ricardo's new recipe that there's yet another way to get named attribute access to cursor results. The secret sauce is namedtuple, "high performance" collection type. This appears to be the "c

Re: [Tutor] accessing Postgres db results by column name

2010-04-12 Thread Serdar Tumgoren
> Wanted to send along one more update about this topic. Steve Orr pointed > out in a comment on Ricardo's new recipe that there's yet another way to get > named attribute access to cursor results. > I should add the disclaimer that namedtuple is only available in Python 2.6+ _

Re: [Tutor] Problem iterating over csv.DictReader

2010-04-26 Thread Serdar Tumgoren
> I have noticed this odd behaviour in the CSV DictReader Class, and at a > loss to understand/ get around it. > > The aim is to read in a CSV file, and then iterate over the lines. The > problem (seems) to be that once you have iterated over it once, you can't do > it again. > > This is expected b

Re: [Tutor] what is wrong with this code?

2010-04-26 Thread Serdar Tumgoren
> user_tables = ['notification', 'userNotification', 'product_comments', > 'product_donation_paypalTransaction', 'product_donation', > 'productList_recommended', 'productList_user_assoc', > 'profile_values'] > > drop_user_tables = """DROP TABLE IF EXISTS db2.%s""" > > try: >cursor.execute(drop_

[Tutor] Unit testing command-line options from argparse or optparse

2010-05-18 Thread Serdar Tumgoren
Hello all, Does anyone have advice for writing unit tests against variables set by command-line options? I have a program I'd like to run in either "debug" or "live" mode, with various settings associated with each. Below is some pseudo-code that shows what I'd like to do: <> mode = p.parse_args

Re: [Tutor] Unit testing command-line options from argparse or optparse

2010-05-19 Thread Serdar Tumgoren
Ah, okay -- both of those options make sense. I'll try my hand at Jan's first and will report back if I have any problems. Many thanks as always! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.or

Re: [Tutor] Django Read

2010-07-08 Thread Serdar Tumgoren
Python Web Development With Django has a good primer on Python (in general and as it relates Django), along with a nice sampling of projects (creating a basic CMS, using Ajax in an application, creating a Pastebin site). You can learn about Django best practices and get a taste for some related to

Re: [Tutor] I don't understand this code

2010-07-14 Thread Serdar Tumgoren
The rest of the list does a great job explaining the situation, which bears out in the code itself. If you look farther down in the code sample in Chapter 9, you'll see the function called twice. http://inventwithpython.com/chapter9/ << snipped >> print('H A N G M A N') missedLetters = '' correct

Re: [Tutor] Global name not found, though clearly in use

2010-07-14 Thread Serdar Tumgoren
> Hmm..If I add a few debugging lines like that into my code, I get this: >> > > The point was that statements in a class at class level (ie, not in defs) > are executed sequentially and expect referenced variables to exist (ie, > defined somewhere 'above' the current statement) -- there is no for

Re: [Tutor] Global name not found, though clearly in use

2010-07-14 Thread Serdar Tumgoren
> > >> > I also found this interesting (but possibly not to newbies :) : > http://www.shinetech.com/attachments/108_python-language-internals.pdf > > Very helpful, especially that last resource. Thank you! Serdar ___ Tutor maillist - Tutor@python.org

[Tutor] is it possible to call a setter property during class instantiation?

2010-08-12 Thread Serdar Tumgoren
Hey all, Does anyone know if it's possible to call a property setter inside of a class's init method? Below is a code sample of what I'm trying to do. class Question(object); def __init__(self, value): self.text(value) @property def text(self): return self._text

Re: [Tutor] is it possible to call a setter property during class instantiation?

2010-08-12 Thread Serdar Tumgoren
> > def __init__(self, value): > > self.text(value) > > self.text = value # is the way to do this, if you're using it as a > property. > > That worked perfectly! So it seems I was botching the syntax. Many thanks for the quick response!! Serdar

Re: [Tutor] is it possible to call a setter property during classinstantiation?

2010-08-13 Thread Serdar Tumgoren
> > > > I have a class with an init method that is getting bloated with >> error-checking guard clauses. >> > > Thats very strange. We don't usually have to check types in Python, > it is a dynamic language and we can use duck-typing and exceptions > so we don't usually care too much about types.

Re: [Tutor] Help with Object Oriented Programming

2010-08-30 Thread Serdar Tumgoren
I haven't read it yet myself, but the below book just came out: http://www.amazon.com/Python-3-Object-Oriented-Programming/dp/1849511268/ref=cm_cr_pr_sims_t I'm not aware of any other book that focuses exclusively on OO in Python, though you'll find good intros to the topic in a number of the "cl

Re: [Tutor] Newbie - regex question

2010-08-30 Thread Serdar Tumgoren
To make a qualifier non-greedy, > simply add an asterix at its end: > > r'WORD1-.*?' > > Hugo explains this nicely, but I just wanted to make one minor correction -- the non-greedy qualifier is the question mark AFTER an the asterisk (which is what Hugo's code shows but I believe he accidentally

[Tutor] A deeper explanation of ability to modify list elements in-place

2010-11-11 Thread Serdar Tumgoren
Hi folks, I'm trying to gain a deeper understanding of why it's possible to modify list elements in-place *without* replacing them. For instance, why is the below possible? >>> class Dummy(object): ... pass ... >>> a = Dummy() >>> b = Dummy() >>> x = [a, b] # modify list elements in-place >>>

Re: [Tutor] A deeper explanation of ability to modify list elements in-place

2010-11-11 Thread Serdar Tumgoren
> > > Would you have the same question about what takes place here?: > > >>> list_ = [3,4,5] > >>> list_[1] = 10 > >>> list_ > [3, 10, 5] > >>> > > No surprise there. It's a familiar usage and it appears to be the canonical example (in textbooks/tuts) for demonstrating "in-place" object modificatio

Re: [Tutor] A deeper explanation of ability to modify list elements in-place

2010-11-11 Thread Serdar Tumgoren
First off, thanks for the detailed response! I had a few follow-up questions below, if you're willing to indulge. Feel free to direct me to RTM some books on C and the python source code, of course :) > Why? Because the designer of Python, Guido van Rossum, wanted it to be > possible, and he desi

[Tutor] does id function return location of reference or the referenced object?

2009-03-06 Thread Serdar Tumgoren
Hi all, I've managed to think myself in circles and was hoping someone could help clarify the nature of the "id" function and references in general. I initially got confused while dealing with file objects, so I'll stick with that example. My question, based on the below tests in the ipython int

Re: [Tutor] does id function return location of reference or the referenced object?

2009-03-06 Thread Serdar Tumgoren
So can I ask what happens internally in python when you create open a file object in a loop without assigning that file object to a variable? E.g.: for line in open(file.py): print line In the above, is pythonimplicitly creating a reference to a file object and using that in the for loop? Or

Re: [Tutor] Help Needed

2009-06-15 Thread Serdar Tumgoren
Hi Raj, It might be easier if you create a simple test string inside the python interpreter and then tinker with it there. once you've found the solution, you can graft it onto the broader program that accepts user input. For example, you might create the following variable message = "This

[Tutor] converting encoded symbols from rss feed?

2009-06-17 Thread Serdar Tumgoren
Hi everyone, I just tried my hand at parsing an RSS 2.0 feed using Universal Feed Parser and it worked beautifully. My one point of confusion -- I'm not sure how to convert encoded characters back to their human-readable ascii/unicode. Not sure if it matters, but the feed I'm dealing with is usin

Re: [Tutor] converting encoded symbols from rss feed?

2009-06-17 Thread Serdar Tumgoren
> Upon searching for – in google, I came up with this: > http://www.siber-sonic.com/mac/charsetstuff/Soniccharset.html The character table definitely helps. Thanks. Some additional googling suggests that I need to unescape HTML entities. I'm planning to try the below approach from Frederik Lundh.

Re: [Tutor] converting encoded symbols from rss feed?

2009-06-17 Thread Serdar Tumgoren
Hey everyone, For the moment, I opted to use string replacement as my "solution." So for the below string containing the HTML decimal represenation for en dash: >>>x = "The event takes place June 17 – 19" >>>x.replace('–', '-') 'The event takes place June 17 - 19' It works in my case since this

Re: [Tutor] converting encoded symbols from rss feed?

2009-06-18 Thread Serdar Tumgoren
> Some further searching reveals this: > (yay archives ;)) > http://mail.python.org/pipermail/python-list/2008-April/658644.html > Aha! I noticed that 150 was missing from the ISO encoding table and the source xml is indeed using windows-1252 encoding. That explains why this appears to be the only

Re: [Tutor] converting encoded symbols from rss feed?

2009-06-18 Thread Serdar Tumgoren
Hey everyone, I'm trying to get down to basics with this handy intro on Python encodings: http://eric.themoritzfamily.com/2008/11/21/python-encodings-and-unicode/ But I'm running into some VERY strange results. On the above link, the section on "Encoding Unicode Byte Streams" has the following e

Re: [Tutor] converting encoded symbols from rss feed?

2009-06-18 Thread Serdar Tumgoren
> The example is written assuming the console encoding is utf-8. Yours > seems to be cp437. Try this: > In [1]: import sys > > In [2]: sys.stdout.encoding > Out[2]: 'cp437' That is indeed the result that I get as well. > But there is another problem - \u2013 is an em dash which does not > appea

Re: [Tutor] converting encoded symbols from rss feed?

2009-06-18 Thread Serdar Tumgoren
Ok, I should say that I managed to "solve" the problem by first reading and translating the data, and then applying Mr. Lundh's strip_html function to the resulting lines. For future reference (and of course any additional feedback), the working code is here: http://pastebin.com/f309bf607 But of

Re: [Tutor] converting encoded symbols from rss feed?

2009-06-19 Thread Serdar Tumgoren
> OK, so newline is unicode, outfile.write() wants a plain string. What > encoding do you want outfile to be in? Try something like > outfile.write(newline.encode('utf-8')) > or use the codecs module to create an output that knows how to encode. Aha!! The second of the two options above did the tr

Re: [Tutor] filling in web forms

2009-06-20 Thread Serdar Tumgoren
You might want to read up on Python Mechanize as well: http://wwwsearch.sourceforge.net/mechanize/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor

Re: [Tutor] re module / separator

2009-06-24 Thread Serdar Tumgoren
Hey Tiago, > text = "a2345b. f325. a45453b. a325643b. a435643b. g234324b." > > Of this line of text, I want to take out strings where all words start > with a, end with "b.". But I don't want a list of words. I want that: > > ["a2345b.", "a45453b. a325643b. a435643b."] > Are you saying you want a

Re: [Tutor] re module / separator

2009-06-24 Thread Serdar Tumgoren
apologies -- I just reread your post and appears you also want to capture the dot after each "b" ( "b." ) In that case, you need to update the pattern to match for the dot. But because the dot is itself a metacharacter, you have to escape it with a backslash: In [23]: re.findall(r'a\w+b\.',text)

Re: [Tutor] re module / separator

2009-06-24 Thread Serdar Tumgoren
As usual, Kent Johnson has swooped in an untangled the mess with a clear explanation. By the time a regex gets this complicated, I typically start thinking of ways to simplify or avoid them altogether. Below is the code I came up with. It goes through some gymnastics and can surely stand improvem

Re: [Tutor] re module / separator

2009-06-24 Thread Serdar Tumgoren
Ok -- realized my "solution" incorrectly strips white space from multiword strings: > Out[92]: ['a2345b.', 'a45453b.a325643b.a435643b.'] > So here are some more gymnastics to get the correct result: In [105]: newlist Out[105]: ['a2345b.', '|', 'a45453b.', 'a325643b.', 'a435643b.', '|'] In [109]

[Tutor] browser encoding standards?

2009-07-13 Thread Serdar Tumgoren
Hi everyone, I just ran into a glitch that got me wondering about the proper encoding to use when outputting data for non-technical folks. I took pains to ensure that I converted a number of XML feeds to UTF-8 prior to storage in a database. And then, when pulling the feed data from a database to

Re: [Tutor] browser encoding standards?

2009-07-13 Thread Serdar Tumgoren
> I guess you forgot to output a tag that defines the content-type of > the page. Aha! Yes indeed. I was just writing out data quick and dirty for testing purposes and forgot to write out the headers. I added Content Header info and all works fine. Thanks! __

Re: [Tutor] browser encoding standards?

2009-07-13 Thread Serdar Tumgoren
> That's precisely the solution that worked for me, though I should say that I only tested this in Firefox 3 on Ubuntu 9.04. The below blog post circa 2006 suggests that IE at least uses some behind-the-scenes magic to decide on an encoding when the declaration doe not appear in the Content heade

[Tutor] advice on creating and working with a complex data structure

2009-07-20 Thread Serdar Tumgoren
Hi everyone, I'm working with a database of campaign finance filings, and I'm trying to create a data structure that captures the fact that: - there can be multiple races - races can have multiple candidates - candidates can have multiple campaign committees - campaign committees can file m

Re: [Tutor] advice on creating and working with a complex data structure

2009-07-20 Thread Serdar Tumgoren
> Have you considered using classes? This looks like a fairly natural fit for > race, candidate, committee and maybe report casses Aha, okay, the multiple classes approach makes sense. But would these be nested classes, perhaps inheriting attributes from their parent classes? E.g.: class Race

Re: [Tutor] advice on creating and working with a complex datastructure

2009-07-21 Thread Serdar Tumgoren
>> >> I do not think any of these meet the criteria for inheritance. None of >> them "is a" kind of any of the others. >> I refreshed on my OO terminology and I see your point -- that composition is a more appropriate fit here than inheritance. >> I don;t like the use of Filing for a class name,

[Tutor] best approach to db-api imports and cursor calls

2009-08-12 Thread Serdar Tumgoren
Hi everyone, Was wondering if you could advise on best practices when it comes to reusing a database cursor. I'm working on a program that must hit a database several times. Basically, I pull some data, process it, and then use a portion of that data as parameters for the next call. And then I rin

Re: [Tutor] best approach to db-api imports and cursor calls

2009-08-12 Thread Serdar Tumgoren
> My understanding is that it is relatively expensive to connect() and > cheap to create cursors. Cursors are also associated with > transactions. So a common practice seems to be to create a connection > that is shared in some way, and to create a cursor for each > transaction / operation. > > Ken

Re: [Tutor] best approach to db-api imports and cursor calls

2009-08-13 Thread Serdar Tumgoren
> But most folks find multiple cursors easier to manage in the same way that > they find multiple variables easier than reusing a minimal number. > That makes sense. I think I'll try using a global import/connect, and then create cursors inside each method. Thanks to you both for the advice! _

Re: [Tutor] Web framework: looking for python-tutor's angle.

2009-08-13 Thread Serdar Tumgoren
I've never used Zope so I can't speak to its strengths or weaknesses. But I can say that Django is quite natural if you already know Python. It certainly is modular, with a ton of apps that you can plug in to gain added functionality. And there's also a project called Pinax that provides layers of

[Tutor] rationale for nested classes?

2009-08-14 Thread Serdar Tumgoren
Hi everyone, I was wondering if there's anyone who can offer a use case/rationale for nested class? For, instance, in the following example (taken from here: http://www.brpreiss.com/books/opus7/html/page598.html): class A(object): def __init__(self): self.y = 0 class B(object):

Re: [Tutor] rationale for nested classes?

2009-08-14 Thread Serdar Tumgoren
2009/8/14 Geneviève DIAGORN : > Bonjour, > Je suis absente jusqu'au 02/09 inclus. > Good to know. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor

Re: [Tutor] rationale for nested classes?

2009-08-14 Thread Serdar Tumgoren
Okay, those explanations definitely help. I thought I had run into a situation where nested classes might be called for, but I think plain-old inheritance is really what I'm after. Many thanks! ___ Tutor maillist - Tutor@python.org http://mail.python.o

Re: [Tutor] rationale for nested classes?

2009-08-17 Thread Serdar Tumgoren
> I would use a nested class to create a particular data structure which > represent a "sub-unit" of the mother class. ... In this > way I could enforce behaviours like "not null" or "default" from within > the datastructure itself (for example in the __init__ method) rather > than enforcing a logi

Re: [Tutor] Problems with encoding in BeautifulSoup

2009-08-18 Thread Serdar Tumgoren
> Setting sys.setdefaultencoding() affects all scripts you run and will > make scripts that you write non-portable. A better solution is to > properly encode the output, for example > for company in companies[:4]: # assuming companies is a list >  print company.encode('cp437') > Kent's suggestion a

[Tutor] yet another question on OO inheritance

2009-08-18 Thread Serdar Tumgoren
Hi all, I've hit another gray area for an application I'm working on. Specifically, I have a campaign Committee object, and then subclasses called CandidateCommittee and PresidentialCommittee. Depending on the type of committee, I have to execute a series of SQL statements to pull data (used to po

Re: [Tutor] yet another question on OO inheritance

2009-08-18 Thread Serdar Tumgoren
Thanks to you both for the suggestions. I think I'll try the approach below. But just one follow-up: should I be setting "self.tablename", or is a static attribute ("tablename") the correct approach? > A nice way to do this is with a class attribute. For example: > class Committee(object): > >   d

Re: [Tutor] yet another question on OO inheritance

2009-08-18 Thread Serdar Tumgoren
On Tue, Aug 18, 2009 at 2:51 PM, Serdar Tumgoren wrote: > Thanks to you both for the suggestions. I think I'll try the approach > below. But just one follow-up: should I be setting "self.tablename", > or is a static attribute ("tablename") the correct approach?

Re: [Tutor] yet another question on OO inheritance

2009-08-18 Thread Serdar Tumgoren
> ..The atttribute is created in the class definition > (not in any method) as just "tablename". This creates an attribute of > the class, rather than of the instance. It is accessed as > "self.tablename". The attribute lookup rules will look first in the > instance, fail to find 'tablename', then

[Tutor] get name of calling class at runtime

2009-08-21 Thread Serdar Tumgoren
Hi everyone, I'm trying to create a data-retriever class that executes certain SQL statements based on the name of a calling class (I'm doing this so I can group a bunch of SQL statements in one place; they're currently scattered all over the program and it's getting unwieldy). Currently, I'm forc

Re: [Tutor] get name of calling class at runtime

2009-08-21 Thread Serdar Tumgoren
> You could simplify the code above by passing self to DataSources(). Or > make CallerX inherit from DataSources and use the class attribute > trick we talked about before. Or perhaps you should look into > SQLObject or SQLAlchemy? > The class attribute trick worked nicely. I'll think about how to

Re: [Tutor] get name of calling class at runtime

2009-08-23 Thread Serdar Tumgoren
>> I think it does makes sense to keep SQL confined to well-defined >> locations. This can be per class - each class holds its own SQL - or a >> single class that does all database access so all SQL and database >> dependencies are in one place. The above is precisely what I'm after, and I agree t

Re: [Tutor] Template long text substitution

2009-08-24 Thread Serdar Tumgoren
Stefan, Have you considered a templating engine such as Jinja or Cheetah? http://jinja.pocoo.org/2/ www.cheetahtemplate.org/ They should be able to handle a lot of the parsing and pairing of variables in a template that you're attempting. Basically, you use template syntax (as you seem to have c

[Tutor] flyweight pattern using Mixin vs. Inheritance

2009-08-28 Thread Serdar Tumgoren
Hi everyone, Based on some earlier list advice, I went back to the drawing board and started testing various approaches to adding the "flyweight" pattern to my classes. To recap, I have a bunch of campaign finance-related classes and subclasses (Committee, HouseCommittee, PresidentialCommittee, C

Re: [Tutor] flyweight pattern using Mixin vs. Inheritance

2009-08-28 Thread Serdar Tumgoren
I was able to resolve the error by explicitly naming the class in the dictionary lookup inside __new__: if candid in CandidateAuto.instances: return candid I'm curious why this is necessary though. From our earlier dicussions (and from other reading), I thought that by declari

Re: [Tutor] flyweight pattern using Mixin vs. Inheritance

2009-08-28 Thread Serdar Tumgoren
class A: > instances = {} > def __new__(self,ID): > if ID in self.instances: > return self.instances[ID] > else: > self.instances[ID] = self > return self > def __init__(self, ID): > if ID not in self.instances: > print("unregistered instance!") > def __del__(self): > del(self.instances[self.I

[Tutor] use case for graphs and generators?

2009-09-08 Thread Serdar Tumgoren
Hi everyone, I was hoping someone could advise on whether I'm tackling a specific problem in the correct manner. Specifically, I'm trying to use a "clean" set of historical data to fix omissions/errors among a stream of newer data. To do so, I've devised a series of backend SQL statements which ne

Re: [Tutor] Getting list of attributes from list of objects

2009-09-10 Thread Serdar Tumgoren
> I have the following list > > l= [ a, b, c] > > Where a,b,c are objects created from one class, e.g. each has title > attribute. > What I want to have is a list of titles, e.g. [a.title, b.title, c.title] > > Is there a quick way to do it? Or I should use loops (looping through each > element, an

Re: [Tutor] Poorly understood error involving class inheritance

2009-09-10 Thread Serdar Tumgoren
class dummy2(str): > ...     def __init__(self,dur=0): > ...             self.dur=dur > ... z=dummy2(3) z.dur > 3 > > So far so good.  But: > z=dummy2(dur=3) > Traceback (most recent call last): >  File "", line 1, in > TypeError: 'dur' is an invalid keyword argument for this f

Re: [Tutor] Poorly understood error involving class inheritance

2009-09-10 Thread Serdar Tumgoren
> When you sub "int" for "str", it seems to work. Is there a reason > you're not just subclassing "object"? I believe doing so would give > you the best of both worlds. > Of course, I should qualify the above -- the "str" subclass inherits very different methods than "int" or "object". http://doc

[Tutor] breaking out of a function that takes too long

2009-09-15 Thread Serdar Tumgoren
Hey everyone, Is there a way to break out of a function if it exceeds a certain time limit for execution? There's a Website I'm scraping on a regular basis, and for some reason that I can't divine the site has radically varying response times. In some cases, I get a result vary quickly; at other t

Re: [Tutor] breaking out of a function that takes too long

2009-09-15 Thread Serdar Tumgoren
Thanks to all for the responses. I've never used threading, but from some initial googling it appears that it can indeed by tricky and there seem to be numerous recommendations against killing threads or processes. I'll explore the socket request libraries mentioned by several to see if that does

[Tutor] calling a superclass method after overriding it

2009-09-22 Thread Serdar Tumgoren
Hi everyone, Is there a way to call a superclass method after I've overridden it in a subclass? Specifically, what I'm trying to is something like the following: class Parent(object): def add_name(self): self.name = result_of_GENERIC_SQLcall() class Child(Parent): def __init__(se

Re: [Tutor] calling a superclass method after overriding it

2009-09-22 Thread Serdar Tumgoren
> You're actually already doing it:  look at __init__. > > __init__ is overridden in your subclass, so you call super(Child, > self).__init__() to initialise the class using the parent > (superclass)'s __init__ method. Yes indeed. Thanks for pointing it out. In case it helps anyone else out down t

Re: [Tutor] calling a superclass method after overriding it

2009-09-22 Thread Serdar Tumgoren
> I prefer the older approach too, it is simple and explicit. super() > comes with a raft of complications (google "super considered harmful") > and AFAIK it is only really needed in the case of "diamond" > inheritance. > The explicit method does indeed seem...well...more explicit and easier to und

Re: [Tutor] calling a superclass method after overriding it

2009-09-22 Thread Serdar Tumgoren
> I know that when you need super(), you have to use it everywhere. So I > would stick with what you have. > > Kent > Okay. Thanks as always to all. Best, Serdar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http:

Re: [Tutor] calling a superclass method after overriding it

2009-09-22 Thread Serdar Tumgoren
> I know this is a simplified example, but I'd still like to point out that > using exceptions when there's a simple test is not reasonable.   You can > just check for None with a simple if test. An "if" test would be more readable, I agree. But I was trying to apply the "Easier to Ask Permission

Re: [Tutor] calling a superclass method after overriding it

2009-09-22 Thread Serdar Tumgoren
> An "if" test would be more readable, I agree.  But I was trying to > apply the "Easier to Ask Permission Forgiveness" style, discussed in > the Python Cookbook: , > Err..."Easier to Ask Forgiveness than Permission" approach is what I meant (perhaps proving my point about not fully understanding t

Re: [Tutor] calling a superclass method after overriding it

2009-09-22 Thread Serdar Tumgoren
>>>            self.name =ame > > I assume this is a typo? And it never gets executed because the error is > always raised. yep. that was a typo that should be "name" > I don't mind using exceptions for a simple test but not where the test is > being forced by a piece of code that does nothing. I

Re: [Tutor] calling a superclass method after overriding it

2009-09-22 Thread Serdar Tumgoren
>   def add_name(self): >       try: >           self.name = SPECIALIZED_SQLcall_for_child() >       except SpecialSQLError: >           #default to the superclass's add_name method >           super(Child, self).add_name() > That certainly is a lot easier to read. So if I were to go that route, wo

Re: [Tutor] how to print a message backwards

2009-09-23 Thread Serdar Tumgoren
Try reading up on sequences and slicing. They offer a very elegant solution to your (homework?) problem. http://docs.python.org/tutorial/introduction.html#strings ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http

Re: [Tutor] how to print a message backwards

2009-09-23 Thread Serdar Tumgoren
> http://docs.python.org/tutorial/introduction.html#strings > The below page is a better introduction to sequences: http://effbot.org/zone/python-list.htm It uses lists, but the lessons on slicing also apply to strings (which are a type of sequence). HTH! Serdar

Re: [Tutor] how to print a message backwards

2009-09-24 Thread Serdar Tumgoren
> Does anyone have an advanced topic on slicing where the :: notation is > explained? > You should find plenty by googling for "python slice step sequence" Here are a few with links to further resources: http://www.python.org/doc/2.3/whatsnew/section-slices.html http://stackoverflow.com/questions

Re: [Tutor] Novice qustion

2009-09-24 Thread Serdar Tumgoren
>>  File "test.py", line 18 >>    print format % (item_width, 'Dried Apricots (16 gr)' price_width, 8) >>                                                                   ^ >> SyntaxError: invalid syntax Oxymoron has pointed you in the right direction. After you fix that error, however, you'll get

  1   2   >