Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions python2/koans/about_monkey_patching.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def bark(self):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you familiar with the concept of Monkey Patching? Could you briefly explain what it is and give an example of what it is used for?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have an understanding of what is, but I'm not that familiar with it.

What I get of Monkey Patching is a way to modify classes to add functionalities according to what you desire for that specific code.

For example, you may be importing a class from another source, but for that specific code you need some kind of test to validate a variable, so instead of creating an object to handle that testing, you just add it to the imported class, and that would be valid for that code.

def test_as_defined_dogs_do_bark(self):
fido = self.Dog()
self.assertEqual(__, fido.bark())
self.assertEqual("WOOF", fido.bark())

# ------------------------------------------------------------------

Expand All @@ -27,16 +27,16 @@ def wag(self):
self.Dog.wag = wag

fido = self.Dog()
self.assertEqual(__, fido.wag())
self.assertEqual(__, fido.bark())
self.assertEqual("HAPPY", fido.wag())
self.assertEqual("WOOF", fido.bark())

# ------------------------------------------------------------------

def test_most_built_in_classes_cannot_be_monkey_patched(self):
try:
int.is_even = lambda self: (self % 2) == 0
except StandardError as ex:
self.assertMatch(__, ex[0])
self.assertMatch("can't set attributes of built-in/extension type 'int'", ex[0])

# ------------------------------------------------------------------

Expand All @@ -46,5 +46,5 @@ class MyInt(int):
def test_subclasses_of_built_in_classes_can_be_be_monkey_patched(self):
self.MyInt.is_even = lambda self: (self % 2) == 0

self.assertEqual(____, self.MyInt(1).is_even())
self.assertEqual(____, self.MyInt(2).is_even())
self.assertEqual(False, self.MyInt(1).is_even())
self.assertEqual(True, self.MyInt(2).is_even())