Skip to content

Instantly share code, notes, and snippets.

View nicoddemus's full-sized avatar

Bruno Oliveira nicoddemus

View GitHub Profile
@nicoddemus
nicoddemus / ruff.diff
Created October 24, 2023 18:01
Trying out ruff formatter on pytest - 7 files modifed
diff --git a/src/_pytest/_code/code.py b/src/_pytest/_code/code.py
index 0288d7a54..54d5956d4 100644
--- a/src/_pytest/_code/code.py
+++ b/src/_pytest/_code/code.py
@@ -486,9 +486,7 @@ class ExceptionInfo(Generic[E]):
.. versionadded:: 7.4
"""
- assert (
- exception.__traceback__
@nicoddemus
nicoddemus / update-mypy-flags.py
Last active October 4, 2023 14:52
Apply allow-untyped-defs
"""
Change the "default" flags for files in a project, so new files will require full type annotations.
If a file has no flags, it adds "allow-untyped-defs".
If a file already has "disallow-untyped-defs", that flag is removed.
Together with this script, one should update the mypy.ini file of a project:
[mypy.app.*]
disallow_untyped_defs = true
from pathlib import Path
import attr
from sqlalchemy import Column
from sqlalchemy import create_engine
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import String
from sqlalchemy import Table
@nicoddemus
nicoddemus / foo.py
Last active March 17, 2021 18:07
mypy slow with nested dict call
def GetFields():
fields = dict(
tabs=dict(
_id='tabs',
caption='',
caption_cmd='',
caption_color_expr='',
caption_horizontal_size_policy='Preferred',
caption_vertical_size_policy='Fixed',
cmd='',

Com relação à type-hints, eu também sou bastante fã.

Type hints, quando rodados junto com um type checker como o mypy, trazem muitas vantagens:

  1. Documentação.

Com certeza não substitui a documentação escrita, mas colocar type hints realmente facilita, pois além de não depender das docstrings, ainda temos a ferramenta checando para você, evitando que ela fica desetualizada.

Eu já vi muitas e muitas vezes (e escrevi também) documentação que até estava correta inicialmente, mas depois de um tempo ficou desatualizada. Por exemplo, dizer que um método retorna um dict de str -> int, mas devido à algum refactoring ele às vezes retornava um valor str (ao invés de int), quebrando o cliente. Aqui o type checker vai detectar o problema imediatamente.

"""
Verbatim translation of the RangeSlider class from:
https://github.com/ThisIsClark/Qt-RangeSlider/tree/b3e381fd383aa5b02e78caff9a42fc5f4aab63e6
This is a verbatim translation, without any improvements that could be
made to the code, such as using max()/min() in a few places, interval comparisons
(`0 < x < 10` instead of `x > 0 and x < 10`), etc.
The intent is to keep it as close as the original as possible in case we want
@nicoddemus
nicoddemus / pluggy-0.11.1-benchs.md
Created May 17, 2019 12:02
pluggy benchmarks v0.11.1 vs master

0.11.1

------------------------------------------------------------------------------------------------------------------ benchmark: 8 tests -----------------------------------------------------------------------------------------------------------------
Name (time in us)                                                              Min                   Max                Mean              StdDev              Median                IQR            Outliers  OPS (Kops/s)            Rounds  Iterations
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
test_hook_and_wrappers_speed[hooks=10-wrappers=10-_multicall]              34.7022 (1.0)        160.4266 (1.0)       38.0200 (1.0)       10.0398 (1.0)       35.2711 (1.0)       0.5689 (1.0)      572;1025
26.3019 (1.0)        6921           1
test_hook_and_wrappers_s
@nicoddemus
nicoddemus / sqlalchemy-scalar.py
Last active March 26, 2019 16:10
Quick example of using class-decorators to declare compound columns
from sqlalchemy import create_engine
from sqlalchemy import Column, Float, Integer, String
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///:memory:', echo=True)
Base = declarative_base()
class ScalarField:
pass
@nicoddemus
nicoddemus / out.diff
Created May 24, 2018 00:33
black on pytest/testing
diff --git a/testing/acceptance_test.py b/testing/acceptance_test.py
index c2eed419..ad709c9b 100644
--- a/testing/acceptance_test.py
+++ b/testing/acceptance_test.py
@@ -595,6 +595,7 @@ class TestInvocationVariants(object):
cur = os.environ.get("PYTHONPATH")
if cur:
return str(what) + os.pathsep + cur
+
return what
@nicoddemus
nicoddemus / conftest.py
Created March 7, 2018 23:20
Obtain parametrized names and values of a failed parametrized test
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item):
outcome = yield
report = outcome.get_result()
parametrize_mark = item.get_marker('parametrize')
if report.failed and parametrize_mark:
# @pytest.mark.parametrize can accept "x, y" or ["x", "y"] as argument names