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!