Is it possible to create a Python list and fake it?

I am working with a Neo4j database and want to adapt one of the existing REST libraries. Imagine a database case with 20 nodes.

>>> db = Database("http://localhost:7474")

I would like the API to be as simple as possible, so it would be possible to get the 14th node with something similar to this:

>>> db[14]

In Neo4j, each node has a numeric key. This means that db[14]it matches very well http://localhost:7474/db/data/node/14. However, I do not want to load every node from the database into the object db. My preferred behavior is to look for node 14 and raise an IndexError if that value does not exist in the database. That is, I want the object to dbbe empty, but pretend that matters.

Is it possible to create something that looks like list, but behaves differently?

+3
source share
1 answer

Yes, you can write your own class that implements __getitem__and generates the 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 details .

+10
source

Source: https://habr.com/ru/post/1785599/


All Articles