Monkey-patching: a magic trick or a powerful tool?

Video in TIB AV-Portal: Monkey-patching: a magic trick or a powerful tool?

Formal Metadata

Monkey-patching: a magic trick or a powerful tool?
Title of Series
Part Number
Number of Parts
CC Attribution - NonCommercial - ShareAlike 3.0 Unported:
You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal and non-commercial purpose as long as the work is attributed to the author in the manner specified by the author or licensor and the work or content is shared also in adapted form only under the conditions of this license.
Release Date

Content Metadata

Subject Area
Elizaveta Shashkova - Monkey-patching: a magic trick or a powerful tool? Monkey-patching is a dynamic modification of a class or a module at runtime. The Python gives developers a great opportunity to use monkey-patching almost everywhere. But should developers do it? Is it a magic trick or a powerful tool? In this talk we will try to give the answers to these questions and try to figure out pros and cons of using monkey- patching. ----- First of all we will learn what is monkey-patching in Python and consider some basic examples of using it. Of course, monkey-patching may cause some problems in the code. We will consider bad ways to use it and try to learn different types of problems monkey-patching may lead to. Despite of some bugs that may appear in a patched program, monkey- patching is used in a real life rather often. There are some reasons and motives to do it. We will consider the examples of using monkey- patching in real projects like `gevent`, in some other libraries and in testing. Also we will learn some monkey-patch tricks that helps to solve real-life problems in the Python debugger which is a part of the PyCharm and the PyDev. After that we will compare using of monkey-patching in Python to using it in an another dynamic language Ruby. Are there any differences between them? Is our reasoning correct for Ruby? Finally we will conclude all our thoughts and examples and try to give the answer to the question from title.
Point (geometry) Functional (mathematics) Standard Model Multiplication sign Mass Theory Computer programming Number Mathematics Root Square number Negative number Aerodynamics Endliche Modelltheorie Exception handling Social class Module (mathematics) Dialect Run time (program lifecycle phase) Mathematics Type theory Particle system Word Computer animation Social class Window
Programming language Group action Patch (Unix) Perceptron Standard Model Mereology TDMA Symbol table Number Formal language Array data structure Computer animation Term (mathematics) String (computer science) Network topology String (computer science) Personal digital assistant Social class Endliche Modelltheorie Reverse engineering Social class Reverse engineering
CAN bus Computer animation Channel capacity Patch (Unix) Code Multiplication sign Statement (computer science) Energy level Form (programming) Stability theory
Point (geometry) Functional (mathematics) Open source Decision theory Multiplication sign Adaptive behavior Source code Set (mathematics) Machine code Dimensional analysis Computer programming Revision control Software testing Endliche Modelltheorie Projective plane Shared memory Code Measurement Particle system Computer animation Order (biology) Video game Software testing Modul <Datentyp> Object (grammar) Cycle (graph theory) Library (computing)
Computer animation Order (biology) Process (computing) Computer programming
Functional (mathematics) Channel capacity Multiplication sign Debugger Instance (computer science) Attribute grammar Revision control Medical imaging Hooking Data management Process (computing) Computer animation Statement (computer science) output Process (computing) Endliche Modelltheorie Resultant Social class Form (programming)
Module (mathematics) Functional (mathematics) Inverse function Module (mathematics) Patch (Unix) Instance (computer science) Measurement Attribute grammar Revision control Hooking Arithmetic mean Data management Process (computing) Computer animation output Endliche Modelltheorie Object (grammar) Social class Form (programming)
Functional (mathematics) Electric generator Multiplication sign Inverse element Instance (computer science) Mereology Event horizon Attribute grammar Hooking Data management Event horizon Computer animation Endliche Modelltheorie Freeware Inverter (logic gate) Library (computing)
Functional (mathematics) Real number Modulare Programmierung Inverse element Protein Event horizon Machine code Computer programming Wave packet Mathematics Synchronization Operator (mathematics) Software testing Endliche Modelltheorie Library (computing) Social class Module (mathematics) Quantum state Code Cartesian coordinate system System call Particle system Event horizon Computer animation Personal digital assistant Network socket Statement (computer science) output Video game Software testing Modul <Datentyp> Physical system Resultant Library (computing)
Mathematics Process (computing) Computer animation Compiler Plastikkarte Object (grammar) Formal language
Standard deviation Patch (Unix) Standard Model Cartesian coordinate system Semantics (computer science) Thread (computing) Computer programming Mathematics Coefficient of determination Event horizon Computer animation Synchronization Network socket Order (biology) Video game Pattern language Modul <Datentyp> Cycle (graph theory) Library (computing)
Debugger Code Control flow Ordinary differential equation Event horizon Thread (computing) Computer programming Revision control Event horizon Logic Revision control Modul <Datentyp> Endliche Modelltheorie Loop (music)
Module (mathematics) Cubic function Functional (mathematics) Module (mathematics) Link (knot theory) Price index Data dictionary Revision control Computer animation Network socket Object (grammar) Network socket Revision control output Modul <Datentyp> Object (grammar) Endliche Modelltheorie Resultant Physical system
Module (mathematics) Boss Corporation Channel capacity Patch (Unix) Price index Modulare Programmierung Data dictionary Event horizon Computer programming Revision control Event horizon Computer animation Network socket Function (mathematics) Revision control Cuboid Modul <Datentyp> Endliche Modelltheorie
Standard deviation Inclusion map Computer animation Patch (Unix) Code Video game Software testing Software testing Modul <Datentyp> Binary multiplier Machine code Computer programming
Axiom of choice Functional (mathematics) Greatest element Matching (graph theory) 1 (number) Shared memory Set (mathematics) Control flow Volume (thermodynamics) Instance (computer science) Power (physics) Process (computing) Computer animation Personal digital assistant Videoconferencing Software testing Pattern language Game theory Library (computing) Social class
the welcome back at outlets window believe you we've Monday budgeting is emitted 3 colourable fulfill welcome a few hi my name is Elisabetta and today I want to tell you about 1 2 by 2 implies in this talk I'll try to give an answer to the question is not too much of it is just magic to or is it a very powerful and just a few words about me the island suffered in the genome brings called time talking about your ideas and developed by yeah in by chance which is also used in by that Python 84 eclipse but the point here is that in a modification of a class or a model that around theory is a simple example which illustrates and what about in this type of model mass has a square function which returns the square root of number of but if the number is negative this function raises an exception will want to change the behavior of this function so what can we do with say that regional square root function to the 100 original of the model and has this square it tributes with our new function the square root function which doesn't throw exception for negative numbers and returns that not a number of constant which is defined in math module so what happened here we've got the the standard model and change in behavior in fact our program and that means that must eventually as to change for a particle without changing the 1st
it's a place where does this term Monte Buchan comes from it but it's that it has to come from the John gaining apart this really is a member of a group of soldiers doesn't know who don't belong to the regular army amplified into words secret and this terror is referred to changing consequently and possibly who commodity with other such much in the late Middle Ages perceptron was transformed to during about which which sounds similar and that it was transformed to as you might already know just only terms has another rather negative meaning but despite of its multiparty exists in a number of other programming language for example if you think you can
define and method in panic last including the standard model like trees or arrays in anaerobic named recalled in the class In this example we replace and the standard opting string models with that reverse as we can see the multiplexing is being is almost as part of the language philosophy because you period and because there reason that and even as special symbols for doing so what about by the irony that
everybody here remembers the Zen of Python and 1 of the most important statements in its explicit is better than implicit Monday capacity down as it is by this requirement because instead of really explicitness she makes by Python code less readable and more difficult for understanding and it
wouldn't be wouldn't budge everything it binds and we can write almost everything because on about the level of the time but stability is defined in the there are some possible some of the form that these to much the syllable but you want distrust them today so as you can see
Monday departure is a very interesting to it is a lot of opportunities and also both the great amount of the person who uses the novel let's have like every object in our going to multiply has its own light and dark sides now let's have a short selling these trends and you're on the right side of multiple well and now already and if you're on the dark side of multi-party other I would like to start from the life cycle from 1 of my capacity and consider how we can use it in real life
so long as only dimension we can change the 3rd particle without changing the source and for example if you found block inside in some libraries and you know how to fix it you can just you can just apply prior to this library and use of the correct version of the library inside your program by remember that nowadays almost every libraries open source so the best decision is to fix the bark and agreed to request and share features with other users it's something important example of usage of abiding is called instrumentation you can use to buy in order to add performance measurements to your court without changing the Court of your project the also sometimes tests need to invoke some functionality which depends on global settings always will support which can be easily test a lot of data library allows you to replace parts of your system and adapt with more objects and the next important example is changing the Standard model this point look similar to the first one but it's not about buckets sometimes there is a need to change the standard library for your own course and there are some libraries who do it later we consider such an it's time for example the
1st example of there will be from the wider internal and I've already mentioned findings developed divided in and it's very important for us us to catch all the new proteases created in the user's programs in order to add to the binary thing to this new processes and multiparty most us to do it and you attach a new
process is created with the work function for them what you always would find very simple class process manager which takes their original form function and calls speed in the method do for the parched versions of this function then it calls the original for function and check this out if the result is your that means that we are situated in the child process we call our debuggers tracing functions stop chasing after the return the process ideas like the original for functions doesn't how can we use our manager it's very simple we invert model uh create the instance of our predicament in class and pass their regional was that for function data and after that replace attributes for all of them would you always with our method to do before and after that every time when we call arrested for functions we and in our divided tracing to averaging process the next
example is about input from almost everything you need to start with the inverse statements and every time we're imaging somewhat deal with the fact called built-in import function let's sediment capacity to in the previous example
we much them all as don't work function but what if we want to pass modular as soon as possible as soon as possible means right after emerging that's why
we need to create and this is an important measure class and it's very similar to that process measures class and it also saves the original input for important function and cause it inside the white version of this function but also give checks the name of the the model and give the name of the module is missing that is we want to plot the object of our model we again get original attribute of the model create the instance of our approach manager and placed at a new form of the model I would like standard inverse function does it will return the object of the model how can we use our in of manager it's very
simple we invertibility and the model where that functions you get create the instance of the virtual manager and again replace the attribute you part of this model with our human and now every time when we leave died inverse where it will be passed as soon as possible right after and the
3rd example on the right side is related to the G event library generators free
market for scalable the synchronous input and output operations based on the the light rays protein it reminds his own event so even when training programs are not blocked by the I O operation that's why Jean and Library is very useful but around looking system calls in the standard library including for example and when he used such models in your program you break the main idea of the gym and library because your final operations becomes synchronous back in this case you can replace some statements like inverse so that's OK with modulus from the G event library which are very similar of will to their Standard model is but we are compatible with it so instead of the result and you should just right from G event in person but if you already have an application which uses such modulation of there is no need to modify such the inverse statements in many many places because there is a special module inside you generally don't want it to happen places functions and classes in the Standard Model and after that they can be used together with that library it allows you bite and applications and libraries it can impressed with no modification multiply she
has many interesting and useful applications in real life like change the particle testing corners fermentation multiply is a very powerful tool but
monitored by saying is a very dangerous to as as well as I already
mentioned in the beginning of my job market but she violates the philosophy of Python language changes made by my departing are not when you buy something it leads to the unpredictable behavior of your problem changes are not implemented and they may be very unexpected for people who uses your card also even if you did commended semantic Parsing sometimes we can meet people who decided that 1 can buy something to and it will be very sad to realize that you decided to modify the same object
the examples and the dark side of semantic patterns are also very important and this example will be related to the geometric Library again in this example I want to show how much pricing can lead to creation rather complicated and to meet solution as I already
mentioned the generic can multiply some standard model In order to make Python applications synchronous without a lot of changes of course In the dog the creators of the given Langley mention that the change should be done as early as possible in the life cycle of the program
but what happens if you run the program with G of unbridled insect bites just about the debate has its own advantage based on the standard model and after given users program is based on the GLS and eventually but 2 of the event moves should be separated because divided it shouldn't affect users Cervantes it shouldn't break the logic of the user's problems so that means that the should use the original versions of models like fretting of something or something instead of watching version but session so
that means that we have a problem somehow we should see the original versions of some standard ontologies and continue to use them simultaneously with that by version next trying to solve this problem 1st let's consider
how the emerging in Python work this is a very very simplified version of the standard cubic function 1st of all you function is trying to find the name of the module indices don't want this dictionary contains and that object of all important models and of this model in this dictionary on the names of these model just as if of the input function didn't find the name of the model in this dictionary it is a huge defined again creates and you will object of the modeled and predicted disasters that model additionally utterance it as a result let's create some
you'll save money here will emerge socket module so that means that after that it was it is situated in this is the model of the dictionary and that the subject is inside piece of this dictionary after that we all the model the object with the subject from the dictionary what does that mean this object is not inside the dictionary but we still have a link to and after that when we import the socket model again that you work function trying to is trying to find it inside the don't sees the models dictionary it can't find it and it creates that another object of this model and it would take to this is of model dictionary and after that we have 2 objects of our ourselves wanted the and 1 of them is situated in the system model dictionaries and another example is used in our secret model so how
can we use it in our program we can't you birds boss we can get access to boss of these objects but after that when the event is trying to buy modules it is fighting the model which is situated indices don't model dictionary and you then it doesn't know anything about another module but we have know about it so that means that we can use the boss of this model is priced less than version and the original 1 together and simultaneously so as you can see the solution of the
problem was not very easy and I guess trying to fix the bark after by saying and we had to create some during facts with Boston so my capacity in the summer complicated boxes and too complicated to complicated fixes of the today we
consider it but size of multiplier but the question has many different and interesting implications in your life like changing your article got instrumentation testing working with standard modular by raising the inclusiveness of the car it can lead to some unpredictable behavior and surprisingly bathed in your program sometimes it may be incompatible with other set by I believe
that sometimes you can use my departure in your program but you should use it if and only if there are no other solutions for your problem if and only if you're absolutely sure that it is necessary in your OK
market matching is a fascinating to but modifies is a very dangerous to as well as for I'm delighted set of modified will use it inside by chance because it's a really powerful to the brain but also the him and without
an below but OK so now I believe that we have something for some questions so at that anybody would have some and I wrote letter do this but you elaborate on some examples of how you use looking like about monkey patterns in Pi sorry of the repeated can you describe some instances where you use the monkey in are you work function of yes and some of these examples borrowed from the bicentennial so the example where we catch new processes we use it inside pleasure by and there are the inverse whose use them side by side and to and to this uh solutions for up to protect from movement pricing is justified by so politicians OK any other questions think you think you talk and you mentioned at the beginning using matching for testing yeah and I've seen nothing like them not much of the libraries is that what you could use those achievements that indirectly because my worry is that if you manufacture test the thing to the next step in the medium this understanding will have that meant that subject and in some testing letters they use money to buy shares and settings that entirely in the library and not you yes yes and well I mentioned to testing in the light of my device I mean that's how they use monte botching investing libraries and there is no need sometimes you of course a candidate but there is no need to do it on your own because there are a lot of powerful testing library which all of who who are already does it for you any other questions this video that question that can we not solve the problem with that of men with that in my mind not doing much better by creating new objects or classes that do the same thing With the motivational so the question is that can be applied to multiple choice that is yes I creating new objects so we will only use those instead of real changing the ones that we want to change so so reasonable volume that there DOS example you create like monkeys that's the last a you yeah that instead of the your Western always yes we know we are in this example we modify their which was always old already in and we the function said it so I would love to talk is like you know the new yes you can create a wires and in this case we should OK poetry so there is no I mean that there are some possibilities to move avoid sentiment among devices as we done in which we did in the bottom of this example it is doesn't protect us from this from this solution which was shown on the in the example of the dark side the big have any other questions the you know them all you do them at the break and let's think the game was