Merken

The Magic of Attribute Access

Zitierlink des Filmsegments
Embed Code

Automatisierte Medienanalyse

Beta
Erkannte Entitäten
Sprachtranskript
right
elimination but they are so I'm sure you're all familiar with the operators in Python not all of them are as interesting as some of the others but the most interesting 1 of always the smallest so little and did and
I'll be diving into the depths of the dot operator and now as you know quite non-hazardous giants standard library
where the doctor is so the best separating so you have some parents module and you get some child out of and this is a different use of the dog the now be speaking about it it's it's a case where the
doctor who does some kind of a namespace so what I will be talking about this attribute
axis so the 3 things you can do with the dot is set
and attribute on an object get an attribute out of an object and doing the actually innocent I hope you all know now these are some of the most optimize operations in Python so it's very good to use them up but you always know that you have to know the name of of the other getting if you don't know it you can use the built-in functions etc. get out of died which actually do the exact same things estimates slower not to understand what the doctor as we'll introducing this very simple approximation of what an object is and I thought so if you have an object that has a type which doesn't change very often and it defines the behavior of and then you have to date which contains all the data data specific to to that 1 instance and that's expected to change quite a lot of of course there are are always exceptions but will go with this simple model so as an example I I have some class where I define a methodology that gets put in the time and then when i define an attribute on an instance of that object the attribute goes and the date and the date is under the hood just a simple dictionary invite from 3 it's more than a simple dictionary but it's acts like 1 and then I want to get the yet-to-be-announced I just use that again and by in the lake and if it doesn't find the attribute and the bigger than it looks on the type so I can also get the get area methods which is not not in the instance so here the simple rules when you said that actually that goes directly to the date when you get the hat review it and you try and the data the driver type and if it's not there then fail and most of this stuff will be about uh how to make this 1 somehow differently so the 1st there are things you can do to override this behavior is not included special get that method on the type of what this does this is hoax induced a 3 year and instead of failing by the way this function is called a it's called and whatever and returned it's returned as the
value of the of so this simple class proxies or let access to some of the objects this works it has some limitations for example it won't so that form so work on attributes that are already in the data so you if you ask for a underscore of object here which is already said that they get out it won't be called and there is another method you can do which is get an attribute has
has a longer name and and it's more powerful than this 1 actually takes over the whole contributing getting process so it's a bit more difficult to use because if there's any attributes you already have on the object you have to we make a special case for it otherwise he can do anything you want and this function in a
way now that's getting out of its there's 1 more thing you want to do and that's something that and for that we can have a set out of methods so what this class will do this it keeps a dictionary when you try to get an
attribute from the object it looks in the dictionary and returns whatever it finds it if you want to set an attribute it also looks in the dictionary and well it's since the attribute on the dictionary as you can see a special case and the date because I'm setting the date here and I don't want to said the date that when we use the link that's not so already we also have the deleterious which does deleting attributes it's the same if you have time to read it I think most of you know looking at me so all yeah during schools
but the question is do any of these hooks run during in uh there on every time you set an attribute and by found so if that in and has attributes setting done yet and it is just a function that gets called on the beginning it's there's nothing 2 special about and so I I have to specialists special case this for the setting here and
now if you ever have find yourself writing something like this think twice because they have to be namespace is not entirely under your control you have attributes like thunder anything you'll inevitably want to add some methods to your class you you'll want to enable subclasses to add new attributes so usually when you have something like a dictionary stick to a dictionary interface and don't mess around with the attributes otherwise you'll run into trouble pretty fast uh yes so I I haven't seen this
many times actually because this sort of blankets overriding of getting a sitting at tributes is not that useful but usually what you want to do is you have 1 attribute that
some kind of special treatment or you have several but each 1 is special in its own way
so if you didn't get either you would have a nasty tree of if and it's it's not very nice so for this Python has a very special feature called
descriptors now what descriptors do it is you put a special objects in the which will control access to the specified attributes so if I have some fun square and I wanted to have an area I put some kind of magic special objects into the class and when I said the side there and then I look
at the area attribute this descriptor will takes the scientists from the this five-year squared and given that give them that this is pretty easy to implement the descriptor object only needs 1 method which is yeah so
double underscore would this method to get is the instance so that would be the square here and the instances so that it can return the value of the of the Indian sense not so that means we're getting at the attribute from the class itself so that's the you see on the bottom here in 1 of the most well behaved descriptors do is straight the descriptor itself so you can use it for some other reasons for things that Clinton just how special object to control access to and from now what
what the subject can also do is controlled setting so
if you in user method status gives the instance and the value of the users trying to set is free to do anything it wants my case we want to update the side because the user said an area to something so we can I only the site then so anybody having trouble reading them it's
not going and the last thing there is is delete the shore Dell was already taken so it's longer this 1 isn't that useful because you don't find yourself deleting attributes all that often but for completeness it's the now a bit of terminology has uh when a descriptor has this
set method is qualitative descriptor if it does not it's called a bonding to descriptive this is so this this set means that pretty much you want to control all access to the yet to be if you only have get just just getting that out if you have said means there's some data are you presumably you want to store in that attribute so that's later called of the data is now how many of you know the property decorated almost everyone yeah so
as you can see a pretty much gone the long way to do something like the property decorated and in fact the property decorator all it does is create a descriptor can actually implement property in pure Python has a description and just give it to 3 functions and call them in the appropriate special methods like example here so I have a set theory
of get to the underlying reality give these 3 functions to the property and without an area you can actually call their bills and property like the that will do the right thing if you have some more sugar to this class and you can clearly reimplement all the mechanics of the properties and again this so it's indeed descriptor at the on time yeah so by the time actually likes descriptors very much and any time there's something special to do 1
attribute access you have the descriptor for example if you look at a simple function the the
look at the attributes and ask 1 of them is gets because functions themselves are descriptors when you have a function on the class then and then you have an instance of the class you want to get the function you don't get the function like you get a method it an object that has the function itself and
the self argument and so it
is a very simple class with a very simple function is and no when you get there when you get the attribute from an instance of that class you get a bound method if you call that it automatically provides the self argument and if you get line from the class it gives you the original that crater uh the original
functions as I said most closely at descriptors 2nd themselves when you get them from a class in Python 2 you would get something called an unbounded method which doesn't really do anything that useful but it's their bounding the sort of fixed it so it's just gets the the function that I feel it closely to the
different this descriptor which we have yeah it's it's pretty much the same way that's something special when you get the thing from the instance when you get it from the class the retains the descriptor itself right you another thing I want to talk about is this little trick for saving memory if I had point class and I had millions of these objects around I wouldn't want of each of
them to have to state actually which as I said is the normal state so it takes up memory and I know that in a point I will only ever have an X number and Y number and nothing else so what this special magic incantation will do is it'll actually maybe the
type not have the data to be it'll have the title and it'll have directly the x and y and the see object itself so there will be no dictionary and it'll save memory you can of course said and get the X and Y and attributes but you cannot send anything else because there's no space when the object for anything extra thank and if you try to get x from the class you get the descriptive so every every time there's some special
attributes Python implements the descriptive right and I think now is the time to give you a the whole magic formula so this
is the way has an attribute it's gotten from an instance 1st he tried get
out of it if there is gets active you just call it and get back if it made if it was an error there is raised if there is no get attributes you look up the attribute on the class and if it is indeed data descriptor then you call get method and which only after that only after looking for the data description of the dataset so the value is governed directly from from the instance attributes and this doesn't calling descriptors you just get the value straight back after that each of the 92 descriptor well where you check if the descriptors nominated and
that's the case then you call that if it's not a descriptor at all it doesn't have to gender get method then you just returned directly so if on the class I have some value 1 no a class attribute constant for example it's just written directly after that people like to get out there and if that is also not there then have to be generous race now that there is this weird thing about the data description not data being in 2 different places what this allows this if you have a data descriptor pretty much controls all the
access to the and so with the Python designers thought is that if you define both get and set and you probably want to control the access to that attribute yourself and if you don't define the set they have freed you override that attribute and the instance so you can put something in the data and then since it's not data descriptor you will get get it back from the day before the descriptors change make there a fine nice use of it
in the pyramid framework it's called Raiffeisen famous colored cash property of course I've heard it called lazy properties so what this does is so you give it a function and then when you get the corresponding attributes the the function is called and then the attributes with the value of the you've computed so calls the function outputs the result in the in the data and
whenever you get the attribute against it doesn't call the function again it doesn't go to the descriptor just returns the cash value from the that so this is a way that if you yeah if you want to implement laser property there's some discussion about adding this to the standard library and so that maybe you will see under some name stare anyone
who who doesn't understand excuse me on that if you want to invalidate this you just remove it from the data yeah you just delete the out of it the mention is that you can just said the attribute normally now if if you would know the name and advanced this would literally be instance top 9 people's about and the setting is not affected at all with with this descriptor so if you want to change the value in the data to just do it normal the only thing that's different is getting and that's the only when it's not already in the it the questions on this so we according to this 1 OK but what the I'm not finished was from yeah yeah if you have a general question that and just like OK so another
thing about this magic formula is this on class which I put in italics because it not easy as it looks at because looking up something on the class of an instance is not and actual actually it's a bit different and it
has to do with something called the method resolution on so if you have a class and you have a subclass of that you can check for the method resolution order and it gives you the child and the parent and the object now when you look something up in the class so it goes to the classes in the cell so the actually it would be defined and child it would be returned from the child if it's not on the child by Python and parents if it's not there by and the universal superclasses have you have some kind of weird hierarchy of classes with multiple inheritance and stuff like that there's an algorithm called I think 2 of which he look up there's which converts this
hierarchy to assume list that's check linearly and 1 more thing about this is a model it's actually an attribute defined on the metaclass I don't know if you familiar with that that's is defined on on other the on the tight metaclasses and if you have an instance of the object that doesn't show up because if you have an instance you only check the instance itself and its class not metaclass so this is maybe you a useful way to hide things from instances if you need
them all the time just put in my class and if you don't know what metaclasses I'm sorry I don't really have time to explain I think that's it the
implementations
few
things that you and we will almost 8 minutes for questions so please raise your hand and I will go over microphone hi thank you very much for the inside really really interesting and 1 thing I actually soul button which was quiet uh in quite a thing was the fault the the salt such as how do you compare this to of name toppled and what are the that I the same with the advantages are compared to the name toppled
but then what we needed trouble are mainly temple is
actually used to the differently the main temple is immutable and the 1st thing and the 2nd thing commendable has order and the attributes so you can actually use it
as a temple here you don't don't have order so use whatever makes sense in your case that if if I wanted to and for example iterator around this lawmakers and integrated I could really do that with name temple since that's already in energy trade what uh can I recall that the script calls for sample right from get should what know about so we can work on that this this crippled all get the actual mobile well you can return it but it won't get method 1 we call could you can actually call the get method yourself that's that's not a problem but it only called if you just return any more questions what is actual there's 1 and sorry the slides and that you you implement there with the area descriptor could perhaps just as easily or possibly even cleaner really be implemented using the straight properties in that it's it's stand in line in 1 spot nities to find what what real world examples you have all of where descriptors are actually useful encode that they add more than they they take half of how I've just seen the news before and that effectively they could've been implemented in other ways but now the descriptor class because of separate it involved a lot more jumping around the call to try and follow the logic of what's going on yes if you just have a simple case like I have here is that it is property you can have 1 thing I took from this slide from the from the top because of time reasons actually examples of more complex descriptors up if you have a forum like say sequel alchemy that uses descriptors along it's because the descriptor is a class in itself so it can cannot other behavior it and just getting and setting you just controlling actually access for example in sequel alchemy you can the you can do operations with the descriptor which is a column the database and it will generate the sequel statement right and if well if you use it on the class is generated the sequel statements that use it on instances against the data of the call and so there are yeah in simple cases it's better just these properties which is also descriptive just a simple 1 in complex when you need some more stage of functionality built into the descriptor then user a class and you can when you have several different several related attributes like that you can just create the descriptor class and users but yeah I I agree that the code is not as readable as it could be 1 use descriptive because there's 1 more place you have to check but it's magic use it wisely and I think this was the perfect conclusion for this talk things again reject you
Nichtlinearer Operator
Rechter Winkel
Code
Attributierte Grammatik
Eliminationsverfahren
Sichtbarkeitsverfahren
Nichtlinearer Operator
Element <Mathematik>
Vererbungshierarchie
Programmbibliothek
Attributierte Grammatik
Ideal <Mathematik>
Computeranimation
Standardabweichung
Dualitätstheorie
Element <Mathematik>
Minimierung
Mathematisierung
Klasse <Mathematik>
Parser
Computeranimation
Informationsmodellierung
Proxy Server
Datentyp
Ideal <Mathematik>
Attributierte Grammatik
Umwandlungsenthalpie
Lineares Funktional
Nichtlinearer Operator
Namensraum
Approximation
Datentyp
Schlussregel
Ausnahmebehandlung
Objektklasse
Menge
Objekt <Kategorie>
Druckertreiber
Diskrete-Elemente-Methode
Flächeninhalt
Attributierte Grammatik
Quadratzahl
Instantiierung
Objekt <Kategorie>
Lineares Funktional
Proxy Server
Bit
Bildschirmmaske
Prozess <Physik>
Proxy Server
Klasse <Mathematik>
Inverser Limes
Vorlesung/Konferenz
Objektklasse
Attributierte Grammatik
Objekt <Kategorie>
Vererbungshierarchie
Klasse <Mathematik>
Vorlesung/Konferenz
Binder <Informatik>
Computeranimation
Attributierte Grammatik
Lineares Funktional
Namensraum
Menge
Vererbungshierarchie
Klasse <Mathematik>
Vererbungshierarchie
Gamecontroller
Schnittstelle
Data Dictionary
Attributierte Grammatik
Attributierte Grammatik
Quick-Sort
Computeranimation
Objekt <Kategorie>
Datentyp
Quadratzahl
Flächeninhalt
Klasse <Mathematik>
Flächeninhalt
Quadratzahl
Computeranimation
Attributierte Grammatik
Objekt <Kategorie>
Datentyp
Quadratzahl
Klasse <Mathematik>
Minimum
Flächeninhalt
Quadratzahl
Objektklasse
Computeranimation
Attributierte Grammatik
Instantiierung
Web Site
Bit
Vervollständigung <Mathematik>
Objektklasse
Menge
Computeranimation
Kreisbogen
Metropolitan area network
Flächeninhalt
Flächeninhalt
Reelle Zahl
Quadratzahl
Instantiierung
Attributierte Grammatik
Arithmetisches Mittel
Deskriptive Statistik
Kategorie <Mathematik>
Mengenlehre
Implementierung
Objektklasse
Menge
Computeranimation
Attributierte Grammatik
Inklusion <Mathematik>
Lineares Funktional
Kraftfahrzeugmechatroniker
Chipkarte
Kategorie <Mathematik>
Klasse <Mathematik>
Gasströmung
Computeranimation
Metropolitan area network
Flächeninhalt
Flächeninhalt
Bildschirmsymbol
Ideal <Mathematik>
Große Vereinheitlichung
Attributierte Grammatik
Logik höherer Stufe
Objekt <Kategorie>
Parametersystem
Lineares Funktional
Klasse <Mathematik>
Computeranimation
Instantiierung
Parametersystem
Lineares Funktional
Funktion <Mathematik>
Klasse <Mathematik>
Punkt
Objektklasse
Quick-Sort
Gerade
Computeranimation
Attributierte Grammatik
Instantiierung
Punkt
Klasse <Mathematik>
Zahlenbereich
Vorzeichen <Mathematik>
Objektklasse
Computeranimation
Objekt <Kategorie>
Festspeicher
Flächeninhalt
Punkt
Quadratzahl
Instantiierung
Aggregatzustand
Objekt <Kategorie>
Datentyp
Rechter Winkel
Festspeicher
Klasse <Mathematik>
Datentyp
Attributierte Grammatik
Punkt
Objektklasse
ROM <Informatik>
Raum-Zeit
Ausdruck <Logik>
Attributierte Grammatik
Deskriptive Statistik
Fehlermeldung
Instantiierung
Attributierte Grammatik
Konstante
Deskriptive Statistik
Menge
Klasse <Mathematik>
Datenerfassung
Attributierte Grammatik
Instantiierung
Attributierte Grammatik
Resultante
Lineares Funktional
Kategorie <Mathematik>
Programmbibliothek
Implementierung
Gravitationsgesetz
Objektklasse
Framework <Informatik>
Computeranimation
Attributierte Grammatik
Menge
Klasse <Mathematik>
Objektklasse
Ausdruck <Logik>
Instantiierung
Attributierte Grammatik
Klasse <Mathematik>
PASS <Programm>
Bildauflösung
Hierarchische Struktur
Zellularer Automat
Mailing-Liste
Objektklasse
Computeranimation
Objekt <Kategorie>
Multiplikation
Informationsmodellierung
Algorithmus
Vererbungshierarchie
Ordnung <Mathematik>
Ordnung <Mathematik>
Attributierte Grammatik
Bildauflösung
Instantiierung
Metropolitan area network
Datentyp
Machsches Prinzip
PASS <Programm>
Attributierte Grammatik
Implementierung
Information
Objektklasse
Computeranimation
Klasse <Mathematik>
Iteration
Fortsetzung <Mathematik>
ROM <Informatik>
Mathematische Logik
Code
Computeranimation
Deskriptive Statistik
Webforum
Reelle Zahl
Stichprobenumfang
Skript <Programm>
Punkt
Gerade
Attributierte Grammatik
Nichtlinearer Operator
Lineares Funktional
Befehl <Informatik>
Datentyp
Kategorie <Mathematik>
Datenhaltung
sinc-Funktion
Systemaufruf
Rechenschieber
Energiedichte
Flächeninhalt
Rechter Winkel
Attributierte Grammatik
Decodierung
Ordnung <Mathematik>
Instantiierung

Metadaten

Formale Metadaten

Titel The Magic of Attribute Access
Serientitel EuroPython 2014
Teil 27
Anzahl der Teile 120
Autor Viktorin, Petr
Lizenz CC-Namensnennung 3.0 Unported:
Sie dürfen das Werk bzw. den Inhalt zu jedem legalen 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.
DOI 10.5446/20015
Herausgeber EuroPython
Erscheinungsjahr 2014
Sprache Englisch
Produktionsort Berlin

Inhaltliche Metadaten

Fachgebiet Informatik
Abstract Petr Viktorin - The Magic of Attribute Access Have you ever wondered how the "self" argument appears when you call a method? Did you know there is a general mechanism behind it? Come learn all about attributes and descriptors. ----- The first part of this talk will describe what exactly happens when you read or write an attribute in Python. While this behavior is, of course, explained in the Python docs, more precisely in the [Data model] section and [related] [writeups], the documentation gives one a "bag of tools" and leaves combining them to the reader. This talk, on the other hand, will present one chunk of functionality, the attribute lookup, and show how its mechanisms and customization options work together to provide the flexibility (and gotchas) Python provides. The topics covered will be: * method resolution order, with a nod to the C3 algorithm * instance-, class-, and metaclass-level variables * ` dict ` and ` slots ` * data/non-data descriptors * special methods (` getattr `, ` getattribute `, ` setattr `, ` dir `) In the second part of the talk, I will show how to use the customization primitives explained before on several interesting and/or useful examples: * A proxy object using ` getattr ` * Generic desciptor - an ORM column sketch * the rudimentary `@property`, method, `staticmethod` reimplemented in pure Python (explained [here][2] and elsewhere), which lead to * SQLAlchemy's [`@hybrid proprerty`][4] * Pyramid's deceptively simple memoizing decorator, [`@reify`][5] * An ["Unpacked" tuple properties][6] example to drive home the idea that descriptors can do more than provide attribute access (and mention weak dicts as a way to non-intrusively store data on an object) (These are subject to change as I compose the talk. Also some examples may end up interleaved with the theory.) Hopefully I'll have time to conclude with a remark about how Python manages to be a "simple language" despite having these relatively complex mechanisms.
Schlagwörter EuroPython Conference
EP 2014
EuroPython 2014

Ähnliche Filme

Loading...