this post was submitted on 15 Nov 2023
24 points (87.5% liked)

Python

6496 readers
1 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

๐Ÿ“… Events

PastNovember 2023

October 2023

July 2023

August 2023

September 2023

๐Ÿ Python project:
๐Ÿ’“ Python Community:
โœจ Python Ecosystem:
๐ŸŒŒ Fediverse
Communities
Projects
Feeds

founded 2 years ago
MODERATORS
 

This is a discussion on Python's forums about adding something akin to a throws keyword in python.

you are viewing a single comment's thread
view the rest of the comments
[โ€“] sugar_in_your_tea 1 points 1 year ago (1 children)

It's not an explicit design goal, but it explains a lot of the Zen of Python and other pushback on PIPs, so to me it's always been an unwritten design goal (be as close to pseudocode as practical, but no closer). It's also how I generally write code (start with Python "pseudocode," then decide what to use in production).

For example, from the Zen of Python:

There should be one-- and preferably only one --obvious way to do it.

Being clever in Python is a bad thing, just as it is in pseudocode. Python will never win awards for performance, so if you need that, you drop in something non-Python to do the expensive operations to keep the rest of the code clean and obvious.

If you think of Python as pseudocode, everything else makes a ton more sense.

You can test for values being 0 before dividing, or catching an exception when it is.

Ideally, you just test for input variables outside of the function and do neither. Something like:

def calc(x, y):
    assert x > 0
    assert y != 0
    ...

This throw exceptions if the preconditions fail, but those can (and should) be removed for production since their primary purpose is to inform the developer of the preconditions and catch mistakes in development. In production, you'd rely on some kind of schema validation to ensure the asserts never trigger (I'm partial to Pydantic).

So ideally you'd never expect a divide by zero or clutter your code with zero checks outside of those asserts (which shouldn't be relied on) because you've already prevented those cases from happening.