0

I want to intercept all object creations to exchange the object with my custom object. For example, if I would like to exchange all list creations with my own list implementation (for this example a string with the content "Hello World!"), so that the following works:

>>> some magic
>>> []
'Hello World'

I tried to overwrite the built-in __new__, but it doesn't work as expected:

>>> import builtins
>>> builtins.__new__ = lambda *args, **kwargs: 'Hello World'
>>> __new__(type([]))
'Hello World'
>>> []
[]
Querenker
  • 2,242
  • 1
  • 18
  • 29
  • 3
    For what purpose? If you elaborate on what you're trying to do, there may be a better way of going about this. – Carcigenicate Jan 26 '20 at 17:16
  • @Carcigenicate I want to provide alternative implementations of some objects (preferable also builtins) without changing the code where they are created. It's for an experiment and not for production code, so it can be "hacky" (and if even possible probably will be). – Querenker Jan 26 '20 at 17:22
  • 2
    Honestly, a cleaner solution would be to create your own subclass of `list`/pseudo-constructors that do any pre-setup on the list. Modifying a built-in like `list` is dangerous. Unless the behavior is identical to the original (and would there be any point in that case?), you'd need to guarantee that no change you make will interfere with any other code that's using `list` (which is likely a lot of code). – Carcigenicate Jan 26 '20 at 17:24
  • That's if it's even possible to modify `list`. It's implemented in C afaik, so it may not even make sense to try and modify it in Python. – Carcigenicate Jan 26 '20 at 17:28

0 Answers0