 Voila, everyone. I'm really excited to be at Europe Python this year, and I'm really glad so many of you made it to this talk, because it's Friday, so yay, cool. So demystifying Mixins with Django is somewhat of an opinionated talk, and it's going to be about understanding what are Mixins, how they work, and how to create your own Mixins in the context of Django framework. I'll be glad to answer all your questions by the end of this talk. So, my name is Anna, and the simplest way to get in touch with me is via Twitter. I work at Potato, and I absolutely love saying this sentence, but seriously, Potato is an amazing company where we create all sorts of apps with Django and not only. Let's dive right in. Mixins are a controlled way of adding functionality to classes, but Mixins are not special language construct. This means there is no special keyword in Python that will point to some construct and say, well, this is a Mixin. In fact, Mixins are just ordinary Python classes. Take a look at this short example. It is a class called someMixin, and it has one method that does nothing. Well, this is a useless Mixin for obvious reasons, but let me draw your attention to one important bit over here. Our little Mixin inherits from object and only from object if we are using new style Python classes. So, the takeaway from here is that Mixins are preferably not derived classes. Mixins offer modularity, and that's the main reason we want to use them. When to use them? Well, when we want to reuse a particular feature in a lot of different classes, especially when this feature doesn't belong in any of the existing classes. That's why Mixins should be narrowing scope. In other words, have one single responsibility. They're not meant to be extended, and they're not meant to be instantiated. I mentioned Mixins are good in creating modular designs, so let's take a closer look at this decoupling concept. Imagine that you have an encapsulator that has four color coded features, orange, blue, green, and yellow. So far, so good. Imagine over time that your project grows bigger and we create new classes that encapsulate their own features. At this point, this code smells. It's ugly. There is something wrong with all those four classes because this yellow feature appears in all four of them. I bet someone copy pasted it. So what we need to do in this case is to extract the yellow feature and put it in a separate encapsulator so that the current and future classes can benefit from our newly created Mixin. And here comes the question. How do we actually do that? Well, in Python and not only, the concept of Mixins is implemented using multiple inheritance. And when we talk about multiple inheritance in Python, the order of inheritance matters. Here's how we can use a Mixin. Say we have a class foo that inherits from base foo and some Mixin. You might think especially according to some naming conventions that base foo acts as a base class and some Mixin is indeed a Mixin. Nevertheless, we should be reading this code in the following manner. Some Mixin is a base class extended by base foo, extended by foo. This might not be a problem if some Mixin and base foo are not sharing, extending, or overriding any of the existing methods. But if you are conscious that some Mixin will be extending a method of base foo, you should reverse the order. Well, that looks much better to me. An easy way to remember Python inheritance order is with one single arrow that goes all the way from right to left. When you start chaining Mixins, be especially careful about your order. So who has heard about this thing like framework, Django, someone? Someone, yeah? Not, not, not, yeah. Kind of grows in popularity, I think. And who's ever used class-based views? That's more like a lot of people. But if you didn't, that's no problem. I'll give you a short intro, really short. So here's a snippet, snippet, snippet, okay. Here's a snippet from the official Django documentation. It is a class-based view that inherits from template view, and a template view helps us render a template. That's all it does, and all it asks from us is to configure the name of the template. Class-based views in Django is one typical use case where Mixins use, where Mixins feel very natural. And so we are interested in plugging in over there and Mixin. Yay, we know two things right now. We know what are Mixins and how to use them. So let's go ahead and write our own first Mixin. The common use case in web development is to protect some of our pages. So we want to enforce our end users to authenticate before accessing a page. Let's create a Mixin that will check if a user is authenticated. First thing we do, we choose a good class name, login-required-Mixin, it inherits from object, and we place it inside some app, views.py file, though it might be placed almost anywhere. We would like to check if the user is authenticated before we start processing the request. You might know that or might not know that, but one of the first methods to be called when processing a request is dispatch. We use the same signature of the dispatch method as in the base view class, and now it's time to do the proper check. So if you take a look at the lines eight and nine, we say if the user is not authenticated, raise a permission denied exception. And since we don't write any Java and there is no way to auto-import packages, let's go ahead and specify on the line number two that we import permission denied from Django Core exceptions. One last thing to do is to handle the use case when a user is actually authenticated and we want to allow him or her to access the ultimate page. Therefore, let's call the super method on dispatch and resume the work of the base method. I'll leave it up to you to provide docs and tasks. Please do that. So going back to our about view, we plug in the login required mixing and ta-da. It works just like that. Now all the anonymous users are not allowed to trust us to the land of the super secret information of the about view. That's all there is required to protect a view. It's a very trivial example and very simplified, but it demonstrates a mixing in action. Here's how we describe graphically our latest usage of a mixing. The about view inherits both from template view and from login required mixing. And if you ever decide, oh well, I want a detail view instead of a template view, well, no problem. And if you didn't see what a health change on the slide is basically I have swapped the template view with the detail view. And that's a good thing, right? Because minimum effort is required to use a different view with no additional cost. And this looks simple. At least I hope it does to you, does it? Yeah? So I'm preaching here how neat are those mixings, but what if there is a different way? There are tons of different ways, but they aren't necessarily good or the best. So this made me think, how would I do it another way? I might check if the user is authenticated right in my view, but that's a stupid idea for obvious reasons. So I came up with this, as you will see also there is stupid idea. So I extended the template view and created a new class called login required template view, starts to remind me of some abstract view factory, view factory, and I made about view to inherit from it. Doesn't look that bad at the moment, but it actually does because every single other view, the number of which I extrapolate to infinity, that you want to have an OOF check will be extended the same way. That's exactly the same problem we have discussed at the beginning. We didn't solve anything, we just continued to copy paste the OOF check everywhere. Now take a look again at this diagram. It's elegant and simple. All right, so we all agree that mixings are fantastic. How about looking a bit more inside class based views and some common class based views methods? If we want to add a feature to a class based view using a mixing we sometimes need to know a bit about the Django internals. Once a request hits the template view, one of the first methods to be called is dispatch. We had this one. It figures out which HTTP method to call, is it a get, is it a post. So it is useful to override dispatch to provide a check very early on before anything else happens to the request. For example, check if the user is logged in or has permission. The next method, get context data, is also sometimes useful to be overwritten. It passes keyword arguments to the template context and so it is a way to add extra context to the views. Next one, get template names is a method called by render to response and it lists all template names. So it can be extended to add more flexibility to the template names if you have a different mechanism of identifying those in your Django project. So by now you probably should be angrily asking me how do I know all that? Because all I showed you was this simple example with the template view and it looked neat. But then suddenly you need to know all of this. Well, I'd be angry too. So here are some ways how you can learn more about Django class based views. So my personal approach is to go to jump right into the source code and it's easy to get your head around Django source code because it has doc strings and it's pretty well structured. But then of course there is a different approach. You can start with Django documentation to read a bit more about base classes of class based views and not by accident, Django uses mixings to build the class based views and you can read about them at this URL. Again, I highly recommend to take a look at the Django class based views and mixings source code because if you can't really wrap your hand, your head around all those mixings, Django provides an example how to get started. This little website, ccbv.co.uk is an awesome resource. It aggregates in one single place all the class based views, their methods, where they come from, their hierarchy diagrams and source code. So it's really good and well structured. I made you go through all of this login required mixing code, but in real life probably you don't bother implementing your own login required unless you really need to, you have a specific use case. Basically, because you have Django braces. Django braces is a package that aggregates common mixings that you will need in your project and they're structured in three categories, access, form and other mixings. If you have been using Django for some time, you're probably familiar with those decorators. Login required, user passes test and permission required. Well, I wish we had something similar in Django for class based views. Well, good news everyone. In Django 1.9, we will get login required mixing, user passes test mixing and permission required mixing. Yay. According to the roadmap, the final 1.9 version will be released sometime in December and those three mixings that shadow the original Django decorators were written during this year Django con Europe sprints in the evening after I gave this little talk. So that's pretty cool. Someone was listening to the talk while I was bubbling on the stage. Now let's get a bit more evil. How about some runtime magic? So what I wanna do, I wanna plug in some behavior to my classes in the runtime dynamically. I personally never had a use case where I would need that but let's try it just for fun. Let me tell you a story. This is a cute mixing and the mixing assumes that we have a name attribute and what it does is one ordinary print statement. Oh yeah, so you can see this is Python 2. And now let's introduce Mr. Mascot and its name attribute. One extra class, one attribute, fairly simple. Now we enter the land of Maine to bring to life some of our classes. So on line number 12, we create an instance of the mascot and his name is Domo. The next line is the magic. It modifies the basis of the mascot class and adds the cute mixing to it. We are mixing it dynamically. Then we try to call the be cute method from the cute mixing on previously instantiated object. And it works. Hey, meet Domokun. I emphasize that this works in Python 2 and we are also using old style classes. I'm not inheriting from object. So basis was mutable back then, spooky story. How about now? How about if we are using Python 3 or we have new style classes? Isn't much of a difference in code? Well, the print function is, the print is a function. Let's see what we can do. Well, we can't screw up as much as with Python 2 because basis is immutable. But we can change the Dunder class attribute on an instance that we have called kumamon and create a new type that includes the cute mixing and then make use of the be cute method. And this will work. If you ever do this, please make sure you do this for a very good reason and please provide plenty of documentation explaining the why and I have warned you. Be careful when you decide to use mixins because with great power comes great responsibility. Be aware of incompatible mixins chaining too many mixins and overdoing mixins, hence making it a nightmare to figure out the execution flow. Same as we advise against 100 lines long views functions and tons of decorators on your functions. We also advise against class-based views that require six mixins to work, you're probably doing something wrong and placing too much logic into your view layer or controller layer. So let's recap what we have learned so far. Mixins in Python are classes and should have one single responsibility. Segmentically, we think about mixins as some plug-in reusable functionality. Although mixins are mixed in using inheritance, they're not creating a subtyping relation. This means they don't adhere to Liskov principle from solid. Liskov principle says the following, instances of base class can be replaced with instances of derived classes and it will make sense. This statement doesn't hold for mixins and that's why we say that mixins are not creating a subtyping relation. I hope I convinced you that mixins are pretty cool and easy to create. Therefore, I strongly encourage you to go back to your views and start writing mixins to clean up your code. Thank you. So if you want, have you got any question? Well, I've got one to start with anyway. You say six mixins is too much for view, but what about three of them? Is this still okay? It depends on your use case. Normally, you would have two mixins, it's quite okay because you probably need a login required and then it has permission, quite a common use case. Maybe you have an extra one, it's still going to be fine, but the harder it gets to figure out where your request flows. So in this case, I think they're kind of like the couple because you login, you know what it's doing and it has permission, they both work with the dispatch and then you have an extra mixin that changes something in your context, might be okay. So three is still fine. Okay. And four might be pushing it. Yes. Okay. Any more questions? Yes, set it back. And what if you want to combine the functionality of several mixins? What's the recommended way? Like extending mixins, subclassing mixins or compositing mixins into one big mixin? Always favorite composition over inheritance. But I have seen use cases where mixins were actually extended. So if you look into the source code of Django braces, they have one kind of base. So they have a base mixin for their access mixins that is doing some of the basic stuff and then all the others they inherit. So you can do that. That's pretty valid, but just be careful. Yeah. Combining them via composition, I'm not sure how would you do that? So can't really give you an advice. More questions? Everyone's hungry. But I don't know if they start serving food now. So we might have to wait 10 minutes anyway. Hi, thank you for the talk at first. I was before in the decorator lectures and they were talking about how to use decorator, how many you can use. And you can use also decorator for classes. I guess it's a bit different from mixing because it's modifying the class attribute. But the speaker also was talking about meta classes. And I was thinking how it's the relation between meta classes and mixing and what it's good to use mixing for and what would you use meta classes for if you have to use it? I haven't used meta classes for creating mixins. So I can't really... So can I echo your question? How would you use meta classes if you're creating mixins? Or was... Instead of using a mixin for adding a small method or functionality to a class, like using having meta classes and redefine all those classes already with global or more broad numbers of methods for views or something. Maybe I'm completely wrong in this question. I don't know. Yeah, I don't know much about meta classes. So that might be also a problem. Yeah, so I definitely should take a look at this talk and learn actually about meta classes. But I'm not sure that in meta classes you can do the same stuff. So yeah, definitely you can have some of your functionalities separated into meta classes. That's what basically Django is doing. So we have meta classes for a set of functionality. And then we have extra placed into mixins. But I gotta try. Maybe I can put all this code into meta classes and it will work. No, no, no, okay, no. Just no. Thanks for the talk. Are mixins also used and are also popular in other contexts than Django? If you have any of the additional models which are outside of the Django core components. So if you're doing models, you don't have mixins. Obviously if you are, so we have the template layer, the view layer and the model layer. So the view layer is the only place where I could see mixins. But then you can have extra logic, extra modules where you can use mixins for your ordinary Python structure. So I can't give an exact use case but you might have the need to use mixins but that's going to be already outside of Django. Thanks. I can actually add something on this one. If you do forms, it's quite common to add a mixin to do date pickers or these weird things. Good point. Thank you. And more questions? Right, so maybe we can go to lunch and please thank you again. It was very good. Thank you.