Skip to content

Python gotchas (comparisons to Elm lang) #3

Description

@badlydrawnrob

for loops

I'm used to List.filter so getting used to for loops again takes time.

Make sure you've exited the loop before raising an exception!

new_list = []

def loop(list):
    for item in list:
        if item == 3:
            new_list.append(item)
    # The correct indentation is OUTSIDE the loop,
    # not within the `if` or `for` loop.
    raise HTTPException(
        status_code=404,
        detail="Item with number 3 was not found"
    )        

if statements

In Elm you have must use the else keyword.
It's optional in Python.

def has_three(list):
    if len(list) == 3:
        return "Yes!"
    return "No!"

Using classes

You can use . dot notation to access fields ...
Dictionaries require dict["key"] (string accessors)

from pydantic import BaseModel
from typing import Optional

class Item(BaseModel):
    id: int
    name: Optional[str]

item = Item(id=1)
item.id # returns 1

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions