Skip to content Skip to sidebar Skip to footer

How Might One Change The Syntax Of Python List Indexing?

After asking this question, it received a comment about how you could do something like this: >>> def a(n): print(n) return a >>> b = a(3)(4)(5) 3

Solution 1:

You'd have to use a custom class, and give it a __call__ special method to make it callable. A subclass of list would do nicely here:

classCallableList(list):def__call__(self, item):
        returnself[item]

You cannot use this to assign to an index, however, only item access works. Slicing would require you to use to create a slice() object:

a = CallableList([1, 2, 3])
a(2)
a(slice(None, 2, None))

nested = CallableList([1, 2, CallableList([4, 5, 6])])
nested(2)(-1)

For anything more, you'd have to create a custom Python syntax parser to build an AST, then compile to bytecode from there.

Solution 2:

the parentheses in my_list() are treated as a function call. If you want, you could write your own class that wraps a list and overwrite the call method to index into the list.

classMyList(object):

    def__init__(self, alist):
        self._list = alist

    def__call__(self, index):
        return self._list[index]

>>> mylist = MyList(['a','b','c','d','e','f'])
>>> mylist(3)
'd'>>> mylist(4)
'e'

Solution 3:

You could create a function that returns a lambda function:

defmake_callable(some_list):
    returnlambda x: some_list[x]

original_list = [ 1, 2, 3, 4 ]
callable_list = make_callable(original_list)

print(callable_list(1)) # Prints 2

Post a Comment for "How Might One Change The Syntax Of Python List Indexing?"