Merken

Python idioms to help you write good code

Zitierlink des Filmsegments
Embed Code

Automatisierte Medienanalyse

Beta
Erkannte Entitäten
Sprachtranskript
which is thank you so let's see what
I can talk about whole 1st bit about myself I don't know if you know me Mark Lambert and expanding
Python for quite a long time the minister of really have a company doing a Python projects for customers
and see you architect for Python and consulting training I'm also passing co-developer I am board member of the PSF and board member of the EPS and and business would often Germany so I thought I put
together a chart with some idioms that might be useful for you this talk is basically focused on and people that have just started programming Python and have all these nice things is nice to out there and nice ways of doing things in Python but sometimes don't really know which of the possibilities there aren't they
should use in their code and maybe you want to get some guidance in in writing better code so and what this is the only photograph have in the slides most of the other stuff is
just text there's lots of text on the slides and I can't read everything for you you don't have to read everything I'm going to put the slides up afterwards and then you can download it if you don't want to get more information from it so this is the
agenda quite a few bullets there so let's start with activation time so 1st thing encoding conventions of course you want to know how to actually write the
your code and fortunately in in in Python we have a standard for this it's the have a standard you can download on the on
the presence of our website it has evolved a lot of the beer over the years it's constantly being updated to address new questions that you might have it's written in a way that allows you to write readable code and that's 1 the the I think 1 of the best features and Python that you have that you'd story easy to write readable code it's a guideline it's not necessarily fixed in any way you can you can change things in there if you want to you can build your corporate recording guidelines based on there's some help from a package called pet age that you can run to actually check your code against is that all guidelines and then it will point out various things that you've done wrong you might want to change them so that's 1 thing that you should if we
have a look at 1 thing that's not mentioned in that have a is this little layout of Python module um and I've seen really well not very well structured code in in in Pasamonte is being written by programmers so the the standard module layout that we usually use inside library for example or we use in our program we write this is this 1 3 basic you have a history of of tools section and then you have a body section just going to go through this very quickly you always starts
with the docstring so you put the dot the documentation for years for your model what's it what's the marginal does on a very high level into the docstring start with the imports I usually put the President Ford's 1st and then the 3rd party imports as a 2nd list and then have the application says that this so it's very easy to see where where various things come from your code and then the next section is constants I was put them into 1 section at the top so I can't really see them and then I have goals of course sometimes at least that I need in the model and put them behind the constant so that you can immediately find them if you need them the the next section is the tools section this is basically used for things that you mostly only need in your model there does 1 exception here which is the exceptions section because sometimes these exceptions of course
they wander outside Europe your model and then you want to be able to to see where they're coming from so 1st to define all the the exceptions that you have in your model and then you define the helper functions and defined exceptions both ways for easy each can this subclass the the ones that you have been in Python and then you can have specific exceptions for your model which is helpful especially when debugging because you maybe know where
where you're which model you're exceptions coming from and in the bottom section which is basically the mean of the module you 1st define the functions and then you find defined classes and at the very end you always have this typical if name equals main and execute some main function for example module exit execution part this is running when you import the module and it's only run because you you have this condition here is only run when you import the module at the in the main scope so when you want when you write Python and then modeled up popped up you want then this part is 1 you should not be tried to avoid having executable code at modules scope level so that you don't have any side effects when importing sometimes that's not possible but we should try to do that so this is the view all the red parts here are basically defined your model and that's constructing models if you want to have a really clear kind of approach then of course it's like everything in Python is always use the descriptive names for your modules it should be more or less immediately obvious what the model does this a typical way of doing that in Pozna? usually take the most important class for example that to define a model and you name the model of the class of really told you about the executable code and 1 recommendation I have treated you should always use absolute imports if you have packages then you can also use rows of imports but if you have larger projects and absolute imports make your life a lot easier so you should just avoid the
relative importance so now I'm going to start
exploring from Hi level too low level has idioms it's basically this is just a collection of things I put together I don't have enough time to go into all the various details I could probably talk for a few hours mentioning
everything from this can this game a few things when give you pointers for other things that you can look at the 1st thing I want to start with is common patterns that you haven't heard from any of you know coding patterns like the gallup book for example not that many people so that software patents are basically the things that people have become aware of common things that you you do it again and again when men programming things so there was the Gang of Four Four you know how many years ago many years ago anyway um there's a wrote a book called the um become a book and that basically a lot of common patterns that you find in software design and and these are just come diesel some patterns that you have and present some of them are not not mentioned and come with the most famous pattern in Python of course is the duck typing pattern so it in present everything happens using you need using you always interested in your API you not so much interested in which these classes in this some objects derived from so the the principle behind Dr. thing is if it if it looks like a duck if it's quite courts like a duck then it's probably a duck and that's good enough for Python so it's not like in Indian Java statically typed languages but we actually have to make sure that a certain base can be used and there are lots of little examples of that in the presence of the library the next 1 is the facade or the adapter patterns this is used in conjunction with the duck typing pattern you try to make an object that you have to look like and other objects so basically you you make some for example some bird make them make the bird look like a duck so that you can use it in your code that uses the deck interface this is the 1st part of the adapted code and again there are many examples of that and parts that we have singletons you probably know false and true or not is also a from ellipses
assessing them a we have a special signal called not implemented you probably don't know
that this small integers and the path singletons so that only exist once in a process the next 1 is factories so in Python you only have a single its thunder in that method to create objects and classes and sometimes you want different ways of of creating new objects and so before we had static that sort before we had class methods and in Python going way to do that was defining a function just a regular function which then return to a an instance of that class and nowadays this is not recommended anymore narratives should use class methods for this so this is just a way of having multiple init method basically what 2 ways of defining your or initializing objects the next pattern is proxies so this is again similar to the facade adaptive In these cases we try to hide certain things from other objects were used try to add certain information to objects it's for commonly used in for
example and decorators and when doing this and decorators you should watch out that you don't create too many rappers because standard trace back to the period you can see that for example if using Django and you have a body neuron u junga code the sentence get tracebacks that span multiple pages which is not very nice and also those of
the the listings that have been there are because of these rappers and they don't really interesting so you should not really well wrapped stuff if you don't really have um and finally we have callbacks that patterns of various standard pattern that using recruits processing for example you can also use it in synchronous processing for example when writing passes so in general and whenever it some event occurs you register of the handler for that event and that handles cold call back and this call is called whenever this event happened so for example if a parser it's a certain element type and certain messages called and you can do something and was for a problem present because all dynamic you can dynamically also introspect your classes for the sound so you can dynamically creates handlers that interact with your with your policy this is very difficult to do another languages then finally there's something else I want to put some emphasis on and this is not really a coding
pattern is a code evolution pattern is a way that you start writing a Python code so what you typically do is you have just a simple script just a few statements that you put into the top US and execute then you find that you need to make it more and more with the more complex and maybe add more features and make it look a little nicer than you you take the sections that you have in a tournament of functions so the functions as the next kind of evolution fusion step that you have in your script and groups of functions and then you can make use of feature that of the object oriented features that we haven't touched that you can put everything into classes and reflected functions that you just created and put them as methods into classes and then can instantiate a classes you can run the application about you can make it even more feature-rich you can add more customization and once you do that you can start doing subclassing to for example adapt certain features have multiple features be more that's the same except for maybe 1 2 certain details you don't have to repeat yourself all the time and then you can
put everything together in loosely coupled components which are basically sets of classes and tire whole application together like that and for a really big applications like and I have a completely separate talk about this in the current goes going to go into details here but I just want to recommend when you start writing code don't necessarily start with writing told just with with classes for example start easy and then get more complex and have a cold evolves like that it's much it's a much better way to the Baltic oak and you learn about which actually knew the code it's not so much about just putting everything into in 2 classes and making everything complicated right from the start so next thing performance idioms again I have a complete separate talks for this 1 so I'm just going to mention a few things that are interesting on 1 thing is moving oversee questions
you always have to do that in Python code there is methods of doing that 1 is the for loop then you have the map function you have list comprehensions and have generators and I that and everything and I found that the superlattice used this comprehensions all the time it's the fastest way of doing this so if you're memory anything from the start this is this is going to
then the next 1 is joining strings but the obvious way of drawing strings just using the plus so the contact con contact operator on strings this is good when just having a few strings as good for readability because it's it's nice to read the other way of doing this is using the joint method on strings so you passed in as parameter a list or any adorable basically the argument the the the object of iterating you calling the joint method on this separator that you want to put into your list and then it'll do the joint for you and this is great for if you have multiple uh if you have many many strains and all the other methods of doing this that are floating around in many this news groups of part not really better than any of these 2 of the universe lower insolently aren't you should try to buy them something else exceptions if you write code that
use exceptions a lot you should be careful that you radical to structure the code in a way that you put the code that runs more often was more likely to run off into your uh tried between the trying except so if you if you put code that runs very often the more often than the common case into the exception part of that tri-accept and you'll find that you have a huge slowdown in your in your code this is because it's very expensive to raise Python exceptions it's not expensive to do that at sea level but if you do it and in Python at 6 it's expensive and so usually use the exceptions for exceptional cases if you do this you get this wrong you can have a slowdown of of 10 times 10 times because of this so that's why I mentioned that if you have want to have more of these kinds of performance
instead please have a look at this wiki page or you can download so another topic gave when performance matters which has a lot more of the details so let's have a look at some coding idioms something that I sometimes see into another coded third-party code and then look at or code from from other programmers and request is that they start to nested if statements Ray deeply and you get this kind of similar what I call the staircase in so you you if statements they move tend to move to the right to the right all the time and this story very simple way of avoiding this is of course this this doesn't look good it's hard to read because you cannot really hard to follow the intention in indentation anymore but but
only have to continue statement in Python which makes it very easy to what this whole thing so you just restructuring and then use continue to just switch to the next look in your for statement and so you don't need the indent tation anymore you can just avoided and everything becomes much more readable the same is also possible functions except in functions you would use to return statement and not the continuous right the next thing to watch out for is readability or because it has everything is pretty everything is mutable you you can use mutable things in places where it's not a good idea to actually I do
so for example if if you put mutable things into the module scope for example a database connection then um this may look very natural to you this may look nice from from a variety of perspectives but it's not that states so if you have multiple threads running accessing that same connections it's not it it it will definitely give you problems in later application especially if you use larger applications or right of the projects and you should not do this instead what you can do is you can have context objects and you create these objects they have all the context as the different for example for web request on RPC request you put the information in there and pass around that object and the object would then for example in the data base case we then also have today this connection you pass it around us 1st parameter of the functions for you if you use in classes you put it into a class instance an attribute and do it like that and then you can avoid distances and everything keeps working the same thing can happen when you define default parameters in functions so for example down here you have a function in a equals none what you what you really want for that's the default parameters you want aid to be an empty list when it's not being passed in as parameter now if you if you'd use an empty list instead of the 9 year and then you function starts doing something with with the a parameter here it was predict the the changes that you make sure that this would persist and so all the future function calls to to ask them to function from would then see those changes that you've made and of course you don't want that so the best way to avoid this is if you have to put something in rule as parameter replace it with non and then your function use the these immutable parameter that you need as default and put it into your variable inside the function a a similar case is for class default attributes so if you have a different define a class you have attributes you want to say for example that might maybe 5 which is supposed to be a list of something then you'd know only write 5 equals the empty list yeah for same problem again some method in your in your class may change this this for example in some methods and then the change would be on the class object and so all yeah instances would see those changes you don't want that so what you do is you replace the the the the assignment for that instance actual into units method to avoid this so from God
chance how many of you know the in operator has all hands go
up really yeah so I mean the and operator Operators's for membership testing so if you want to check whether something is in a list you different use the and operator you should not use the index method that you have on the list this may be a bit unusual for years to come from coming from other languages which always use methods for for doing these things it's better to do it that way for dictionaries is not necessary obvious what X in some that would mean in Python means that x the key is in your dictionary so if you test with this because it's the same as the doctor has key method come and task uses the property anyway so you should only use this 1 4 sets of sets rather related language so for sets don't even have a method to do this in operations we always have to use this which is good so you can't make any mistakes and someone got if you do bowling testing and positive and then you have cost you have true and false at 2 singletons I mentioned there various ways of testing for 4 billion um from for truth of all the false 1 way I often see is that people writing if x equals true it's not not a good way to do this because may fail to actually is an integer and has the value 1 so if you if X for example this is to there is still true but this won't work so you could print Science Princeton wouldn't execute and even more so if you write it's if X is true because it is actually checks the address of the object and of course it's honest X is actually a true single this will never be true whenever print exist for and likewise for the not the the case so this is something to remember and similarly but
if you do empty container testing so you want to check whether list for example and you topless empty you should always use if and and container because empty containers in Python always falls and containers that have something always true so this is much more efficient to do it that way you don't need the length of function for this you don't need to check with the length of positive because they can only be 0 or positive so that's really not necessary and finally something
I will it's a mistake I'll make a it's a it's comma in parts and if you look at you have 1 topples in positive so you can have trouble with 1 element in and the way to write it this you see uh user parentheses around 1 and you have to have this comedy and now this is very it's it's obvious to see that this is topic but the next line is also 1 topic and this is not obvious to see how the mistake I sometimes make is I had accidentally entered time at to the end of the line and maybe I do copy-paste from somewhere in the the colleges gets added and as you can see in the example here I I originally wanted to have S equals ABC the string ABC but what happens is that actually creates a 1 toppled so the length of s is 1 it's not 3 as I would have expected and similarly if index into S I don't get the to the last 4 s 2 I didn't inexorably because it's want limit doesn't have a the 3rd element in that in next so this is something to watch out for but comments are also nice in Python because you can python the present passes through the the brain I see because it allows having commas in places where you know we don't need them and where other languages for example give you an error message so if you have these things With the dictionaries items you can have the comma at the end of each of them items including the last 1 that you have in definition and this is very nice because if you want to add new elements to that this thing you can very easily do so and you just dependent a common and you're done you don't have to worry about and syntax errors that you might get if they missing In this even works for functions so if you have functions that take a lot of lot lots and lots of parameters you can do that with so just a short few
tools that you can use nursing in Python minutes whenever someone has a problem they write a tool for it and put it on type I and everyone uses so we
don't have to repeat ourselves all the time there's a very good to a cop island this is 1st time type of checking and has good documentation it creates quite a few false positives but you can configure and you can configure it to not to so you should if you have a look at that had 8 already mentioned pi flakes is another 1 it does logical checking foot doesn't have much documentation so you should probably have a look at flight 8 which is 1 of the the combination of that age and flakes and also has an extra complexity check it has good documentation so you should probably look at this 1 and then there's high chapter which is a very old tool that predates all the other tools that maintaining anymore it's still give you some good results so now this question type the
we thank
B. hi thank what what is the deal
would you recommend to check if it's is not not like they just the meet the dissemination received from the object is not about they should not like to look for false
and the variance then your question really you object is done now and then get out because not as a single thing you should always use if X is not as strict is the fastest way of doing it because in see is just a point of comparison and also really becomes clear that you're looking for exactly that particular value so you should not write if x equals not especially not present 3 because there's always some except this text is not the questions so no
fj the yeah good treatment
Metropolitan area network
Bit
Code
Vorlesung/Konferenz
Projektive Ebene
Menge
Computeranimation
Metropolitan area network
Angewandte Physik
Wellenpaket
Gruppe <Mathematik>
Fächer <Mathematik>
Vorlesung/Konferenz
Blase
Menge
Whiteboard
Computeranimation
Rechenschieber
Digitale Photographie
Vorlesung/Konferenz
Information
Code
Lesen <Datenverarbeitung>
Code
Computeranimation
Basisvektor
Standardabweichung
Web Site
Programmiergerät
Pauli-Prinzip
Elektronischer Programmführer
E-Mail
Modul
Code
Computeranimation
Gewöhnliche Differentialgleichung
Quader
Datensatz
Diskrete-Elemente-Methode
Programmbibliothek
Garbentheorie
Datenstruktur
Optimierung
Modul
Basisvektor
Standardabweichung
Lineares Funktional
Gerichteter Graph
Mailing-Liste
Kartesische Koordinaten
Ausnahmebehandlung
E-Mail
Code
Computeranimation
Übergang
Eins
Zeichenkette
Konstante
Metropolitan area network
Kappa-Koeffizient
Informationsmodellierung
Garbentheorie
Drei
Modul
Klasse <Mathematik>
Betrag <Mathematik>
Code
Computeranimation
Übergang
Metropolitan area network
Informationsmodellierung
Datensatz
Modul <Datentyp>
Code
Modul
Soundverarbeitung
Inklusion <Mathematik>
Videospiel
Lineares Funktional
Sichtenkonzept
Übergang
Ausnahmebehandlung
Modul
Arithmetisches Mittel
System F
Betrag <Mathematik>
Konditionszahl
Mereologie
Datenerfassung
Garbentheorie
Projektive Ebene
Restklasse
Datenfluss
Binärdaten
Datentyp
Gruppe <Mathematik>
Klasse <Mathematik>
Formale Sprache
Applet
Betrag <Mathematik>
Code
Computeranimation
Übergang
Zeichenkette
Objekt <Kategorie>
Metropolitan area network
Spieltheorie
Software
Ellipse
Mereologie
Mustersprache
Statistische Analyse
Programmbibliothek
Zeiger <Informatik>
Schnittstelle
Inklusion <Mathematik>
Proxy Server
Lineares Funktional
Prozess <Physik>
Klasse <Mathematik>
Stichprobe
Pi <Zahl>
Quick-Sort
Computeranimation
Objekt <Kategorie>
Metropolitan area network
Multiplikation
Ganze Zahl
Anpassung <Mathematik>
Mustersprache
Datenerfassung
Entropie
Faktor <Algebra>
Information
Normalvektor
Instantiierung
Maschinencode
Prozess <Physik>
Formale Sprache
Klasse <Mathematik>
Systemaufruf
Mailing-Liste
Element <Mathematik>
Extrempunkt
Kombinatorische Gruppentheorie
Parser
Frequenz
Synchronisierung
Code
Ereignishorizont
Computeranimation
Homepage
Metropolitan area network
Mustersprache
Datentyp
Ereignishorizont
Message-Passing
Standardabweichung
Turnier <Mathematik>
Klasse <Mathematik>
Gruppenkeim
Kartesische Koordinaten
E-Mail
Extrempunkt
Code
Computeranimation
Metropolitan area network
Softwaretest
Code
Mustersprache
Skript <Programm>
Zusammenhängender Graph
Skript <Programm>
Lineares Funktional
Befehl <Informatik>
Datentyp
Gruppe <Mathematik>
Zeitabhängigkeit
Singularität <Mathematik>
Speicherbereichsnetzwerk
Vorhersagbarkeit
Invariante
Objekt <Kategorie>
Menge
Funktion <Mathematik>
Betafunktion
Evolute
Garbentheorie
Gruppenkeim
Code
Computeranimation
Loop
Metropolitan area network
Mailing-Liste
Unruh-Effekt
Grundraum
Große Vereinheitlichung
Trennungsaxiom
Nichtlinearer Operator
Parametersystem
Lineares Funktional
Güte der Anpassung
Singularität <Mathematik>
Mailing-Liste
Ausnahmebehandlung
Zeichenkette
Mapping <Computergraphik>
Objekt <Kategorie>
Generator <Informatik>
Loop
Festspeicher
Mereologie
Zeichenkette
Data Mining
Befehl <Informatik>
Maschinencode
Programmiergerät
Suite <Programmpaket>
Loop
Rechter Winkel
Güte der Anpassung
Mereologie
Zustand
Ausnahmebehandlung
Wiki
Ideal <Mathematik>
Code
Computeranimation
Hyperbelverfahren
Mathematisierung
Klasse <Mathematik>
PASS <Programm>
Kartesische Koordinaten
Oval
Computeranimation
Metropolitan area network
Benutzerbeteiligung
Einheit <Mathematik>
Perspektive
Code
Thread
Abstand
Default
Analytische Fortsetzung
Chi-Quadrat-Verteilung
Gammafunktion
Modul
Attributierte Grammatik
Binärdaten
Einfach zusammenhängender Raum
Parametersystem
Lineares Funktional
Befehl <Informatik>
Datenhaltung
Singularität <Mathematik>
Mailing-Liste
Schlussregel
Ausnahmebehandlung
Knoten <Statik>
Kontextbezogenes System
Modul
Objekt <Kategorie>
Rechter Winkel
Grundsätze ordnungsmäßiger Datenverarbeitung
Datenerfassung
Projektive Ebene
Information
Varietät <Mathematik>
Aggregatzustand
Instantiierung
Schnittstelle
Bit
Ortsoperator
Hochdruck
Mengensystem
Adressraum
Formale Sprache
Element <Mathematik>
Extrempunkt
Nichtlinearer Operator
Computeranimation
Intel
Task
Metropolitan area network
Mailing-Liste
Ganze Zahl
Softwaretest
Nichtlinearer Operator
Kategorie <Mathematik>
Mailing-Liste
Data Dictionary
Objekt <Kategorie>
Menge
Funktion <Mathematik>
Automatische Indexierung
Ganze Zahl
Schlüsselverwaltung
Informationssystem
Softwaretest
Parametersystem
Lineares Funktional
Dicke
Ortsoperator
Finite-Elemente-Methode
Formale Sprache
Mailing-Liste
Element <Mathematik>
Extrempunkt
Menge
Computeranimation
Data Dictionary
Metropolitan area network
Automatische Indexierung
Parametersystem
Inverser Limes
Bildschirmsymbol
Gerade
Message-Passing
Haar-Integral
Zeichenkette
Fehlermeldung
Resultante
Ortsoperator
Code
Schaltnetz
Datentyp
Reelle Zahl
Ideal <Mathematik>
Mathematische Logik
Komplex <Algebra>
Computeranimation
Baum <Mathematik>
Computeranimation
Objekt <Kategorie>
Punkt
Paarvergleich
Baum <Mathematik>
Große Vereinheitlichung
Varianz
Computeranimation
Roboter
Metropolitan area network
Red Hat
Vorlesung/Konferenz
Computeranimation

Metadaten

Formale Metadaten

Titel Python idioms to help you write good code
Serientitel EuroPython 2015
Teil 78
Anzahl der Teile 173
Autor Lemburg, Marc-André
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/20157
Herausgeber EuroPython
Erscheinungsjahr 2015
Sprache Englisch
Produktionsort Bilbao, Euskadi, Spain

Inhaltliche Metadaten

Fachgebiet Informatik
Abstract Marc-André Lemburg - Python idioms to help you write good code Python focuses a lot on writing readable code and also tries to make solutions obvious, but this doesn't necessarily mean that you cannot write unreadable code or design your code in ways which makes it hard to extend or maintain. This talk will show some useful idioms to apply when writing Python code, how to structure your modules and also goes into details on which techniques to use and which to think about twice, based on 20 years of experience writing Python.
Schlagwörter EuroPython Conference
EP 2015
EuroPython 2015

Ähnliche Filme

Loading...