Applying decorators to built in Python functions?

Discussion

Is it possible to do this? We have huge codebase making use of some of standard python modules and we see that in our environment some of the python standards functions needs us to do some additional retries or changes in their call flow, currently we are wrapping those standards functions inside our own functions and making use of it, but was wondering if we can write a decorators which can be applied to standards functions in python, so that if someone uses standard functions in code base our modified routine should also be invoked.

Any suggestions comments are welcome

Posted Jun 2, 2022, 8:40 AM UTC

05
james_pic•

Yes

import builtins
builtins.str = my_decorator(builtins.str)

But don't. You will regret it.

19
wineblood•

Don't do that, it sounds awful. Write a modified version and explicitly use that instead.

10
jammasterpaz•

It sounds like an absolutely terrible idea, but yes it is possible. As you're not defining the function you just can't use the @ syntactic sugar, you must override the standard function directly.

Why though? It's bound to cause errors and annoy that "someone".

8
[deleted]•

[deleted]

1
pythonHelperBot•

Hello! I'm a bot!

It looks to me like your post might be better suited for r/learnpython, a sub geared towards questions and learning more about python regardless of how advanced your question might be. That said, I am a bot and it is hard to tell. Please follow the subs rules and guidelines when you do post there, it'll help you get better answers faster.

Show r/learnpython the code you have tried and describe in detail where you are stuck. If you are getting an error message, include the full block of text it spits out. Quality answers take time to write out, and many times other users will need to ask clarifying questions. Be patient and help them help you. Here is HOW TO FORMAT YOUR CODE For Reddit and be sure to include which version of python and what OS you are using.

You can also ask this question in the Python discord, a large, friendly community focused around the Python programming language, open to those who wish to learn the language or improve their skills, as well as those looking to help others.


^(README) ^(|) ^(FAQ) ^(|) ^(this bot is written and managed by u/IAmKindOfCreative)

^(This bot is currently under development and experiencing changes to improve its usefulness)

1
metaperl•

Additional retries can be handled by the pypi module tenacity.

Please give an example of what you mean by changing call flow.

1
[deleted]•

[removed]

1