How to create cross between __getattr__() and __getitem__()?
John Lull
lull at acm.org
Sat Dec 4 12:04:35 EST 1999
(posted & mailed)
In the waning years of the 20th century, "Darrell" <news at dorb.com>
wrote (with possible deletions):
> Assuming I understand, this might help.
Perhaps I didn't express myself well.
> attrs={'dog':1, 'cat':2}
>
> class A:
> def __getattr__(self, name):
...
> print a.dog
> print a.dog
This is standard __getattr__() usage, and does not accomplish what I
need.
I have a procedure
queryRemoteDatabase(name, index=-1)
which is my sole means of accessing a remote database. That database
is not under my control, and queryRemoteDatabase() is very slow,
especially when retrieving a tuple.
In that database, "dog" is the integer 1, and "cat" is the tuple
[3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3].
The following all work:
print queryRemoteDatabase(dog)
1
(this takes 20 mS)
print queryRemoteDatabase(cat,4)
2
(this takes 20 mS)
print queryRemoteDatabase(cat)
[3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3]
(this takes 360 mS since "cat" is a tuple of 18 integers, and it takes
the remote database 20 mS to retrieve *each* element of the tuple)
There is no way to find out whether "cat" or "dog" is an integer or a
tuple other than a call to queryRemoteDatabase(). Each such call
requires a minimum 20 mS, *even if it fails*, and specifying an index
when retrieving "dog" will cause it to fail.
I need to have both of these work with a single invocation of
queryRemoteDatabase():
print a.dog
print a.cat[4]
in a system where class A cannot know ahead of time which is an
integer and which is a tuple.
Regards,
John
More information about the Python-list
mailing list