Search code examples
pythonpython-3.xpython-clicktinydb

Call Function in if-Statement/ evoke call with print() - good practice?


Using tinydb i have an object for database operations like this:

#database.py 
class DataBase(object):
    """CRUD access to database."""

    def __init__(self):
        """Initialize database."""
        self.db = TinyDB('/db.json')

    def new(self, **kwargs):
        """Add a new entry to the database."""
        if self.db.insert(kwargs): # 1
            return 'New item added to the database.'
        else:
            return 'Item NOT added to the database.'

The method 'insert' from tinydb returns the id of the entry after it is inserted, see #1. So i use this effect to return a success/ fail message, which can be displayed when the function is called with print():

#main.py
#...
@entry.command('new')
@click.argument('first_arg', type=str)
@click.argument('second_arg', type=str)
def entry_new(**kwargs):
    """Create a new entry."""
    if kwargs is not None:
        click.echo(a_db.new(**kwargs)) # 2
#...

Question #1:

if self.db.insert(kwargs):

Is it 'good practice' to execute the insert function inside the condition statement of the if-block? If not, what are the alternatives to get create an if/ else-statement based on the return value?

Question #2:

click.echo(a_db.new(**kwargs))

The whole process of inserting a file into the database is wrapped in a print-statement to be able to access the return value of the insert function. Is this 'good practice' or are there better ways to call the insert function, access the return value and print it out?

Thanks in advance for your clarifications!


Solution

  • It can be hard to say what is 'good practice' as people often different opinions on what they are.

    1: You are not using the returned value anywhere else, so it would seem ok to only have it within the conditional statement. If the insert method raised some exception, you would have to handle that, but it does not seem that it does.

    2: The same answer as in number 1. If you don't use the variable anymore, then it would be fine to it like this.