tags:

views:

91

answers:

3

Is there a way of hooking str.__getitem__?

Example:

I'd like to be capable of do:

>>> "this is a string"[[1,3,4]]
'hs '

passing a list to [] and get the items in that list.

A more realistic example:

class STR(str):
    pass

class INT(int):
    pass

It's easy to make that STR("a string")[1] or STR("a string")[INT(1)] return an STR instance.

I'd like to be capable to make "a non STR string"[INT(1)] return an STR instance.

+3  A: 

Why hook an often-used internal function when you can

def get_characters (s, l):
  return "".join(s[i] for i in l)

>>> get_characters("this is a string", [1,3,4])
"hs "
KennyTM
The above was just an example. What a really want is make a modification on the semantic of getitem without modifying the original source.
Juanjo Conti
@Juanjo: Myabe you should edit your question to show what you really want to accomplish.
KennyTM
Done. Please see my new example.
Juanjo Conti
+2  A: 

Methods on objects defined in C cannot be monkeypatched. The best you can do is to use an external function to complete the task.

Ignacio Vazquez-Abrams
A: 

Try Ruby if you want to hack the language. The fact that some "programmer" who thinks he knows better than others how string or integer is supposed to behave cannot do this in Python is one of the reasons why Python is my favorite language.

Messa
I don't think I know better than others how those types should work. I want to do a differt use of them.
Juanjo Conti
-1 for not-very-subtly-masked flaming. Believe it or not, someone can have a need to do something you havn't personally thought of yet and still be a sans-snarky-quotation-marks programmer.
Glenn Maynard