Last active
June 24, 2020 17:15
-
-
Save osantana/c7ddce9d94a1eb7450f1491c9440ed78 to your computer and use it in GitHub Desktop.
Python Bloat
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def say(animal_name): | |
match animal_name: | |
case 'cow': | |
print('mu!') | |
case 'duck': | |
print('quack!') | |
case _: | |
print(f'Invalid animal type: {animal_name}') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Exemplos extraídos diretamente da PEP-622: | |
# https://www.python.org/dev/peps/pep-0622/#rationale-and-goals | |
def is_tuple(node): | |
if isinstance(node, Node) and node.children == [LParen(), RParen()]: | |
return True | |
return (isinstance(node, Node) | |
and len(node.children) == 3 | |
and isinstance(node.children[0], Leaf) | |
and isinstance(node.children[1], Node) | |
and isinstance(node.children[2], Leaf) | |
and node.children[0].value == "(" | |
and node.children[2].value == ")") | |
def match_is_tuple(node: Node) -> bool: | |
# The new command match/case: | |
match node: | |
case Node(children=[LParen(), RParen()]): | |
return True | |
case Node(children=[Leaf(value="("), Node(), Leaf(value=")")]): | |
return True | |
case _: | |
return False |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Cow: | |
def say(self): | |
print('mu!') | |
class Duck: | |
def say(self): | |
print('quack!') | |
def say(animal_name): | |
animals = { | |
'cow': Cow, | |
'duck': Duck, | |
} | |
try: | |
animal_type = animals[animal_name] | |
except KeyError: | |
print(f'Invalid animal type: {animal_name}') | |
animal = anymal_type() | |
animal.say() | |
say('cow') | |
say('duck') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import typing | |
PLUGINS = {} | |
def register_plugin(plugin: typing.Type['Plugin']) -> typing.Type['Plugin']: | |
PLUGINS[plugin.name] = plugin | |
return plugin | |
class Plugin: | |
name: typing.Text = "" | |
@register_plugin # o que essa @ significa? (esse já tem tempo) | |
class MyPlugin(Plugin): | |
name: typing.Text = 'My Plugin duh!' # str? o que é str? eu não sei Python! | |
# v- esse self aqui já causa confusão desde sempre... | |
def say_hello(self, name: typing.Optional[typing.Text] = None) -> None: # uahh! o que são esses parâmetros? | |
match name: | |
case '': | |
print('Hello!') | |
case name: | |
print(f'Hello {name}!') # f? porque esse texto começa com f? | |
case _: # caso o nome seja "_" onde tem essa variável? | |
raise Error("Cannot say hello) | |
def extract_numbers(self, s: typing.Text) -> typing.Text: | |
return ''.join(n for n in s if n.isdigit()) # WTF? E dá pra piorar ainda mais :) | |
plugin = MyPlugin() | |
plugin.say_hello() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# There is no default or else case - instead the special wildcard _ can be | |
# used as a final 'catch-all' pattern. | |
# | |
match shape: | |
case Point(x, y): | |
... | |
case Rectangle(x, y, _, _): # _ é um caracter "coringa"(?!) | |
... | |
print(x, y) # This works | |
# Name Pattern | |
match data: | |
case [x, x]: # Error! | |
... | |
case [_, _]: | |
print("Some pair") | |
print(_) # Error! | |
# Constant value Pattern | |
from enum import Enum | |
class Color(Enum): | |
BLACK = 1 | |
RED = 2 | |
BLACK = 1 | |
RED = 2 | |
match color: | |
case .BLACK | Color.BLACK: # o que são esses "dotted-names"? isso nunca existiu em Python! | |
print("Black suits every color") | |
case BLACK: # This will just assign a new value to BLACK. | |
... # ^-- ãh? atribuir um valor aqui? | |
# Sequence Pattern | |
match collection: | |
case 1, [x, *others]: # leia essa expressão e tente entender antes de ler a PEP? | |
... # o que será atribuído a `x` e a `others`? | |
case (1, x): # o que será atribuído à x? | |
... | |
# Mapping Patterns | |
import constants | |
match config: | |
case {"route": route}: | |
process_route(route) | |
case {constants.DEFAULT_PORT: sub_config, **rest}: | |
process_config(sub_config, rest) | |
# Class Patterns | |
match shape: | |
case Point(x, y): # como que esse match funciona sem ter acesso ao código de Point.__match__()? | |
... | |
case Rectangle(x0, y0, x1, y1, painted=True): | |
... | |
# Multiple Patterns | |
match something: | |
case 0 | 1 | 2: # esse `|` é o OR bit-a-bit? não! :) | |
print("Small number") | |
case [] | [_]: | |
print("A short sequence") | |
case str() | bytes(): | |
print("Something string-like") | |
case _: | |
print("Something else") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment