Is it possible to somehow make [] in Python associated not with a sheet, but with some other class?

  • one
    And you can ask why? - andreymal
  • I just wondered, but I couldn’t get the answer) - Tolkachev Ivan
  • Numpy and Pandas in all this enjoy ... Explain what you want to do. - MaxU

2 answers 2

Can. For example, using the codetransformer package :

 from codetransformer import CodeTransformer, instructions, pattern class BuildSetFromList(CodeTransformer): @pattern(instructions.BUILD_LIST) def _build_set(self, _build_list): yield instructions.LOAD_GLOBAL("set") yield instructions.CALL_FUNCTION() @BuildSetFromList() def f(): return [] assert f() == set() 

Instead of a list, [] create set() here.

There are several other ways, see starting with "Python code in different representations can be manipulated as a simple object . "

  • Ok, and now we have >>> type(f()) -> <class 'set'> but >>> type([]) -> <class 'list'> not sure what this is called "can". Thanks for the fun, interesting - Igor Lavrynenko
  • @IgorSergeevich: (a) we look inside f() : return [] see square brackets (no objection? Do you agree?). (b) Then we call f() as you yourself have already recognized f() == set() (c) from (а) and (б) affirmative answer to the question "Is it possible to redefine square brackets in Python?" (Python code - ✓, [] - ✓, received a list is not - withdrawal: you can). The scope in which [] redefined can vary from the chosen method, but there is no doubt that [] redefined (in the example, the question inside the f function - you cannot say that it is not Python code, that [] not redefined) . - jfs

To make it so that [] cannot be applied to the list at all - it is impossible. To make [] applicable to a custom class object — it is possible, and it is not necessary that the parentheses have indexing semantics

 class IsEven: def __init__(self): pass def __getitem__(self, item): return item % 2 == 0 x = IsEven() print x[1], x[2] # --> False True 

If it is a question that a constructor call has the syntax of a list generator - it is impossible.

  • the question is not about how to redefine indexing: seq[index] , but about how to do it so that [] does not return list() , but something else. - jfs