🐍 👍 🎯

Write Right Code

(by making the machine do it for you)

What’s “right”?

Code that you’re not ashamed of

Code that works

Code that looks good

😰

What’s this about 👀

Tools to help you write confidently!

  • Type hinting w/ type annotations
  • Code formatters
  • Other stuff

Types in Python

Static

type("100")  # -> <class 'str'>
type(100)    # -> <class 'int'>

Dynamic

word = "hi"
word = 100

🔥💯 Neat!!!

One problem though

>>> a = Something()
>>> b = AnotherThing()
>>> a.mysterious_method(b)
Traceback (most recent call last):
  ...
TypeError: element index must be an integer, a slice, or
an attribute name string

😡

Well, what happened was…

Hackbright’s build system

One document → slides & handouts

Implemented with Sphinx

…which is implemented with docutils

img

(This goes on for a while)

Type Annotations

(the best substitute for documentation!)

Without types

def add_data(container, data):
    """Add data to container."""

    container.append(data)
    return container

…in VSCode

WITH type annotations

def add_data(container: List[str], data: str) -> List[str]:
    """Add data to container."""

    container.append(data)
    return container

Once again, in VSCode…

How

  • VSCode can do most of this automatically
  • mypy — a linter that understands type annotations

But that’s not all!

So, what happened was…

  • I need to write a Google Calendar script
    • It should also be flexible so others can use it
    • …but it needs to get done quick
  • Parsing JSON by hand is grosssssss
    • If only there was something like SQLAlchemy
    • JSON & strings → Python data

Type Annotations

(for parsing JSON/raw data)

Extracting JSON by hand

raw = get_event_from_google()

event_attrs = {}
if owner_data := raw.get("owner"):
    event_attrs["owner"] = User(
        owner_data.name,
        owner_data.email,
        ...,
    )

# ...etc

event = Event(**event_attrs)

Parsing JSON with Pydantic

from pydantic import BaseModel

class Event(BaseModel):
    id: str
    summary: str
>>> data = get_event_from_google()
>>> Event.parse_obj(data)
<Event id="blah" summary="This is great">

Great for nested objects!

from pydantic import BaseModel

class User(BaseModel):
    name: str
    email: str

class Event(BaseModel):
    id: str
    summary: str
    owner: User
>>> data = get_event_from_google()
>>> event = Event.parse_obj(data)
>>> event.owner
<User name="ashley" email="ashley@hackbrightacademy.com">

How

Code Formatting

Turn disgusting code → pretty code

How my coworkers think I write code

my_dict =  {
    "key": [
        "very",
        "nice",
        "value",
        "hi",
        "wow this is great"
    ],
}

How I actually write code

my_dict = {'key': ['very', 'nice', 'value', 'hi', 'wow this is great']}

How

  • Black — Python code formatter
  • Prettier — for any other language
  • If you don’t use VSCode, set up a pre-commit hook

Concluding slide

(I’m bad at titles)

Contact info & links & stuff

ashley@hackbrightacademy.com

Office hours: https://calendly.com/hb-ashley