Home > database >  Is code "if sql_answer: " in pythonic style
Is code "if sql_answer: " in pythonic style

Time:12-09

I am a junior and in my pet project wrote next code:

# Try to find information about this offer in database
sql_answer_ad = __select_from_ad_table(conn, cur, (one_offer_data[0],))

# If information about offer is in database                
if sql_answer_ad:

But some of my friends think that right variant is

if __is_sql_answer_ad_not_empty():

What you think, what variant is more pythonic?

if sql_answer_ad:, IMHO, standard code construction. I saw same code many times. I.e.:

  1. finally block in https://www.geeksforgeeks.org/python-sqlite-connecting-to-database/
  2. Naomi CEDER. "The Quick Python Book"

CodePudding user response:

the first one is smaller, and has everything you need to know,

if sql_answer_ad:

anyone with at least a week of experience in python will know that the first code variation is checking that the reply is not empty, and very long names that add nothing to context are bad, as they reduce the white space, which makes reading the code harder.

i know you are checking that the reply is not empty, if you put a 10 word function in front of my face i will have to read its name and figure out what it is doing instead of skipping it, which reduces code readability.

as to what is pythonic, if you look into PEP8 you will find

For sequences, (strings, lists, tuples), use the fact that empty sequences are false

  • Related