Python coding practice: Return None vs Returns the same data type with an empty value?

Are the same data types used to return from functions or assign default values? or not? What is the best coding practice and why?

eg. Some pseudo codes in python:

/1

def my_position():   # returns a positive integer if found
    if(object is present):
          position = get_position()
          return position # eg 2,3,4,6
    else: 
          return None     # or return -1 or 0 ??

/ 2

def get_database_rows():    
    do query to whatever database
    if(rows are found):
       return [list of rows]
    else:
       return None  # or return empty list []  ?

/ 3

the_dictionary = {'a' : 'john','b':'mike','c': 'robert' }  # values are names i.e. non empty string
my_new_var = the_dictionary.get('z', None)  # or the_dictionary.get('z','')  ?
+5
source share
6 answers
  • Raise IndexErrorif the item is not found. This is what Python does list. (Or, perhaps, return the index where the element should have lived when performing a binary search or similar operation.)

  • , , : , , , , (len, in) .

    , , .

  • , , : , , . dict KeyError, . , , . , .

, None , . None - Python, , , , return:

def food(what):
    if what == HAM:
        return "HAM!"
    if what == SPAM:
        return " ".join(["SPAM" for i in range(10)])
    # should raise an exception here

lunch = food(EGGS)    # now lunch is None, but what does that mean?
+6

1: .

: -1 - C-, IndexError pythonic.

2: .

: . " Java (2ed) Item43 , " (, Java, )

3: .

: KeyError, None , : -, , None ; -, , ( ), , None.

+1

, : . , , python, , .

:

  • -1, , "".find, ValueError, , [].index ( , ). , 0 .

  • , . , None . , ( ), None .

  • , , None . - , , , None ( , , , , ).

+1

, , , .

, None, , , -1, , , . , , .

, [], None, [] - . , , 0 - , , , -

len(odd_numbers(lst))

. None ,

0 if odd_numbers(lst) is None else len(odd_numvers(lst))
+1

, , , : . , - ( None). , coulr return: string, None, bool, 1, 2 3. .

0

.

1 - return position # eg 2,3,4,6

, None . (, , , , .)

2 - return [list of rows]

, [] , , , for row in rows:.

3 - `the_dictionary = {'a': 'john', 'b': 'mike', 'c': 'robert'}

Again, it looks like a record, so the missing value will naturally None(usually) be. (And if you always expect a dictionary, then throw an exception).

0
source

All Articles