gofmt – Sam & Max http://sametmax.com Du code, du cul Wed, 30 Oct 2019 15:34:04 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.7 32490438 Once you go black, you never go back http://sametmax.com/once-you-go-black-you-never-go-back/ http://sametmax.com/once-you-go-black-you-never-go-back/#comments Wed, 06 Jun 2018 11:16:12 +0000 http://sametmax.com/?p=24513 PEP8 sont pour moi deux features fondamentales de Python, limitant énormément la quantité de code illisible qu'on trouve dans la communauté.]]> L’indentation obligatoire et l’existence du PEP8 sont pour moi deux features fondamentales de Python, limitant énormément la quantité de code illisible qu’on trouve dans la communauté.

Malgré cela, le reformatage de code reste une tache courante, et nécessaire, mais un gâchis énorme de temps. D’abord il faut décider comment on va formater, ce qui en équipe veut dire débat sur le pire sujet qui soit: le goût. Ensuite il faut mettre en place des configurations de linter (flake8, pylint, etc), et potentiellement l’infra qui va avec (tox, hooks git, CI…).

Pour cette raison, de nombreux outils de formatage automatique ont vu le jour. Le premier a été autopep8, et plus tard yapf de Google.

Mais ces deux outils ont quelques soucis:

  • Pas facile à faire marcher ou à configurer.
  • Ne résout pas l’éternel débat du formatage préféré qui revient dans un meeting chaque année.
  • Parfois ils ne marchent pas.
  • Parfois ils changent le sens du code (arg!).
  • Ils vous font des git diff bien velus.
  • Ne marche pas avec toutes les versions de Python.

Le monde du langage Go a choisi une stratégie différente: la technique du “ta gueule”.

Et aussi: ta gueule

Et aussi: ta gueule

Cette technique subtile et raffinée s’est incarnée dans l’outil Gofmt, qui est fourni par défaut avec go, et n’a AUCUN réglage.

Le résultat, tout le monde a fermé sa gueule et a adopté l’outil.

Est-ce que le formatage est parfait ? Non.

Est-ce qu’il plaît à tout le monde ? Absolument pas.

Est-ce qu’il fait fermer sa putain de gueule à tout le monde afin qu’on puisse enfin retourner à des choses plus importantes comme coder ?

Yes !

Gofmt produit un formatage suffisamment clair et pragmatique, et comme il est fortement ancré dans la communauté, tout le monde est à la même enseigne. Passer d’un code à un autre est facile. Pas de temps perdu à discuter du style ou à tweaker ses linters. Tout le monde lance go fmt (aka go ferme ta …) et on passe à autre chose.

Dernièrement facebook a décidé de faire pareil, et à pondu en open source black (en référence à Henry Ford), un outil de formatage en Python, qui n’a que 2 réglages. Il suit le PEP8, mais évidemment sa propre interprétation, et ne propose rien d’autre.

Black a aussi l’avantage de fournir des diffs assez petits, et surtout, vérifie si l’AST change après un reformatage, et annule le cas échéant, garantissant que le sens de votre code n’est pas altéré.

Est-ce que j’aime toutes les règles de formatages de black ? Non.

Est-ce que regarder sa sortie me donne parfois envie de me bouffer les couilles parce que franchement, qui pense que c’est une bonne idée d’aligner les choses comme ça ? Parfois.

Mais c’est good enough.

Et du coup, l’adoption de black a été très rapide dans la communauté, et il a été appliqué à heroku, requests, tablib, envoy, clint, fabric 2 et pytest. 4000 stars sur github.

Installation

Évidemment, ça se pip install, mais uniquement sur Python 3.6. Black peut checker du code 2.7, mais il lui faut du 3.6 minimum pour exister, donc on l’installe en parallèle. Évidemment, on peut l’intégrer à ST, Vim ou VSCode. Si votre projet utilise un Python different, il faut donc dans les options faire pointer l’exécutable vers l’installation séparée.

Résultat

Dans l’esprit du lien partagé par Seb, créons un générateur de titre de film porno:


import random

subject_qualifiers = ( "shy", "mature", "busty", "hot", "horny", "ebony", "quiet", "excited", "naughty", "bad", "cheating", "beautifull", "gorgeous", "drunk", "emo", "fat", "chubby", "goth", "lingery wearing", "latex enthousiast", "placid", "energic", 'slutty', 'sweaty', 'curvy', )

subjects =(
    'teen',
    'doll',
    'brunette',
    'blonde',
    'midget',
    'milf',
    'bitch',
    'babe',
    'sister',
    'step-mom',
    'vixen',
    'secretary',
    'real estate agent',
    'teacher',
    'student',
    'schoolgirl',
    'cheer leader',
    'asian tourist',
    'babysitter',
    'ex girlfriend',
    'nurse',
    'squirtter',
    'model',
    'granny',
    'furry',
)

actions = (
        "recieves anal",
        "get busted",
        "driven to bukakke",
        "taught double penetration",
        "fucked hard",
        'gently chocked',
        'punished',
        'forced into blow job',
        'pounded',
        'creampied',
        'ass raped',
        "eaten",
        "get her pussy wet",
        "shamed",
        "get an orgasm for the first time",
        'lead to loud climax',
        'offered best sex of her life',
        'worn out',
        'cured from boredom',
        'warmed up',
        'loved in and out',
        'generously oiled',
        'shocked and impressed',
        'decieved into giving it',
        'woke up roughly',
        'get sexy massage',
        'ridden to exhaustion',
        'turned into a lavish slave',
        'never submit to torture',
        'rebels against abuses',
        'taken in every possible way',
        'enjoy the 10 inches provided',
)

actors = (
        "pawn shop owner",
    "corrupted cop",
    "dirty plumber",
    "big ass nigga",
    "sport coach"
    "her boss",
    "twisted psychiatrist",
    "ripped doctor",
    "crispy fire fighter",
    "smug playboy",
    "skinny geek",
    "eccentric millionaire",
    "airplane pilot",
    "movie star",
    'football team',
    'her big brother',
    'security guard',
    'hairy beast',
    'wasted guitard player',
    'hung indian immigrant',
    'a guy twice her size',
    '17 guys in a row',
    'her ideal man',
    'her secret prince charming',
    'weirdo albinos',
    'muscle giant',
    'the worst cook ever',
    'cable man',
    'more men that she can count',
    'two friendly brothers',
    'enrike strongsteel'
)

contexts = (
    "on the beach","in a cheap motel","in the back of a van",
    "in airplane toilets", "for hours", "to pay back her depts",
    "for a stupid mistake", "and it gets better", "and ask for more",
    "because she could", "in exchange for a favor",
    "right next to her boyfriend", "as a reward",
    "hopping to get him back", "caught on security cam", "every monday",
    "in a barn", "but that's not all", 'but she has a secret',
    "and she has a dick too", 'before inviting her friend over',
    'while her father is watching', 'with her ', "while auditing for a role",
    "to get her job back", "for an interview", "in exclusive sex tape",
    "again and again", ", begging to stop", "for a change", "for chrismas",
    "in public", 'in a back alley', "during a concert", 'on her death bed'
)

punctuation = ('','!','!!','...')

def get_title(subject_qualifiers, subjects, actions, actors, contexts) :


    qualifier = random.choice(subject_qualifiers)
    subject = random.choice(subjects)
    action = random.choice(actions)
    actor = random.choice(actors)
    context = random.choice(contexts)

    return f"{qualifier} {subject} {action} by {actor} {context}" .capitalize()


if __name__ == "__main__":
    print(get_title(subject_qualifiers = subject_qualifiers, subjects=subjects,
                    actions=actions, actors=actors, contexts=contexts))

Usage:

$ python3.6 porn_title_generator.py
Chubby model loves bukakke by skinny geek during a concert
$ python3.6 porn_title_generator.py
Busty bitch rebel against abuses by security guard but she has a secret
$ python3.6 porn_title_generator.py
Lingery wearing student creampied by weirdo albinos on the beach
$ python3.6 porn_title_generator.py
Horny bitch offered best sex of her life by hairy beast in airplane toilets
$ python3.6 porn_title_generator.py
Emo blonde punished by airplane pilot on the beach
$ python3.6 porn_title_generator.py
Quiet squirtter lead to loud climax by wasted guitard player while auditing for a role
$ python3.6 porn_title_generator.py
Emo babysitter get her pussy wet by football team caught on security cam
$ python3.6 porn_title_generator.py
Busty asian tourist taken in every possible way by muscle giant and she has a dick too
$ python3.6 porn_title_generator.py
Placid milf ass raped by muscle giant in a back alley
Je soupçonne un coup des frères Markov

Je soupçonne un coup des frères Markov

On applique black, zero réglage, usage simplissime:

$ black . # appel recursif, modification in place par défaut

Le résultat.

import random

subject_qualifiers = (
    "shy",
    "mature",
    "busty",
    "hot",
    "horny",
    "ebony",
    "quiet",
    "excited",
    "naughty",
    "bad",
    "cheating",
    "beautifull",
    "gorgeous",
    "drunk",
    "emo",
    "fat",
    "chubby",
    "goth",
    "lingery wearing",
    "latex enthousiast",
    "placid",
    "energic",
    "slutty",
    "sweaty",
    "curvy",
)

subjects = (
    "teen",
    "doll",
    "brunette",
    "blonde",
    "midget",
    "milf",
    "bitch",
    "babe",
    "sister",
    "step-mom",
    "vixen",
    "secretary",
    "real estate agent",
    "teacher",
    "student",
    "schoolgirl",
    "cheer leader",
    "asian tourist",
    "babysitter",
    "ex girlfriend",
    "nurse",
    "squirtter",
    "model",
    "granny",
    "furry",
)

actions = (
    "recieves anal",
    "get busted",
    "driven to bukakke",
    "taught double penetration",
    "fucked hard",
    "gently chocked",
    "punished",
    "forced into blow job",
    "pounded",
    "creampied",
    "ass raped",
    "eaten",
    "get her pussy wet",
    "shamed",
    "get an orgasm for the first time",
    "lead to loud climax",
    "offered best sex of her life",
    "worn out",
    "cured from boredom",
    "warmed up",
    "loved in and out",
    "generously oiled",
    "shocked and impressed",
    "decieved into giving it",
    "woke up roughly",
    "get sexy massage",
    "ridden to exhaustion",
    "turned into a lavish slave",
    "never submit to torture",
    "rebels against abuses",
    "taken in every possible way",
    "enjoy the 10 inches provided",
)

actors = (
    "pawn shop owner",
    "corrupted cop",
    "dirty plumber",
    "big ass nigga",
    "sport coach" "her boss",
    "twisted psychiatrist",
    "ripped doctor",
    "crispy fire fighter",
    "smug playboy",
    "skinny geek",
    "eccentric millionaire",
    "airplane pilot",
    "movie star",
    "football team",
    "her big brother",
    "security guard",
    "hairy beast",
    "wasted guitard player",
    "hung indian immigrant",
    "a guy twice her size",
    "17 guys in a row",
    "her ideal man",
    "her secret prince charming",
    "weirdo albinos",
    "muscle giant",
    "the worst cook ever",
    "cable man",
    "more men that she can count",
    "two friendly brothers",
    "enrike strongsteel",
)

contexts = (
    "on the beach",
    "in a cheap motel",
    "in the back of a van",
    "in airplane toilets",
    "for hours",
    "to pay back her depts",
    "for a stupid mistake",
    "and it gets better",
    "and ask for more",
    "because she could",
    "in exchange for a favor",
    "right next to her boyfriend",
    "as a reward",
    "hopping to get him back",
    "caught on security cam",
    "every monday",
    "in a barn",
    "but that's not all",
    "but she has a secret",
    "and she has a dick too",
    "before inviting her friend over",
    "while her father is watching",
    "with her ",
    "while auditing for a role",
    "to get her job back",
    "for an interview",
    "in exclusive sex tape",
    "again and again",
    ", begging to stop",
    "for a change",
    "for chrismas",
    "in public",
    "in a back alley",
    "during a concert",
    "on her death bed",
)

punctuation = ("", "!", "!!", "...")


def get_title(subject_qualifiers, subjects, actions, actors, contexts):

    qualifier = random.choice(subject_qualifiers)
    subject = random.choice(subjects)
    action = random.choice(actions)
    actor = random.choice(actors)
    context = random.choice(contexts)

    return f"{qualifier} {subject} {action} by {actor} {context}".capitalize()


if __name__ == "__main__":
    print(
        get_title(
            subject_qualifiers=subject_qualifiers,
            subjects=subjects,
            actions=actions,
            actors=actors,
            contexts=contexts,
        )
    )

L’indentation est revue et normalisée vers 4 espaces, les espacements et sauts de ligne sont rééquilibrés (limite de caractères à 88 ), les quotes deviennent toutes ‘”‘. C’est lisible. Le code marche toujours.

Problem solved.

]]>
http://sametmax.com/once-you-go-black-you-never-go-back/feed/ 19 24513