Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Só Python builtins

Luciano Ramalho
November 09, 2019
720

Só Python builtins

Um passeio pelas funções, classes e objetos embutidas em Python 3.7/3.8. Apresentada na 3ª edição do Just Python em São Paulo.

Luciano Ramalho

November 09, 2019
Tweet

Transcript

  1. n ã o p r e c i s a

    i m p o r t a r SÓ PYTHON BUILTINS Um passeio pelas funções e classes embutidas no Python 3.7+ Luciano Ramalho @ramalhoorg
  2. PRIMEIRA OLHADA: DIR E HELP 3 Python 3.8.0 (v3.8.0:fa919fdf25, Oct

    14 2019, 10:23:27) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> dir() ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__'] >>> help(__builtins__) Help on built-in module builtins: NAME builtins - Built-in functions, exceptions, and other objects. DESCRIPTION Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices. CLASSES object BaseException Exception ArithmeticError FloatingPointError OverflowError ZeroDivisionError AssertionError AttributeError BufferError 8618 linhas de ajuda
  3. LISTA HIERÁRQUICA DE CLASSES NO HELP 4 UnicodeEncodeError UnicodeTranslateError Warning

    BytesWarning DeprecationWarning FutureWarning ImportWarning PendingDeprecationWarning ResourceWarning RuntimeWarning SyntaxWarning UnicodeWarning UserWarning GeneratorExit KeyboardInterrupt SystemExit bytearray bytes classmethod complex dict enumerate filter float frozenset int bool list Um monte de exceções... Classes com nomes em caixa baixa bool é subclasse de int!
  4. LISTA DE NOMES EM __BUILTINS__ 6 >>> print(*dir(__builtins__), sep=' ')

    ArithmeticError AssertionError AttributeError BaseException BlockingIOError BrokenPipeError BufferError BytesWarning ChildProcessError ConnectionAbortedError ConnectionError ConnectionRefusedError ConnectionResetError DeprecationWarning EOFError Ellipsis EnvironmentError Exception False FileExistsError FileNotFoundError FloatingPointError FutureWarning GeneratorExit IOError ImportError ImportWarning IndentationError IndexError InterruptedError IsADirectoryError KeyError KeyboardInterrupt LookupError MemoryError ModuleNotFoundError NameError None NotADirectoryError NotImplemented NotImplementedError OSError OverflowError PendingDeprecationWarning PermissionError ProcessLookupError RecursionError ReferenceError ResourceWarning RuntimeError RuntimeWarning StopAsyncIteration StopIteration SyntaxError SyntaxWarning SystemError SystemExit TabError TimeoutError True TypeError UnboundLocalError UnicodeDecodeError UnicodeEncodeError UnicodeError UnicodeTranslateError UnicodeWarning UserWarning ValueError Warning ZeroDivisionError _ __build_class__ __debug__ __doc__ __import__ __loader__ __name__ __package__ __spec__ abs all any ascii bin bool breakpoint bytearray bytes callable chr classmethod compile complex copyright credits delattr dict dir divmod enumerate eval exec exit filter float format frozenset getattr globals hasattr hash help hex id input int isinstance issubclass iter len license list locals map max memoryview min next object oct open ord pow print property quit range repr reversed round set setattr slice sorted staticmethod str sum super tuple type vars zip
  5. LISTA DE NOMES EM CAIXA-MISTA, SÓ INVOCÁVEIS 8 >>> Names

    = [s for s in dir(__builtins__) if s.lower() != s] >>> Exceptions = [s for s in Names if callable(getattr(__builtins__, s))] >>> print(*Exceptions, sep=' ') ArithmeticError AssertionError AttributeError BaseException BlockingIOError BrokenPipeError BufferError BytesWarning ChildProcessError ConnectionAbortedError ConnectionError ConnectionRefusedError ConnectionResetError DeprecationWarning EOFError EnvironmentError Exception FileExistsError FileNotFoundError FloatingPointError FutureWarning GeneratorExit IOError ImportError ImportWarning IndentationError IndexError InterruptedError IsADirectoryError KeyError KeyboardInterrupt LookupError MemoryError ModuleNotFoundError NameError NotADirectoryError NotImplementedError OSError OverflowError PendingDeprecationWarning PermissionError ProcessLookupError RecursionError ReferenceError ResourceWarning RuntimeError RuntimeWarning StopAsyncIteration StopIteration SyntaxError SyntaxWarning SystemError SystemExit TabError TimeoutError TypeError UnboundLocalError UnicodeDecodeError UnicodeEncodeError UnicodeError UnicodeTranslateError UnicodeWarning UserWarning ValueError Warning ZeroDivisionError Notebook com códigos para explorar __builtins__: http://bit.ly/2Q5x3oa
  6. HIERARQUIA DE EXCEÇÕES 9 >>> def tree(cls, level=0): ... yield

    ' ' * 4 * level + cls.__name__ ... for sub in sorted(cls.__subclasses__(), key=lambda c: c.__name__): ... yield from tree(sub, level+1) ... >>> print(*tree(BaseException), sep='\n') BaseException Exception ArithmeticError FloatingPointError OverflowError ZeroDivisionError AssertionError AttributeError BufferError EOFError EndOfBlock Error ErrorDuringImport ImportError ModuleNotFoundError ZipImportError LookupError CodecRegistryError
  7. TOPO DA HIERARQUIA DE EXCEÇÕES 10 BaseException │ ├──Exception 59↳

    │ ├──GeneratorExit │ ├──KeyboardInterrupt │ └──SystemExit
  8. SUBCLASSES DIRETAS DE EXCEPTION 11 BaseException │ └──Exception ├──StopIteration ├──StopAsyncIteration

    ├──ArithmeticError 3↳ ├──AssertionError ├──AttributeError ├──BufferError ├──EOFError ├──ImportError 1↳ ├──LookupError 2↳ ├──MemoryError ├──NameError 1↳ ├──OSError 15↳ ├──ReferenceError ├──RuntimeError 2↳ ├──SyntaxError 2↳ ├──SystemError ├──TypeError ├──ValueError 4↳ └──Warning 10↳
  9. ERROS DE ACESSO A ATRIBUTOS OU ITENS 12 BaseException |

    └──Exception | ├──AttributeError | └──LookupError | ├──IndexError | └──KeyError
  10. ERROS DE UNICODE 13 BaseException | └──Exception | └──ValueError |

    └──UnicodeError | ├──UnicodeDecodeError | ├──UnicodeEncodeError | └──UnicodeTranslateError
  11. LISTA DE NOMES EM CAIXA-BAIXA SEM PREFIXO _ 15 >>>

    names = [s for s in dir(__builtins__) if s == s.lower() and s[0] != '_'] >>> print(*names, sep=' ') abs all any ascii bin bool breakpoint bytearray bytes callable chr classmethod compile complex copyright credits delattr dict dir divmod enumerate eval exec exit filter float format frozenset getattr globals hasattr hash help hex id input int isinstance issubclass iter len license list locals map max memoryview min next object oct open ord pow print property quit range repr reversed round set setattr slice sorted staticmethod str sum super tuple type vars zip
  12. MESMA LISTA DE ANTES, AGORA COM TIPOS 16 >>> categorized

    = [] >>> for name in names: ... obj = getattr(__builtins__, name) ... categorized.append((type(obj).__name__, name)) ... >>> print(*categorized, sep='\n') ('builtin_function_or_method', 'abs') ('builtin_function_or_method', 'all') ('builtin_function_or_method', 'any') ('builtin_function_or_method', 'ascii') ('builtin_function_or_method', 'bin') ('type', 'bool') ('builtin_function_or_method', 'breakpoint') ('type', 'bytearray') ('type', 'bytes') ('builtin_function_or_method', 'callable') ('builtin_function_or_method', 'chr') ('type', 'classmethod') ('builtin_function_or_method', 'compile') ('type', 'complex') ('_Printer', 'copyright') ('_Printer', 'credits') ('builtin_function_or_method', 'delattr') ('type', 'dict')
  13. MESMA LISTA DE ANTES, AGRUPADA POR TIPOS 17 >>> for

    category, group in groupby(sorted(categorized), itemgetter(0)): ... print('!' * 20, category) ... for _, name in group: ... print(name) ... ──────────────────── Quitter exit quit ──────────────────── _Helper help ──────────────────── _Printer copyright credits license ──────────────────── builtin_function_or_method abs all any ascii bin breakpoint callable chr compile
  14. FUNÇÕES abs all any ascii bin breakpoint callable chr compile

    delattr dir divmod eval exec format getattr globals hasattr hash hex id input isinstance issubclass iter len locals max min next oct open ord pow print repr round setattr sorted sum vars 18 bool bytearray bytes classmethod complex dict enumerate filter float frozenset int list map memoryview object property range reversed set slice staticmethod str super tuple type zip CLASSES Essa distinção não é importante na prática
  15. LISTA DE NOMES EM CAIXA-MISTA, NÃO INVOCÁVEIS 19 >>> Const

    = [s for s in Names if not callable(getattr(__builtins__, s))] >>> print(*Const, sep=' ') Ellipsis False None NotImplemented True
  16. LISTA DE NOMES EM CAIXA-MISTA, NÃO INVOCÁVEIS 20 >>> set(Names)

    - set(Exceptions) {'Ellipsis', 'NotImplemented', 'False', 'None', 'True'} >>> Const = [s for s in Names if not callable(getattr(__builtins__, s))] >>> print(*Const, sep=' ') Ellipsis False None NotImplemented True Conferindo que os nomes acima são todos os nomes em caixa-mista que não são classes de exceções:
  17. BOOL E INT 23 >>> import math >>> math.factorial(100) 93326215443944152681699238856266700490715968264381621468592963

    89521759999322991560894146397615651828625369792082722375825118 5210916864000000000000000000000000 >>> bool(0), bool(-313223424) (False, True) >>> >>> int(True), int(False) (1, 0) >>> isinstance(True, int) True >>> >>> issubclass(bool, int) True Tamanho limitado só pela RAM Conversão nos dois sentidos Todo bool é um int
  18. USANDO BOOL COMO INT 24 >>> def comissao(vendas, bonus=500): ...

    if vendas > 10_000: ... return vendas * 0.1 + bonus ... else: ... return vendas * 0.1 ... >>> comissao(20_000) 2500.0 >>> comissao(500) 50.0 >>> def comissao(vendas, bonus=500): ... return vendas * 0.1 + (vendas > 10_000) * bonus ... >>> comissao(20_000) 2500.0 >>> comissao(500) 50.0 Use com moderação
  19. OBJECT Principais usos:
 • Superclasse padrão (implícita no Python 3)


    • Sentinela: valor único no sistema, para sinalizar o fim de alguma série de dados ou terminar processo ("poison pil") 25 >>> marcador1 = object() >>> marcador1 <object object at 0x1025c2ff0> >>> marcador2 = object() >>> marcador2 <object object at 0x1025c2ec0> >>> marcador1 is marcador2 False >>> marcador1 == marcador2 False
  20. FLOAT E COMPLEX float: padrão IEEE 754 double (64 bits)

    complex: dois floats 26 >>> w = 3 + 4j >>> w (3+4j) >>> w.real 3.0 >>> w.imag 4.0 >>> abs(w) 5.0 >>> x = 1.1 >>> y = 0.11 >>> z = 0.011 >>> y * 10 == x True >>> z * 100 == x False >>> f'{x:0.20f}, {y*10:0.20f}, {z*100:0.20f}' '1.10000000000000008882, 1.10000000000000008882, 1.09999999999999986677' >>> math.isclose(x, z*100) True Notebook demonstrando alguns tipos de dados: http://bit.ly/33B9rLQ math.isclose(): o jeito certo de comparar floats! float complex
  21. ITER Uso alternativo de iter: com segundo argumento, cria iterador

    que invoca função até que um valor sentinela apareça. 28 >>> from random import randint >>> def d6(): ... return randint(1, 6) ... >>> [d6() for _ in range(20)] [5, 5, 4, 3, 4, 5, 2, 4, 3, 3, 6, 6, 5, 1, 6, 5, 2, 3, 1, 2] >>> for lance in iter(d6, 1): ... print(lance) ... 2 6 >>> for lance in iter(d6, 1): ... print(lance) ... 2 2 4 3 >>> for lance in iter(d6, 1): ... print(lance) ... 2 4 3 3 6 2
  22. PROCESSAMENTO DE MASSAS DE DADOS sorted, max, min: com ordenação

    customizável via key= sum, all, any: funções que reduzem iterável a um único valor enumerate, zip, map, filter: geradores que consomem iteráveis 29 Notebook demonstrando funções e classes citadas acima: http://bit.ly/33JGaip
  23. LIÇÃO APRENDIDA: BUILTINS NÃO CABEM EM 1 AULA! 31 Repositório

    com esses slides, notebooks e outros materiais: http://bit.ly/2X2IEWA