Using String Methods In Jump Tables
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Thu Aug 19 20:23:57 EDT 2010
On Thu, 19 Aug 2010 18:27:11 -0500, Tim Daneliuk wrote:
> Problem:
>
> Given tuples in the form (key, string), use 'key' to determine what
> string method to apply to the string:
>>> table = {'l': str.lower, 'u': str.upper}
>>> table['u']('hello world')
'HELLO WORLD'
[...]
> As I said, I know I could do this as a set of cascading ifs or even as
> an eval, but I'm loathe to use such approaches. I like jump tables as a
> structural construct because they are easy to understand and maintain. I
> also realize that what I'm asking may be violating some deeply held
> notion of OO purity, but, well, now I'm just curious if there is a way
> to do this
This is Python, not some "pure" OO language. We have functional
programming constructs, procedural constructs, and probably other
programming models as well. Screw the deeply held notion of OO purity :)
But seriously, Python's object model includes bound and unbound methods
precisely so you can do this sort of thing, and the above table-based
approach is very common and recommended as an alternative to case/switch
statements. It's a very common Pythonic idiom, so never fear that people
will stone you for using it.
The only thing that is a bit unusual is that you call it a jump table. In
my experience, "Jump Table" is used for low-level languages where the
table values are memory addresses.
--
Steven
More information about the Python-list
mailing list