Merken

Using and abusing Python’s double-underscore methods and attributes

Zitierlink des Filmsegments
Embed Code

Automatisierte Medienanalyse

Beta
Erkannte Entitäten
Sprachtranskript
I I'm 190 hello of everybody's enjoying the week so far I I don't about you guys but I've seen a lot of slides this week so today I figured I'd do something a little bit more experimental no slides and I'm just going to show you some some code of some really really silly little code examples please do not take them seriously don't write code like what I'm going to show you today but my hope is that will illustrate some of the funds special Dundar or double underscore meant here but which are also called special methods magic methods but I like the term done the best column Dundas and then as I mentioned I put up all these examples in a little repo of aculei slashed under and what I'm hoping is that and at the end of the talk to have a couple extra minutes to to discuss with you guys that like to do this more interactively and if if people have other than the tips and tricks that I am not able to cover because there's too many wonderful things that fit into 20 minutes I'm I would love to have people discussed and afterwards and possibly even after the talk if you can contribute to this add stuff to the Wiki Open issues start discussions and if you have fun little code samples that you want to add up and there's a there's a directory you're sharing is caring where you can put in whatever you want know about the on off of it and self that's what I'd like to do today because Dundar methods are super fun if you ask me so I know what are the Dundas well there these special method that had to be surrounded by double underscores which is why we call them Dundas and some of them are our best friends right so everybody probably uses Dundar in it all the time it's obvious construct map so here I got a custom class college stringy and and it's going to be a weird kind of a number I'm I'm constructing it with this thunder in and I'm giving it an attribute called value and added under everybody brolly is already super from the with Dundas straw maybe is a better way to pronounce them and where we can have whatever kind of string representation we want usually it's just like the value of the object but this one's going to be more exciting can I have the again so was this is why you should never lie further presentation so therefore we around this little module that we get to use another down there that super fun which it is this beloved if done their name equals under main block which as you all probably know it is run only when you are and when you run the on module itself and not when you imported into something else so that's cool let's run a little interpreter and and I have set up some streams here so we've got 1 is a stringy and object and 2 and 3 awesome and if I print them and that that might undisturbed them at I have fun string representations and and so and other than the that we all probably know and love is the what is giving me this year depends on ED object the looking a string representation here and that's upper at which if I am comment this here is supposed to be another tapestry resentation that's more at the code object itself but more unique to the objects and the interface understand how to be more boring and just out of print the string of the value and so we can see that when we with this and do it again now that now what it evaluates 1 it prints out just the values so I don't have to look at all this gobbledy-gook addresses and whatever OK so far so boring we all probably know these know love these Dundas what about other fun stuff so when I have regular integers I can like and then Emerald wine and that's because of some of the the building and object has these fine operated under its like thunder ad and under
model which are used by the plus and the star asterisk operators to perform these mathematical operations and I can overload them in my own classes by just implementing these methods super cool self uh let's see here what happens now and I have my 1 and my 2
and it usually if I add 2 integers together again you know reasonable things like 3 but if I add my stringy together it's giving me an integer that's just merging them together like strings this is completely useless class you probably don't even you don't want anything like this but the point is you can because pattern and so on what if I want had a Estonians to regular and doesn't work the operand type is not supported as because it's looking for a dunderhead function on the integer to the left of the plus operator that works with a stringy and object and it doesn't find 1 so if it if it tries to find the under method on the left hand side object but doesn't find something that works for the for the right hand side object from Python will also try looking for are these thresholds our methods which are
like of these are opposite implemented for the right hand side objects like for example the undergrad which is possibly the best named method in the world so this 1 will be called on the right-hand side object as sort of all that if you can't use the the regular agenda and on the left hand side of so now I we can see
that if we try uh 1 plus 1 and a half it works now we can change anything about the built-in and so on but we use this thunder rad and a super rat and sorry I can't help myself again OK I 1 of the and operator that is a little bit different is this people
equals right we all know and love it 1 is 1 and and the string and 1 is itself but we would be cool if we knew that those 2 things were were similar somehow so I can do that by implementing Dundar and there's equivalents for all of you know less than and greater than etc. etc. but in this case I'm gonna try to make it work for anything that I can into 5 so again don't write code like this is just an example so now known if I try of a 1 is still itself and my stringy 1 is still itself and now hopefully from direction a hot now it knows how to compare these 2 different types so I am vivid under each function also is but its special because it also used um for for example making objects of a hashtable so they can be used like as he's in a dictionary so if I have a dictionary D right now if I wanna make an integer a that's no problem we do that all the time but if I wanna try using my chemistry and uh it said 0 no it's on hashable well we can fix that of course wouldn't under called the and if I implement this thunder hash function what I wanna do is return a unique hash value for for whatever it this object is on in this case the minute you kind of a really silly 1 which is just returning the
the integer value itself ideally you have something better than this 1 but the important thing is that you don't want to implement this kind of thing on them an object that shouldn't be hashable like a mutable object you don't want that to be Acuna dictionary but these are not mutable so I can use that so let's see now if
I have my dictionary the OK I can still use my regular are integer keys let's try now uh 0 over at very a half OK so now I've got and and it's not complaining about the possibility and because of my Dundar river function it's it's difficult to see this but if I do for end the year the it really is harder type when you have period let's print the type of each key obviously about 1 and a monastery and so it's working so we can now use this new custom type as possible to predict I write them 1 other thing I want to talk to you about with the stringy and it is a fun little than there that's an to be actually not a method which is done the slots I am so identified to the bit different but when I have an object like a vast amount of usually I have some a dictionary and under underdamped that stores all of the attributes for that object so that's what allows me to do like 1 not value and get something out and if I assigned something new to the objects I if I look at Derek a C a high got added to this dictionary it's it's just a regular dictionary you can mess however you want but I am the thing is that dictionaries take up space and so whenever you create a new object by gives you this standard uh for all the object attributes and it might be the case that for an object like stringy and you know that it's never gonna have more attributes and value it's only going to have that 1 or maybe you just have a small set of activities and if I'm going to be creating like millions and millions of stringy and creating all those in the under that dictionaries could take up more space than I wanna use it takes up all the little bit of time so what I can do is use this declares Dundar slots and name how all of the attributes that I want on my object i in this case it's just value am and what that does is to prevent the dictionary from that under Dick dictionary from being created so if this is right here if I try
now accessing the that directly i doesn't have 1 that is still have its value it does indeed can I have a new attribution I no I can add extra attribute so it's basically constraining the the size and shape of this of this object in a way that if you're in if you're creating the Jillian's of objects that might that efficiency might actually come in handy so I got under sort of pretty cool when I heard about it earlier this year I right arm itself I had the time flies when you're having fun with Dundas there are a lot of other funders that we can use to
make I like container objects for example where we already saw how we can make objects that are kind of similar you know like numbers numeric types but what if we want to make things that have come content so for example let's say I wanna make a list but finalists really boring because you know when you have things to them you can things you know they're going to show that the and then when you index things you know that you're going to find the right objects for the right and that's what we want a crazy last whereas there's just an element of randomness so in this case I've made a silly little object called crazy list which and a my under in it I got my under reparandum adding a little append map that just because all good list 1 but instead of you know pending things to the end of this self dot values last I'm just going to insert them at a random because why not and so again I'm using my dander name thing in year 2 run some code right when I run the module see here alright so about an L
objects and it's got some elements in I wanna find out how long it is 0 no it has no length that's not good at what should I do probably use it under In this case the 1 I want is done their land this is what called by the built environment that's a lot of the built-in methods that may find the we we're used to using our super beautiful paper on they depend on these Dundas and 1 really simple 1 is to underline and so in this case instead of telling you actually how long the list and I'm just going to sort of give you a random number that somewhere in the vicinity of its length super useful right I hope you guys notice the word of using in the title of this talk so now if I tried to lend my object hot it gives me a completely wrong number but at least it gives me a number 3 OK I so there's another let's see in advance that the head here but what if I want to do for I am in my name list uh you know print spider 0 no it's not that's not bad how do we think that we think that we're that under the social In this case
and then the area kept under ball here that's used for like if l you can get the idea but then the air is probably more important you're trying to make some kind of sequence object or something that you should be able to use in for loops and that sort of thing is want to implement this and I and how it works exactly the little bit more complicated than so many other than there is but a in this case I'll just point to the documentation of a running out of time and and in this case i'm just gonna kind of yield a random element from the latest in a completely wrong a range of of of the number of elements that may or may not be in my last so really useful the underwriter function here but hopefully you get the idea so now let's
try to do our for iron hello Brent I I OK so I have a little thing here that shows when under is getting called a couple without for live and it's doing something really useless which is not only the printing the wrong number of items but it's also just printing question sometimes against mystery but the point is that we can use this now in for loops so if I wanted to define a really super useful Dundas during method that uses a for loop to print out all the things in the in the last OK what about so usually analysts like l I wanna be able to get you know a certain elements by using this bracket notation but it doesn't support of only it did if only we had implemented thunder get item which lets us and pass an
index or or a key to these brackets for object arm and soul depending on whether you want your object to be indexable using integer indices for you wanted to be like exceeded right like a dictionary you can define this method to let's say look for a certain type like only integers or to to just handle anything which is what I'm doing here is i'm not even caring about what the key is really of the index I'm just gonna accept it and just give you a random item from the list no matter what you asked me for so no I have my own if
I want a certain index gesture whatever yeah it's totally working great and what if I want to try to access it as if it were a dictionary share their problem that will just give you random things from the west the point is if you were to make it actually useful than get item at that then become part of and you got a dictionary or an index of all sequence whatever you want OK and it also add understand item for the equivalent which you can imagine 1st for setting up a certain item at a certain index or and setting the value of the key OK I'm 100 under that I wanna talk about with containers is Dundar contains so I
am if you have a of an object where you're going to be wanting to test for membership like you know if x is in L them if you don't have under contains implemented what you'll see is if I do that let's say I want see if 2 is in hell if you don't have that contains and wondered it's actually gonna use that under it and go through everything analyst and see if it finds um something with this something in there that's the thing you're looking for that can be a bit slow depending on various features like for example how far it was the beginning of the list of you the item you're looking for it so if you implement under contains this can be it doesn't need to be that can be and a faster way of testing for that membership so depending on what your use case is if you need something that you can really quickly
decide whether or not something is a member of like a set let's say I'm Dundar contains can be a good idea so now we see that if I ask OK is 3 N see how might underrated didn't get called that little print statement there it's using Dundar contains 1st OK FIL a crazy less that's completely useless but nevertheless showcases the magical containedIn 1 last thing I wanna show you and it's a problem that there are some fun function Dundas self
and I have a little function here all add its super boring it just adds to things famine X whatever but because is magical since I have this uh docstring in here I can if I ask right behind help me out with it tells me OK cool the contents of that that docstring and information about the the function itself sweet and when I had 2 things that you know it does where the function so as to deal but what if that's not cool enough for me and I want to have my little function on the fly so this probably something you should never ever do but if you were a
cat you wouldn't care about adding 2 numbers together you would want human to give you more to so what I've got here is a little function which makes use of some fun function object Dundas Dundar doc which contains the stock strength I'm going to change it to something more task-specific and then the code which is actually the cold object the content the functionality of your function you can actually mess with that you can replace it to be for example the contents of another function called more to not which instructs the human to give more to so now if I had if I have my regular had function of
a had still period and it still works great if I now modify it and I tried had 2 things together it actually changed the functionality that's attached to this ad name and similarly the docstring is different
and useless but this is something
you probably don't really ever want to do but the important thing is that you should know that you can and so if you ever see this kind of messing with going on to be really careful alright last thing of where time for 1 more than the the the wind keyword works with 2 special Dundas called Thunder enter and then the
excess and this is what allows us to define the context manager so basically what happens is the this Dundar
enter map that is called whenever we enter with block and it can set something up for for us like for example if you use like with open file right it'll it'll do something like reading the file object and when you exit the with what it calls this Dundar exit method which can do something useful like closing the file object in this case where and how do something less useful which is it's connect-cachify a function on the enter that under under and it's gonna uncodified a function by replacing the original Dundar code and ended up with the boring human code and the boring human docked on that under exit so what we should see here it is that's now if I have my regular function and
it works but if I do with cats in charge of bad and then I try to add 2 and 3 I'm and let's do something else to you let's say let's just call the help and what Saturn foreign 5 and 6 short so what I'm doing on there that under enter it can find this function so we should see that any ad calls I meet in the middle of this what are the codified version but when I exit it and sending it back so any ad call they make after this book should be normal again and just because maybe you guys want something that's actually a tiny bit useful out of this talk but I'm also putting in a timer here so I'm timing when the cat rain begins when I go into the vendor enter method and then I'm I'm a lot in the time of when the cat brain ends when I leave in the Dundar exit method and I'm printing out how long the cats rule 2 for so this is an example of of something you might actually wanna do is write your own and timer for example to to time an arbitrary block of code OK so let's try out OK so we called the help of and it's now out and we saw that
it called add twice and actually using the the numbers of the arguments to determine Ghazanfar here and then it told me how long it took and of the how long the cats were in charge so just a little example of something that you can do with these context managers depending on what you're trying to decode it can be really useful the pair of alright so that all I wanted to tell you about the Dundas that I find cool I would love to hear now if people have other ideas for Dundas you find cool and just before we kind of open and up to everybody I'm I just wanna perhaps point out that the um the documentation for the
pipeline data model has information about all kinds of vendors that you could possibly want to know and so if you're curious that any of these yet check that out right when he has rank vendors to share that the 1st 1st thing thank you for talk if you overwrite than the old a module then you overwrite what can be important so you can just say I always just these 3 functions OK gender all of my this thing but that sounds really awesome so if you if you underrate all you can right what's important in the module of what can be imported from the model that school so that's something I should be able to access right here like that try no is it something would be in the vase like in the I've only ever written at the normal vector where we have a anyway if you put it in your marginal is anywhere should be at a list OK so far I wanna say that only you can only import Kattophile I get what I did I gotta wanna use the the object itself OK that the order matter they need this kind of IT to converse OK week let's see at so if I know it's sorry this is what would happen if I import from that OK so let's try an imports From stratification and then import that had it should work right of the world effects are area so if I do from clarification import star then had should be a hot the cat the bank cool thanks the anybody else wanna share stuff yeah coolest if I whoever just mentioned that could like when a node in the wiki you're on and add a little example at the 3 any to anybody else wanna share something but it if you're looking for for doctors that you can do with the increases things what's the wanted to are we all want to look for is done New than any of its which if you want to do decreases things you normally would do would be return your your objective source but you can return whatever you want so for instance if you return the integer 42 instantiated your costs we get to the integer 42 it sorry by around if you if you in your garden you in advance I should put the 42 but the and and associating the source we get to the integer 42 the north users about cost of SOA by in my history and if instead of um an integer I want that whatever editor I wanted I just want always be answers of life the universe and everything and I could do under new self or whatever it is that of all the values of you do have very early enough the last years at end and you get the value of effect to be like that and I could just returned 42 such the and if I run this I should have um I had like
1 342 exactly 1 other them their goal of any any she did did you do type on on 1 wanted insights in and so tricky thank you yet you get to but that in the and everybody the anybody out so something so if I'm really useful this is usually Python 2 and you have to color you catch there was vital to sort of you can you can use the called sorry that number missing here it is the thunder missing you get attached out of the tree in 5 lines of code so we say that again media forcefully did hear it from the cherry and implement are done the amusing yeah whatever on item is not fun you can specify function and that's cool way to implement a such often so like I imagine I would also be useful for things that you want like default values like like a default vectors and with our very cold under missing yet you add that to every other you can implement method goal and the on the goal goal object because function right OK so if I have like an integer should usually be callable of you need to have to be unfair note that new right let's replace it
and it takes for itself right and any arguments can be like this take however many many we want for that work and I don't know and just in a pretty the aid and there's and return I don't know 42 many OK so now if I have 1 OK it's mine my number it's and it's still hopefully experience cool but I should be able to call it it so rate that they're called do you could implement the unbounded below the number of them with you little and move them with the right right so yeah we saw like um somebody getting and setting but there's there's a bunch of other vendors like the leading whatever which you can do special cleanup or what not that you need very close thank you now we are a part timer rhe so I actually do a large break started so the IRA well think everybody for sharing and IF NUI anybody wants you and contribute to my little Dundas rebo I'm hoping that it can be like a conversation starter so go it thank you
Bit
Gemeinsamer Speicher
Klasse <Mathematik>
Hochdruck
Adressraum
Selbstrepräsentation
Zahlenbereich
Kombinatorische Gruppentheorie
Term
Code
Metropolitan area network
Streaming <Kommunikationstechnik>
Stichprobenumfang
Schnittstelle
Attributierte Grammatik
Inklusion <Mathematik>
Gebäude <Mathematik>
p-Block
Wiki
Modul
Mapping <Computergraphik>
Objekt <Kategorie>
Rechenschieber
Ganze Zahl
Offene Menge
Attributierte Grammatik
Repository <Informatik>
Verzeichnisdienst
Zeichenkette
Lineares Funktional
Nichtlinearer Operator
Overloading <Informatik>
Schwellwertverfahren
Elektronische Publikation
Punkt
Singularität <Mathematik>
Klasse <Mathematik>
Extrempunkt
Systemaufruf
Computeranimation
Objekt <Kategorie>
Metropolitan area network
Informationsmodellierung
Ganze Zahl
Rechter Winkel
Code
Mustersprache
Datentyp
Zeichenkette
Objekt <Kategorie>
Metropolitan area network
Nichtlinearer Operator
Bit
Elektronische Publikation
Head-mounted Display
Rechter Winkel
Code
Restklasse
Systemaufruf
Hilfesystem
Quick-Sort
Computeranimation
Lineares Funktional
Elektronische Publikation
Schlüsselverwaltung
Eindeutigkeit
Extrempunkt
Äquivalenzklasse
Systemaufruf
Code
Computeranimation
Richtung
Data Dictionary
Zeichenkette
Objekt <Kategorie>
Metropolitan area network
Ganze Zahl
Datentyp
Hash-Algorithmus
Zeichenkette
Lineares Funktional
Shape <Informatik>
Bit
Subtraktion
Elektronische Publikation
Head-mounted Display
Schlüsselverwaltung
Extrempunkt
Frequenz
Systemaufruf
Quick-Sort
Raum-Zeit
Computeranimation
Data Dictionary
Objekt <Kategorie>
Metropolitan area network
Menge
Datentyp
Restklasse
Gravitationsgesetz
Speicher <Informatik>
Schlüsselverwaltung
Attributierte Grammatik
Hochdruck
Zahlenbereich
Element <Mathematik>
Kardinalzahl
Extrempunkt
Code
Computeranimation
Metropolitan area network
Mailing-Liste
Datentyp
Randomisierung
Vererbungshierarchie
Schreib-Lese-Kopf
Dicke
Datentyp
Elektronische Publikation
Spider <Programm>
Gasströmung
Mailing-Liste
Systemaufruf
Zufallsgenerator
Objekt <Kategorie>
Mapping <Computergraphik>
Automatische Indexierung
Rechter Winkel
Wort <Informatik>
Restklasse
Bildschirmsymbol
Cloud Computing
Programmierumgebung
Lineares Funktional
Bit
Folge <Mathematik>
Punkt
Zahlenbereich
Element <Mathematik>
Quick-Sort
Computeranimation
Objekt <Kategorie>
Metropolitan area network
Loop
Zahlensystem
Poisson-Klammer
Flächeninhalt
Vererbungshierarchie
Große Vereinheitlichung
Gammafunktion
Folge <Mathematik>
Punkt
Gemeinsamer Speicher
Mailing-Liste
Extrempunkt
Computeranimation
Objekt <Kategorie>
Metropolitan area network
Poisson-Klammer
Zustandsdichte
Loop
Automatische Indexierung
Rechter Winkel
Ganze Zahl
Datentyp
Vorlesung/Konferenz
Indexberechnung
Schlüsselverwaltung
Große Vereinheitlichung
Softwaretest
Lineares Funktional
Bit
Befehl <Informatik>
Hochdruck
Varianz
Mailing-Liste
Element <Mathematik>
Extrempunkt
Computeranimation
Objekt <Kategorie>
Metropolitan area network
Zurücksetzung <Transaktion>
Große Vereinheitlichung
Gammafunktion
Objekt <Kategorie>
Metropolitan area network
Lineares Funktional
Zahlenbereich
Inhalt <Mathematik>
Information
Computerunterstützte Übersetzung
Code
Hilfesystem
Metropolitan area network
Lineares Funktional
Frequenz
Computeranimation
Lineares Funktional
p-Block
Extrempunkt
Kontextbezogenes System
Elektronische Publikation
Code
Computeranimation
Objekt <Kategorie>
Mapping <Computergraphik>
Metropolitan area network
System F
Datenmanagement
Rechter Winkel
Offene Menge
Ext-Funktor
Pell-Gleichung
Lineares Funktional
Parametersystem
Machsches Prinzip
Versionsverwaltung
Systemaufruf
Zahlenbereich
Schlussregel
p-Block
Kontextbezogenes System
Code
Computeranimation
Metropolitan area network
System F
Datenmanagement
Offene Menge
Computerunterstützte Übersetzung
Automorphismus
Große Vereinheitlichung
Hilfesystem
Umsetzung <Informatik>
Gemeinsamer Speicher
Implementierung
Zahlenbereich
Extrempunkt
Code
Netzwerktopologie
Spezialrechner
Metropolitan area network
Knotenmenge
Informationsmodellierung
Rangstatistik
Default
Grundraum
Gerade
Soundverarbeitung
Videospiel
Lineares Funktional
Datentyp
Singularität <Mathematik>
Datenmodell
Mailing-Liste
Vektorraum
Quellcode
Wiki
Modul
Quick-Sort
Objekt <Kategorie>
Texteditor
Bildschirmmaske
Flächeninhalt
Rechter Winkel
Ganze Zahl
Geschlecht <Mathematik>
Hypermedia
Information
Cloud Computing
Normalvektor
Ordnung <Mathematik>
Computerunterstützte Übersetzung
Instantiierung
Metropolitan area network
Parametersystem
Umsetzung <Informatik>
Lemma <Logik>
Gemeinsamer Speicher
Rechter Winkel
Mereologie
Kontrollstruktur
Zahlenbereich
Extrempunkt
Bitrate
Computeranimation

Metadaten

Formale Metadaten

Titel Using and abusing Python’s double-underscore methods and attributes
Serientitel EuroPython 2016
Teil 94
Anzahl der Teile 169
Autor Vakil, Anjana
Lizenz CC-Namensnennung - keine kommerzielle Nutzung - Weitergabe unter gleichen Bedingungen 3.0 Unported:
Sie dürfen das Werk bzw. den Inhalt zu jedem legalen und nicht-kommerziellen Zweck nutzen, verändern und in unveränderter oder veränderter Form vervielfältigen, verbreiten und öffentlich zugänglich machen, sofern Sie den Namen des Autors/Rechteinhabers in der von ihm festgelegten Weise nennen und das Werk bzw. diesen Inhalt auch in veränderter Form nur unter den Bedingungen dieser Lizenz weitergeben
DOI 10.5446/21104
Herausgeber EuroPython
Erscheinungsjahr 2016
Sprache Englisch

Inhaltliche Metadaten

Fachgebiet Informatik
Abstract Anjana Vakil - Using and abusing Python’s double-underscore methods and attributes The curious Python methods and attributes surrounded by double underscores ('` `') go by many names, including “special”, “dunder”, and “magic”. You probably use some of them, like ` init `, every day. But that’s just the tip of the iceberg! In this talk, we’ll explore the weird and wonderful world of the double-underscore, and find out how dunders can be useful, silly, dangerous, and just fun! We’ll play pranks on Python’s builtin operators for arithmetic and comparison. We’ll make arbitrary objects behave like dictionaries and containers. We’ll reduce an object’s memory usage, and speed up tests for membership. We’ll even try some naughty function hacks that we should never use in real life! You'll get the most out of this talk if you're already comfortable writing object-oriented Python code. If you already use special dunder magic in your own code, that's excellent! You’ll have a chance to share your tips & tricks with the rest of the audience at the end of the talk. Talk repo :

Zugehöriges Material

Ähnliche Filme

Loading...