vendredi 11 mai 2018

How to avoid parameter type in function's name?

I have a function foo that takes a parameter stuff Stuff can be something in a database and I'd like to create a function that takes a stuff_id, get the stuff from the db, execute foo.

Here's my attempt to solve it: 1/ Create a second function with suffix from_stuff_id

def foo(stuff):
    do something

def foo_from_stuff_id(stuff_id):
    stuff = get_stuff(stuff_id)
    foo(stuff)

2/ Modify the first function

def foo(stuff=None, stuff_id=None):
    if stuff_id:
        stuff = get_stuff(stuff_id)
    do something

I don't like both ways. What's the most pythonic way to do it ?

Aucun commentaire:

Enregistrer un commentaire