Is it possible to create a Python list and fake populating it?
سؤال
I am working with Neo4j graph database, and would like to adapt one of the current REST libraries. Imagine a case with a database with 20 nodes.
>>> db = Database("http://localhost:7474")
I would like the API to be as simple as possible, so that it would be possible to get the 14th node with something similar to this:
>>> db[14]
In Neo4j, every node has a numeric key. This means that db[14]
maps very nicely to http://localhost:7474/db/data/node/14
However, I don't want to load every node from the database into the db
object. My preferred behaviour is to lookup node 14, and raise an IndexError if the value doesn't exist in the database. That is, I want the db
object to be empty but pretend to have a value.
Is it possible to craft something that looks like a list
, but behaves significantly differently?
المحلول
Yes, you can write a custom class that implements __getitem__
and generates a result dynamically.
>>> class MyDatabase(object):
... def __getitem__(self, x):
... if 10 <= x <= 15:
... return "foo"
... else:
... raise IndexError('key not in database')
...
>>> db = MyDatabase()
>>> db[12]
foo
See Special method names for more information.