Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do monkeypatching in python?

I've had to do some introspection in python and it wasn't pretty:

name = sys._getframe(1).f_code
name = "%s:%d %s()" %(os.path.split(name.co_filename)[1],name.co_firstlineno,name.co_name)

To get something like

foo.py:22 bar() blah blah

In our debugging output.

I'd ideally like to prepend anything to stderr with this sort of information -- Is it possible to change the behaviour of print globally within python?

like image 306
1729 Avatar asked Sep 03 '08 12:09

1729


People also ask

What's multi patching in Python?

In Python, the term monkey patch refers to dynamic (or run-time) modifications of a class or module. In Python, we can actually change the behavior of code at run-time. We use above module (monk) in below code and change behavior of func() at run-time by assigning different value.

How does monkey patching work?

Monkey patching is reopening the existing classes or methods in class at runtime and changing the behavior, which should be used cautiously, or you should use it only when you really need to. As Python is a dynamic programming language, Classes are mutable so you can reopen them and modify or even replace them.

What is monkey patching in code?

Monkey patching is a technique used to dynamically update the behavior of a piece of code at run-time. A monkey patch (also spelled monkey-patch, MonkeyPatch) is a way to extend or modify the runtime code of dynamic languages (e.g. Smalltalk, JavaScript, Objective-C, Ruby, Perl, Python, Groovy, etc.)

What does patch mean in Python?

(monkey-) patching is a technique for changing code behaviour without altering its source. It is done in runtime, usually by overriding attributes of existing objects. An object can be an instance of some sort, a class or even a module.


2 Answers

A print statement does its IO through "sys.stdout.write" so you can override sys.stdout if you want to manipulate the print stream.

like image 134
Curt Hagenlocher Avatar answered Oct 22 '22 04:10

Curt Hagenlocher


The python inspect module makes this a lot easier and cleaner.

like image 32
Pat Notz Avatar answered Oct 22 '22 05:10

Pat Notz