string literal or NoneType

Terry Reedy tjreedy at udel.edu
Sat Mar 15 20:41:32 CET 2008


<menosaint at gmail.com> wrote in message 
news:b2d5cbd3-b207-4c46-89ef-75ae101752ca at e6g2000prf.googlegroups.com...
| hi all
| i want to check a condition and if true should return a filename
| string  from a list.if the condition is false i am returning a
| ""  (string literal)..
|
| retv=""
| if  somecondition:
|    retv=mylist[x]
| ...
| return retv
|
|
| The calling function will check the return value and print the
| filename if it is not """.
| in the calling function i can code
| if returnval !="":
|    print "filename is:",returnval
| else:
|    print "no filename found"
|
| what i want to know is ,should i rewrite the  if returnval !=""  as
|
| if returnval:
|   print "filename is:",returnval
| else:
|    print "no filename found"

In this situation, where returnval must be a string, the two are 
equivalent.
So I consider the shorter, more efficient form stylistically better.
In situations where various null or non-null conditions are not equivalent,
one should use the one that is correct for the situation.

| or is the way i coded the right way ? i am little confused here
| Someone suggested that i make a variable retv None and if the
| condition true then set retv as filename ,
|
| retv=None
| if somecondition:
|    retv=mylist[x]
|
| ...
| return retv
|
| which approach is correct..?

As long as the function returns are documented and the behavior matches the 
documentation and the calling code matched the behavior, both are 
'correct'.
I see this as stylistic preference.  I can think of situations where a null 
string might be more useful that None, so I might go with that. Others 
might think of situations where a None return might be better.  But a 
function cannot satisfy all possible callers ;-)
(The is one problem with writing library code.)

Terry Jan Reedy






More information about the Python-list mailing list