We're sorry but this page doesn't work properly without JavaScript enabled. Please enable it to continue.
Feedback

Pattern Matching in Python

00:00

Formale Metadaten

Titel
Pattern Matching in Python
Untertitel
Learning why Python and patterns are a perfect match
Serientitel
Anzahl der Teile
115
Autor
Mitwirkende
Lizenz
CC-Namensnennung - keine kommerzielle Nutzung - Weitergabe unter gleichen Bedingungen 4.0 International:
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.
Identifikatoren
Herausgeber
Erscheinungsjahr
Sprache

Inhaltliche Metadaten

Fachgebiet
Genre
Abstract
When Python 3.10 comes out in October 2021, it will include a new feature called “Structural Pattern Matching”. Structural Pattern Matching has been a staple of functional programming languages, but it has recently appeared or been proposed as future additions to imperative and OOP programming languages (like JavaScript, C++, and Rust). It provides an elegant way of processing and deconstructing heterogeneous data structures, and it enables an alternative paradigm to method dispatch. As one of this feature's contributors, my goals in this presentation are to describe the motivation for this new functionality, present some of the problems that its use will effectively solve, and give a brief introduction of how to use it. This talk is aimed at intermediate Python developers (although a beginner will be able to understand it). After attending you should be able to understand not just how to use pattern matching, but also when it’s a good idea to use it and what are the possible pitfalls to avoid. There will be a Q&A session which could be a good chance to discuss your questions about why certain design decisions were made when introducing pattern matching into Python.
19
Vorschaubild
43:26
GoogolATMMustervergleichKontrollstrukturImplementierungProgrammierspracheMapping <Computergraphik>HochdruckShape <Informatik>Element <Gruppentheorie>Mailing-ListeAttributierte GrammatikGraphfärbungZahlenbereichObjekt <Kategorie>Deskriptive StatistikHelmholtz-ZerlegungVariableFolge <Mathematik>Boolesche AlgebraMusterspracheVerschlingungFunktionale ProgrammierungElektronischer ProgrammführerCASE <Informatik>Güte der AnpassungEntwurfsmusterDämpfungZeichenketteRechenschieberBenutzeroberflächeZusammenhängender GraphQuick-SortSoftware EngineeringNichtlinearer OperatorDifferenteSchwarzer StrahlerBefehl <Informatik>TabelleCodeArithmetischer AusdruckProgrammierungEigentliche AbbildungSystemaufrufPunktRechter WinkelSoftwareentwicklerUmwandlungsenthalpiePauli-PrinzipMultiplikationp-BlockKonditionszahlGenerator <Informatik>TopologiePhysikalisches SystemSubstitutionOrtsoperatorFunktionale ProgrammierspracheMereologieAusnahmebehandlungPaarvergleichBitMultiplikationsoperatorInvarianteMathematikMathematische LogikSummengleichungDickeE-MailTwitter <Softwareplattform>Digitale PhotographieDatenstrukturBimodulInformationDifferenzkernÄußere Algebra eines ModulsMaßerweiterungVirtualisierungParametersystemMotion CapturingFreier ParameterDatenanalyseExogene VariableKlasse <Mathematik>AuswahlaxiomSpannweite <Stochastik>StichprobenumfangKonstruktor <Informatik>ProgrammierparadigmaPlastikkarteTemplateQuadratzahlRechteckSchlüsselverwaltungFlächeninhaltFehlermeldungKreisbogenRauschenProgram SlicingInstantiierungWort <Informatik>KonstanteTypentheorieNichtlineares GleichungssystemKonfiguration <Informatik>KreisflächeLeckData DictionaryDefaultSpieltheorieCompilerProgrammverifikationDienst <Informatik>ZeitrichtungLesen <Datenverarbeitung>Schreiben <Datenverarbeitung>GruppenoperationFitnessfunktionApp <Programm>GeradeAusdruck <Logik>EinsEllipseFokalpunktMatchingTablet PCSpezifisches VolumenBus <Informatik>MinimumRhombus <Mathematik>Rekursive FunktionLeistung <Physik>AlgorithmusSampler <Musikinstrument>Projektive EbeneProgrammbibliothekAutorisierungReelle ZahlParserGewicht <Ausgleichsrechnung>ComputerspielVisualisierungFormale SemantikDivisionGlobale OptimierungInhalt <Mathematik>NeuroinformatikBetafunktionTupelSoftwareBesprechung/Interview
EntwurfsmusterPauli-PrinzipMustervergleichDatenstrukturBitPauli-PrinzipAutorisierungMusterspracheComputeranimation
Jensen-MaßImplementierungKreisflächeEinsObjekt <Kategorie>ZeichenketteMatchingShape <Informatik>DifferenteMustervergleichComputeranimation
Shape <Informatik>DatentypTextur-MappingSchlüsselverwaltungInstantiierungAttributierte GrammatikObjekt <Kategorie>Shape <Informatik>SchlüsselverwaltungAttributierte GrammatikInstantiierungQuick-SortDeskriptive StatistikArithmetischer AusdruckSchaltnetzBoolesche AlgebraComputeranimation
Shape <Informatik>MustervergleichObjekt <Kategorie>MusterspracheComputeranimation
Shape <Informatik>MusterspracheDickeAttributierte GrammatikNichtlinearer OperatorCodeUmwandlungsenthalpieFolge <Mathematik>IndexberechnungComputeranimation
VariableEntwurfsmusterVariableMailing-ListeFolge <Mathematik>Element <Gruppentheorie>TabelleZusammenhängender GraphDifferenteObjekt <Kategorie>PunktMustervergleichMusterspracheComputeranimation
HochdruckElement <Gruppentheorie>EntwurfsmusterObjekt <Kategorie>Nichtlinearer OperatorMusterspracheHelmholtz-ZerlegungMereologieComputeranimation
MusterspracheEntwurfsmusterInnerer PunktMustervergleichEntwurfsmusterObjekt <Kategorie>TabelleDämpfungZahlenbereichDifferenteGenerator <Informatik>Arithmetischer AusdruckFolge <Mathematik>Rechter WinkelMailing-ListeCASE <Informatik>MusterspracheComputeranimation
EntwurfsmusterTypentheorieRechenschieberFreier ParameterMotion CapturingCASE <Informatik>DifferenzkernKonstruktor <Informatik>BimodulObjekt <Kategorie>InformationSystemaufrufInstantiierungKlasse <Mathematik>Computeranimation
Innerer PunktFahne <Mathematik>EntwurfsmusterAuswahlaxiomMultiplikationsoperatorCASE <Informatik>ZeichenketteBoolesche AlgebraArithmetischer AusdruckElement <Gruppentheorie>EntwurfsmusterData DictionaryFolge <Mathematik>MusterspracheSchlüsselverwaltungMathematische LogikMapping <Computergraphik>BitDefaultComputeranimation
Klasse <Mathematik>EntwurfsmusterAttributierte GrammatikObjekt <Kategorie>EntwurfsmusterKonfiguration <Informatik>CASE <Informatik>GraphfärbungComputeranimation
EntwurfsmusterCodep-BlockEntwurfsmusterMustervergleichProgrammierspracheCASE <Informatik>Befehl <Informatik>Zweip-BlockGruppenoperationArithmetischer AusdruckMultiplikationSchreiben <Datenverarbeitung>Mailing-ListeMusterspracheCodeSystemaufrufFunktionale ProgrammierungKonditionszahlVariableComputeranimation
MultitaskingImplementierungParametersystemEntwurfsmusterDifferenteDickeParametersystemMessage-PassingFehlermeldungBitUmwandlungsenthalpieVariablePunktSpannweite <Stochastik>Folge <Mathematik>MusterspracheMustervergleichProgram SlicingMailing-ListeShape <Informatik>CASE <Informatik>KreisbogenMultiplikationsoperatorRechter WinkelFunktionale ProgrammierungCodeSoftwareentwicklerp-BlockComputeranimation
Spannweite <Stochastik>HochdruckWort <Informatik>ZahlenbereichMultiplikationUnendlichkeitMultiplikationsoperatorSpieltheorieMustervergleichProgrammierungComputeranimation
Spannweite <Stochastik>HochdruckBoolesche AlgebraTupelMatchingCASE <Informatik>ZahlenbereichMinimumMustervergleichBefehl <Informatik>Computeranimation
SystemaufrufVolumenvisualisierungExogene VariableBefehl <Informatik>CodeHochdruckMathematische LogikCASE <Informatik>FehlermeldungTemplateExogene VariableMustervergleichKonstanteSchlüsselverwaltungInformationWeb SiteBefehl <Informatik>Quick-SortVariableEigentliche AbbildungCodeMereologieDienst <Informatik>SystemaufrufMultiplikationsoperatorLesen <Datenverarbeitung>MinimumAusnahmebehandlungComputeranimation
Syntaktische AnalyseDatenstrukturPolygonzugTopologieRekursive FunktionRechenschieberMustervergleichBenutzeroberflächeDatenstrukturAlgorithmusAusgeglichener BaumZeichenkettePaarvergleichMailing-ListeEntwurfsmusterKonditionszahlGraphfärbungSyntaktische AnalyseTypentheorieComputeranimation
EntwurfsmusterShape <Informatik>FlächeninhaltRechteckQuadratzahlKreisflächeRadiusCodeMustervergleichHelmholtz-ZerlegungDifferenteShape <Informatik>FlächeninhaltMathematische LogikKreisflächeQuadratzahlPunktNeuroinformatikAusnahmebehandlungFunktionale ProgrammierungParametersystemTabelleKlasse <Mathematik>Objektorientierte ProgrammierspracheMusterspracheObjekt <Kategorie>MinimumGeradeProgrammbibliothekComputeranimation
EntwurfsmusterProgrammierungPlastikkarteMusterspracheProgrammierparadigmaMathematische LogikFunktionale ProgrammierungMultiplikationsoperatorSubstitutionQuick-SortMaßerweiterungNichtlinearer OperatorObjektorientierte ProgrammierspracheCASE <Informatik>MathematikMustervergleichKreisflächeMusterspracheFlächeninhaltShape <Informatik>App <Programm>FokalpunktAusdruck <Logik>DatenstrukturFunktionale ProgrammiersprachePhysikalisches SystemPlastikkarteDifferenteLeistung <Physik>Klasse <Mathematik>DatenanalyseComputeranimation
EntwurfsmusterBefehl <Informatik>MusterspracheCompilerKonstanteSubstitutionFormale SemantikGlobale OptimierungNeuroinformatikBefehl <Informatik>CompilerComputeranimation
Pauli-PrinzipCodeStichprobeProgrammierspracheUmwandlungsenthalpiePauli-PrinzipVerschlingungMustervergleichElektronischer ProgrammführerCASE <Informatik>Güte der AnpassungImplementierungComputeranimation
TemplateDigitale PhotographieSpezialrechnerTemplateDigitale PhotographieMustervergleichTwitter <Softwareplattform>E-MailComputeranimation
Physikalisches SystemOrtsoperatorInformationXML
Vorlesung/KonferenzBesprechung/Interview
Kartesische Koordinaten
Transkript: Englisch(automatisch erzeugt)
Hi, again. I hope you all had a great lunch break. Now we have with us Daniel, who has a very interesting talk on pattern matching in Python. He, I guess, is streaming from London.
He has 20 years of professional background in technology with diverse roles like software engineering, project leader, and a trainer. And he loves Python, compilers, piano, and Dungeons and Dragons. Over to you, Daniel. Thank you very much. Is my audio working properly?
Yes. OK, amazing. Thank you. So thank you, everyone. And hello from surprisingly sunny London to everyone. And what I want to talk about today is what I think is one of the most exciting features in Python coming up, which is structural pattern matching. My name is Daniel.
I work as a trainer and training engineers at Bloomberg. And something a bit more relevant about me for this talk is that I'm one of the multiple authors of the pattern matching PEPs. It's not a single PEP. It's a trilogy, like just look at this. Well, at least it's not a trilogy of trilogies,
but it's three PEPs because it's a big feature and important to describe it well and discuss it well. So this is something that's not present in the latest Python release, which is official Python release, which is 3.9. But if you download one of the Python 3.10 betas, it's available.
The implementation is ready. You can play with it and learn about it. So 3.10 will be available this October. And we'll talk about the matching. So let's discuss what is pattern matching. And it's about recognizing objects of different shapes. And if we look at the background of these slides,
you can see that there are a lot of different shapes in this background. And we can recognize them by different aspects of them. We could look at which of these shapes are black and which ones are white. We can say which ones are circles or which one are crosses or which one are big.
And we only get this big white X. So there are a lot of different things that you can look about into a shape. So we're doing this not with string but with full objects. So what makes objects different? So what's the shape of an object is the first thing we're trying to talk about.
And the shape of an object, of a Python object, will be related to its type. If it's a sequence, how big it is. If it's a mapping, for example, a dictionary, what keys are present in an object. And if it's any other instance
which attributes are present also there. So these are all different things that are present inside an object and that you can care about when describing its shape. Also, you can check for a specific object, like an exact value, like is this object the number three?
Or even combination and nesting of this, for example, is the attribute full of my instance the value, exactly the value of three? So the first impression you get from this description is that this is some sort of Boolean expressions that will tell you yes or no given an object
to check if it matches a shape or not. But pattern matching goes beyond that. And that's one of the key insights of this idea of pattern matching, which is why are we checking the shape of the objects?
And when your code, you're checking the shape of a object, it's because you're about to do something on it that depends on the shape and typically depends on extracting some data that where the extraction can only be done if the object has a certain shape. So for example, if you check that the variable X
holds a DAC object, it's probably because you want to do some DAC specific operation on top of it. And if you're checking for the length of a sequence, it's because you probably want to extract some indices from the sequence before that length. If you check for the presence of a key or an attribute in a mapping or in a general object,
it's because you are about to access a key or access that attribute. So this is the most important thing. Checking that the notion matches the pattern and extracting data are normally very related operations and they're close to each other in your code. So can we do both of them sort of at the same time?
Can we describe, so our patterns want to describe not just the shape, but how to extract data from that. And the fun thing is that if we say, okay, we need to invent something about the composite object and also assign the different components into variables and Python before pattern matching
already has something like that. So if you look at a table unpacking or essentially sequence unpacking would be the proper name. For example, I can say, okay, given the sequence, I want to take the first element into A, the last element into C and everything else into B with this description, A, star, B, C.
And this will disassemble my sequence. It will check that it has at least two elements and it will capture the proper elements in the proper variables. So pattern matching is cranking up this idea up to 11 and that's what we will do. And the first idea of the first point about how we design the syntax of patterns
is following this example over here that Python already has. If you look at this, this is not actually building a list. This is actually describing how to assemble a list but it looks very similar to how you can build a list like this one where you put A as the first element, C as the last and all elements of B in the middle. So the object decomposition uses the same syntax
as the object creation. And when we are taking this idea further away, we will be doing more of this. Our patterns will look like object creations but it's important to recognize that our pattern will be used for the opposite operation from creation which is decomposing the object into its component parts.
So an easy way or an intuitive way to see this is that when you have a pattern, this on the left are patterns, you have an object on the right and we call the object being match the subject. We can say, okay, can this expression on the left
generate given some values of the variables, the value on the right? And in some cases it's truly true. Like for example, this is the same. A variable like X can generate anything because anything could be held into X and that's actually the value that will be captured.
So a pattern like this X,Y will only generate lists or sequences of two elements. And something like this will only generate integral numbers but never will generate a float. So these are the left are patterns that match these corresponding subjects when there's a tick here
and don't match when there's a red X. So there are a lot of different patterns that will be available in Python 3.10. I have this big table with all the examples and all the definitions. I just want to quickly go over the most prominent of these samples.
So you don't need to read this whole slide. There's a lot of information here. But essentially you can check for a specific value like these two examples of the top or this middle example is even pulling down the constant for a module and what you're checking is for equality. If you use a variable as a pattern, this actually always matches but it will capture the value of the subject
inside of the variable that you chose. I have a special case for the underscore variable which always matches but doesn't capture anything. So this is like a placeholder and will be useful in some cases that we'll see. We can also use like a call to a class name to say, okay, this object is an instance of this given type
because this looks like creating that object. But in this case, we are checking if this can be created with this constructor. So we can do compositions of this. So for example, this is a sequence pattern checking that I have a sequence of two elements and the first element matches the pattern and the second matches this one. So this will extract the second element into variable A
and we can do more complicated scenarios combining the things above. You can also use patterns not just on sequences but also mappings like dictionaries or default bits or other Python mappings where you check for the presence of certain keys and check for the values to match certain patterns. And again, you can do nested extraction over there.
So there are some patterns that don't look exactly like Python syntax because we need to do things that were slightly different than what Python logic creation can do. For example, this vertical bar essentially means any of the possible options over here.
This is called an or pattern because it's doing an or between multiple possibilities. We have this ask to essentially capture whatever is captured on the pattern on the left into a variable at the right. So this allows you to give variable names to more complicated things in patterns like this or expression between a Boolean or a JSON string.
And you can even have more complicated cases where you use a variable multiple times in all the different choices. So the syntax is quite powerful and extends a bit to what normally Python can do. We also can see that we can match on arbitrary objects
based on their attributes. So this is checking that my object is a duck and the color of the duck should be green. This is checking that it's a duck, the color of the duck should be green and it should have an age attribute and I will capture the value of the age attribute into A. So this is essentially like doing all these checks
and also capturing this. This is great in many cases because it's simplifying a lot of checks that you normally have to do before accessing some nested complicated attribute. And you can nest even objects. For example, you can say, I want the duck and the mother of that duck should be another duck and I want to capture the age of the mother of the duck
like that and this does all the checks and pulls the attribute out of that. So as you can see, there's a lot of flexibility, there's a lot of options. It's possibly better if we look at some examples but also before doing that, I mentioned what patterns are
but I still haven't explained how patterns fit into the language, where can you use pattern? And patterns can only be used in a single place which is this new match case statement that has been added to the language which normally looks like this.
It has a match with the subject and the subject is any Python expression so a value or a variable or a function call or a list comprehension or whatever you want. And then you have multiple of these case blocks each one containing some code and a pattern and an optional regard which I'll explain in a second. So you can think of this as a large if-alive statement.
So the goal of this statement is to choose a single block that will get executed. Only one block, one of these blocks at most will be executed. Zero is also a possibility. For a block to execute the pattern must match the subject. And if there's a Boolean condition over here
these Boolean conditions are useful when you want to express a more complicated condition that cannot be expressed with the pattern syntax. So you can add some extra checks over here. So if the pattern of under guard matches this code block will be executed. And the case blocks are attempted top to bottom.
So there might be multiple pattern matching that will match patterns that will match the subject but only the first one that matches will be the one that runs. Something also useful is that this guard can use the variables captured by the pattern. So this also tends to simplify how we can write
expressions and let's look at some examples of all of these in action. So let me show you a slicer function that we are writing. Let's say that this is a spec that we've been given. This works similar to the essentially
the range function in Python where you have a mandatory stop argument but you can also provide a start and a step on the left and right. So if I want to slice the sequence until the stop point I can pass only this argument beside the sequence. If I want to an interval and specify the start point I can pass two arguments.
And if I want to specify the start to stop and the interval, I pass the three arguments. And that's what I should get. This is my specification. When you start writing that you say, okay this argument seem to be optional but you can not do this in Python because you can not put an optional argument
before a mandatory argument. So this confuses Python a bit because it doesn't support directly this case. And this is a syntax error. So this doesn't work. So let's see if we can use pattern matching for this. So what I want to do is essentially capture whatever arguments I get with these star arcs and match on that to consider all the different cases
and possibilities. So if I have only a stop value I return the sequence and the stop value. If I have a start and stop I return the sequence slice with the start and stop. And if my start arcs is these three arguments I return everything in the slice. And you'll notice that this is not just checking
that the length of the list is the proper length for each different scenario but it's also capturing those variables and these variables are being used on the right. So this is a good example of how I'm checking the shape and capturing data all at the same time and how that works. And I also have a final case with this magic underscore wildcard that I mentioned before
that matches always where I'm raising an error if all of the cases above fail. Remember that cases are checked from top to bottom. So this ensures that this is a very general case that always will match but we will only execute this block if none of the cases above happen. So if you look at the spec again you will see that this looks really, really similar
to our spec. As Russek Ekel someone said this is like executable pseudocode. So you can see that in this scenario pattern matching allows us to capture our intent as developers and make very elegant and readable code which is something nice. So let's go into another example which is the famous fist pass problem.
It's a very common Charles game and also very frequently using bad programming interviews where you want to go over the numbers from one to 100 and you say one, two, three, four, five but instead of saying three every time you hit a multiple of three you say the word fist.
Every time you hit a multiple of five you say the word bass and every time you hit a multiple of both you say fist bass. So you'll say one, two, fist, four, bass, fist, seven, et cetera. So if we want to call that
there are infinite solutions to this problem but let's look at the one with pattern matching. Essentially I have different scenarios and which scenario to choose depends on whether my number is divisible by three, sorry and whether my number is divisible by five.
So I'm matching on this pair of Boolean values. So if both are true, it means it divisible by both so I print fist. If it's divisible by three, I print fist. If it's divisible by five, I print bass and otherwise I print the number. So I'm again matching on a pair of values is matching on a tuple which are Booleans in this case.
And I'm again relying that the cases go from that the matching goes from top to bottom. And this is a very common way of using the match statement where you put more specific cases at the top and more general cases at the bottom. So I don't have to worry about this fist being printed if the number is also multiple of five
because that case was covered before. So let's do something more interesting and more closer to real life. Let's say we're rendering some template on a website and I'm getting some user information from the service and my template has to print a greeting for the user.
So I have some sort of user ID. I have this API call that give me some shades of information about the user giving the ID which is this response. And I want to check what of the possible responses that this service gives me are available
so I can get either an error or I can get the user. And also let's say I have a special case where I want to make a special reading for the user if today is the birthday of that user. So let's say, okay, if I get some, if my response is a JSON that has some error key inside of this, and this only checks
that the error key is present, it doesn't care if I have another 20 keys, which is very common in APIs, I have a lot of keys that I don't care about. I will raise, for example, this sort of error. If I get the user with the name N and the date of birth, D, and also this is part of the fashion,
let's say it's telling me that today is the birthday of a person born on date D, then I will print happy birthday. I will use the name that I captured here. So look that the name that I captured here, the date that I'm using inside and the date that I captured I'm using in the guard over here. And I'll print happy birthday to the user. In any other case, not that this third case
will match any user match by the second case, but the second case will cover the birthday cases. So if it's not the birthday, I will fall back into this third case and we'll just print a generic welcome to the user. And if I get anything else from the API, probably there's a bug in either the API code or my code.
So I'm raising an exception and telling that I get an unexpected response. Again, we can see that cases go from specific, the one on the top, to general, the one on the bottom. So a very boring use for, a very boring use case for pattern matching
is a switch statement. A lot of people are saying, oh, Python now has a switch statement. Yes, you can use this as a switch statement and you can check, okay, is this, let's say this HTTP status, is it 200? Is it an invalid user, a 403 code, a 301, which needs to be processed as redirect.
But you can also combine them with more complicated cases. So you can say, is the code something between 500 and 599? And essentially caption the code and using the guard and raising its error. And if it's something else, I raise an invalid status. And this works. And again, in this case, I could look at this and say,
am I getting anything out of, as compared as doing this with an if and a leave statement? I'm probably not. So this case probably should be rethought as something that may be made simpler. But in some cases, if you're saying that you will have more complicated logic and the response here, then pattern matching is a great fit.
So something else to be careful about is that I'm using literal constants and this match properly. If I use a variable name, let's say I have a constant which is called HTTP OK, with the value 200 and I write HTTP OK, this will actually look like a variable.
So you'll always match. In that case, you still get some sort of syntax error because Python realizes that I'm matching the whole variable and they have cases after that, which looks a bit funny. So it stops me from doing that. But in many cases, especially if your last case is a constant name,
but constants and variables in Python are the same, you'll actually capturing the value into the contents, which is probably not what you want. Python will try to help you most of the time here, but careful with this. So other use cases, if you look at pep636, there's an example of a simple parser for like a command line user interface
where you type commands and there are parser. So very simple parsers where you pass a list of strings and you want to check commands and arguments, it can be done with pattern matching. And going over complicated data structures, if you follow this link, the slides will be online later, if you follow this link,
you'll see an example of a red-black tree. Red-black trees are a fancy balancing tree data structure where those are of two possible colors and you need to maintain some invariance. We need to check that if the top node is red and the left child is black and the right node has a nephew that does something.
And all of these conditions can be very succinctly and clearly expressing patterns. So you can see comparison of how much simpler the algorithm is with pattern matching. So going over recursive data structures is great with pattern matching. So let's see how this allows us
to not just talk about the feature, but how this allows us to use, to think about code in different ways. So we can think of pattern matching as a decomposition approach. And Python has some other decomposition approaches. For example, if I want to do a library to represent geometrical shapes, we can use OOP.
And in OOP programming, I define a base shape class and a lot of subclasses, for example, a circle subclass that has an area method that knows how to compute the area for a circle. This is classical OOP, the lines in the bottom. But I can instead put the logic outside of my objects and say, well, my objects will be dumb data structure,
like Python data classes or name tables or anything like that, or more complicated object, it doesn't matter. And they have this area function that checks the shape of my shape here. And if it's a rectangle, it computes area for rectangle, it computes area for square or for a circle, or if it doesn't know how to compute the area,
it raises an exception. So in this case, putting the logic for all area computations in the same place, which has some benefits and drawbacks. And the main point here is that it allows me to focus
on how I want to decompose things. You can say that, okay, but in OOP, it's very easy to add a new shape because I just define a single class and all the logic is inside of here. Well, in the pattern matching approach, I have to add the shapes to all of these possible functions that operate in shapes and the code is spread all over.
And that is true, but I can give you a counter argument when I say, if I want to add new functionality rather than new shapes, new operations, in the object-oriented approach, you need to spread new methods all about. Well, here, all of the logic is in a single place. So the emphasis is, what do we want to make extensible?
Do we want to make it easy to add verbs to our system or to add nouns to our systems? Well, verbs are methods and nouns are objects. So these are the kind of same things as a method dispatch, but focus on extensibility in a different place. So it's an alternative, not a substitute for OOP.
And this comes from the functional programming paradigm where it's typical that we have dumb values and smart functions is the way they call it. And essentially data structures don't have any behavior and the functions have all the logics to handle multiple cases.
And this works very well when your data doesn't change as often as the operations that you want to do on the data. For example, some sort of data analysis where every time you get new requirements on how to analyze existing data that you have. In OOP, you can do this kind of same things with the visitor pattern, which is to sort of solve this problem.
But it's a bit cumbersome. You have to define a lot of auxiliary methods and auxiliary classes. Pattern matching has a more straightforward syntax than the visitor pattern. And it also has additional power because the visitor pattern can only split things apart based on their class.
Well, pattern matching can check a lot of different things. So you could, for example, if you have an ellipsis shape you can have a complicated formula for the area of ellipsis. But if you know that the focus of the ellipsis are in the same place, then that's a circle and you can use the circle formula instead.
So I see some great questions that I will answer on the Wonder app later on because I don't think we'll have time for questions within the talk. So as comparison, how does this compare with the switch statement?
So the checking is sequential while some switch statements have these computer go-tos that are typically faster because it's based on literals. I mean, a modern Python compiler in the future could do some optimizations if all of your values are constant but no one is talking about doing that anytime soon.
And also in a switch, you can use constant values but you need to be careful with semantics the problem I mentioned before. So again, it's not a great substitute for a switch statement. You can use it as that, it's not its main goal. So if you want to learn more about this
I recommend you to go in over the peps. The three peps cover different things. 634 is the specification. So it's quite hard and technical and it's for language implementers. 635 is interesting if you are wondering why pattern matching is designed the way it is
or why should you use it? What are good use cases for this? So that's recommended in this case. And if you already love pattern matching and want to just learn how to use it, use it. 636 is a tutorial which guides you step-by-step through all of the syntax. And I have some link with some examples over here. I would also like to credit the people
who made the Slice Carnival provided this awesome template. And these are public. There are other pictures and photographs which are just with permission from the creators. And thank you very much for attending. This is my Twitter. It is very easy to reach me over here.
And this is my email. I'm also trying to answer anything that comes over pattern matching over here but Twitter is probably the best way. Thank you. So again, thank you very much for attending. As a last point, I mentioned that I work from Bloomberg. Bloomberg is hiring. You can find this information about positions in this careers link.
And also we have a sponsor room in the conference systems and you can jump around. And there's people, I'm around there. So if you want to talk to some engineers, we're around there. And there's also people from HR if you want to talk about recruiting and hiring. So you're welcome to come.
So if you, I'm going to jump out now, I think. But if you want to ask any questions I'll be in the Wonder Me outside the October room. So thank you very much. Thank you, Daniel.