Is it possible to somehow make [] in Python associated not with a sheet, but with some other class?
- oneAnd 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
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 callf()as you yourself have already recognizedf() == 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 theffunction - 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 returnlist(), but something else. - jfs
|