Skip to content

Instantly share code, notes, and snippets.

@NerOcrO
Last active August 30, 2022 09:53
Show Gist options
  • Save NerOcrO/3616acee8743bb330251c27041703cf8 to your computer and use it in GitHub Desktop.
Save NerOcrO/3616acee8743bb330251c27041703cf8 to your computer and use it in GitHub Desktop.
Python

Tips

  • type()
  • print()
    • Ne fonctionne dans un test que s'il est rouge
    • print(obj.__dict__) ou print(vars(obj))
  • help(method)
  • dir(intance_dune_classe)
  • intance_dune_classe.__dict__ => affiche tous les attributs
  • Méthodes spéciales
  • self = this
  • """ docstring """
  • def method_static(cls) avec classmethod(method_static)
  • On peut typer et mettre une valeur par défaut à un paramètre de fonction/méthode
  • _ma_methode => privée (par convention)
  • class Payment(PcObject, Model) => héritage
  • EXISTS vs JOIN and use of EXISTS clause
    • Garder JOIN si c'est 1 pour 1
  • * est comme un spread en JavaScript
  • Les listes, délimitées par les crochets [ et ]
  • Les tuples, délimités par les parenthèses ( et )
  • Les dictionnaires, délimités par les accolades { et }
  • print(str(query.statement.compile(compile_kwargs={"literal_binds": True})))
  • package vs module
  • What is the meaning of single and double underscore before an object name?
booking_ids_subquery = _query_keep_on_non_activation_offers() \
    .distinct(Booking.stockId) \
    .filter(Booking.userId == user_id) \
    .order_by(Booking.stockId, Booking.isCancelled, Booking.dateCreated.desc()) \
    .with_entities(Booking.id) \
    .subquery()

return Booking.query \
    .filter(Booking.id.in_(booking_ids_subquery)) \
    .join(Stock) \
    .order_by(Stock.beginningDatetime) \
    .all()

Open a file

path = f'{os.path.dirname(os.path.realpath(__file__))}/../static/tuto_mediations'
with open(path, 'w') as file:
    # ...

Mesurer le temps

before = datetime.utcnow()
# Insère ici la fonction à mesurer
after = datetime.utcnow()
elapsed_time = after - before
print('------------------ ??? ------------------')
print(divmod(elapsed_time.total_seconds(), 60))

Filter or filter?

# C'est mieux d'utiliser cette syntaxe
# https://www.artima.com/weblogs/viewpost.jsp?thread=98196
used_bookings = [booking for booking in bookings if booking.isUsed]
# equal to
used_bookings = filter(lambda booking: booking.isUsed, bookings)
# Add list() to transform to dict

Map

used_bookings = [f(x) for booking in bookings]

Compiler Python

  • wget https://www.python.org/ftp/python/3.9.6/Python-3.9.6.tgz
  • tar xzf Python-3.9.6.tgz
  • cd Python-3.9.6
  • ./configure --enable-optimizations --prefix /chemin/isolé (permet d'installer dans un endroit que l'on pourra supprimer facilement après)
  • make
  • sudo make install
  • alias python=”python3.9” à .bashrc

S'il manque des librairies systèmes alors il faut les installer via apt et refaire la manipulation ci-dessus.

Virtualenv

pip3 install virtualenv (relancer un terminal) (si nouvelle version de python installée)
virtualenv venv
source venv/bin/activate
pip install -r requirements.txt
pip install -e . (là pù il y a le setup.py)
deactivate
pip3 freeze | xargs pip3 uninstall -y

Chercher une dépendance

pip show [package]

Import by default with CLI

  • Il faut mettre dans un fichier Python from algolia import * puis, dans le _init_.py de ce module from algolia.domain.eligibility import * et enfin lancer python -i mon_fichier_avec_import.py
  • Le CLI de Python a déjà de l'autocomplete des fonction built-in

Run a server

python3 -m http.server 1337

Linter

# singleton-comparison
filter((User.isCreated == True)) => filter((User.isCreated.is_(True)))
filter((User.isCreated != False)) => filter((User.isCreated.isnot(False)))

"If you want your code to run faster, you should probably just use PyPy."
-- Guido van Rossum (creator of Python)

VSCode

  • Importmagic
  • Python
  • Pylance
  • il faut prendre l'environnement local pour qu'il prenne en compte la configuration du projet

Pytest options

  • -s (show std_out even if the test passes)
  • -k STRING (run test with STRING in the name)
  • -m MARKER (run tests containing a marker)
  • -v (verbose output -- show each test's name)
  • --tb=LENGTH (adjust the length of traceback messages: auto, short, line or no)
  • --lf (re-run only the tests that failed)
  • --durations=n (see execution times for n slowest tests)
  • fixture = un moyen de faire un mock
  • setup_module/teardown_module : appelé une fois par fichier de test
  • setup_function/teardown_function : appelé une fois par test (function)
  • setup_class/teardown_class : appelé une fois par classe
  • setup_method/teardown_method : appelé une fois pas test (class)
import requests

def mon_test()
    # given
    requests.get = MagicMock()
    requests.get.return_value = MagicMock(status_code=400)

mock

# Ca fonctionne :
mock_add_to_redis.assert_called()
mock_args, mock_kwargs = mock_add_to_redis.call_args
assert mock_kwargs['offer_id'] == booking.stock.offerId
# Mais il y a plus court :
mock_add_to_redis.assert_called_once_with(client=app.redis_client, offer_id=booking.stock.offerId)

stub

from unittest.mock import MagicMock, patch

# Constante
@patch('validation.routes.headers.ENV', 'development')

# Fonction
@patch('scripts.dashboard.ma_fonction')
def test_xxx(stub_ma_fonction):
    stub_ma_fonction.return_value = 5
    # où
    stub_ma_fonction.return_value = MagicMock()
import pytest

# Quand on teste qu'une exception doit être lévée
# When
with pytest.raises(Exception) as exception:
    ma_fonction()

# Then
assert str(exception.value) == 'my error message'
# Quand on teste qu'une exception ne doit pas être lévée
try:
    # When
    ma_fonction()
except Exception:
    # Then
    assert pytest.fail('my custom error message')

Test a decorator

from unittest.mock import MagicMock

from scheduled_tasks.decorators import cron_context


def test_should_give_app_context_to_decorated_function(self):
    # Given
    @cron_context
    def decorated_function(*args):
        return 'expected result'

    application = MagicMock()
    application.app_context.return_value = MagicMock()

    # When
    result = decorated_function(application)

    # Then
    assert result == 'expected result'
    application.app_context.assert_called_once()

Pytest lancé en local ou via un container Docker ? (2900 TU)

  • CI : docker 02m16s
  • MEFA (WSL) : docker exec 2m14s
  • Damien : (linux) pytest 2m26s
  • François (macos 10.15.7 catalina avec plugins) : pytest 4min15s , pc test-backend 2m55, docker exec 2m23
  • Flora (macos Catalina avec mdm) : docker exec 3m08s
  • Victor (vieux pc sous linux sans mdm) : docker exec 5m37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment