Skip to content

Instantly share code, notes, and snippets.

@ludwig
Created September 17, 2018 23:37
Show Gist options
  • Save ludwig/0bf83d7d7a820e9bd04e8f00f5c4c16f to your computer and use it in GitHub Desktop.
Save ludwig/0bf83d7d7a820e9bd04e8f00f5c4c16f to your computer and use it in GitHub Desktop.
Using `mock.patch` to redefine sin & cos
from math import cos, sin, pi
def point_on_circle(theta):
return (cos(theta), sin(theta))
#!/usr/bin/env python
import numpy as np
from circle import point_on_circle
pt = point_on_circle(np.pi/4)
print(pt)
# output is: (0.7071067811865476, 0.7071067811865475)
#!/usr/bin/env python
import contextlib
import mock
import numpy as np
from circle import point_on_circle
def str_cos(theta):
return "cos({})".format(theta)
def str_sin(theta):
return "sin({})".format(theta)
with contextlib.nested(
mock.patch('circle.cos', str_cos),
mock.patch('circle.sin', str_sin)):
pt = point_on_circle(np.pi/4)
print(pt)
# output is now: ('cos(0.785398163397)', 'sin(0.785398163397)')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment