Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I redefine functions in python?

Tags:

python

django

I got a function in a certain module that I want to redefine(mock) at runtime for testing purposes. As far as I understand, function definition is nothing more than an assignment in python(the module definition itself is a kind of function being executed). As I said, I wanna do this in the setup of a test case, so the function to be redefined lives in another module. What is the syntax for doing this? For example, 'module1' is my module and 'func1' is my function, in my testcase I have tried this (no success):

import module1

module1.func1 = lambda x: return True
like image 249
Thiago Padilha Avatar asked Sep 11 '10 18:09

Thiago Padilha


2 Answers

Use redef: http://github.com/joeheyming/redef

import module1
from redef import redef

rd_f1 = redef(module1, 'func1', lambda x: True)

When rd_f1 goes out of scope or is deleted, func1 will go back to being back to normal

like image 197
Joe Heyming Avatar answered Sep 21 '22 07:09

Joe Heyming


import foo

def bar(x):
    pass

foo.bar = bar
like image 31
leoluk Avatar answered Sep 24 '22 07:09

leoluk