Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

python - Why should functions always return the same type?

I read somewhere that functions should always return only one type so the following code is considered as bad code:

def x(foo):
 if 'bar' in foo:
  return (foo, 'bar')
 return None

I guess the better solution would be

def x(foo):
 if 'bar' in foo:
  return (foo, 'bar')
 return ()

Wouldn't it be cheaper memory wise to return a None then to create a new empty tuple or is this time difference too small to notice even in larger projects?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why should functions return values of a consistent type? To meet the following two rules.

Rule 1 -- a function has a "type" -- inputs mapped to outputs. It must return a consistent type of result, or it isn't a function. It's a mess.

Mathematically, we say some function, F, is a mapping from domain, D, to range, R. F: D -> R. The domain and range form the "type" of the function. The input types and the result type are as essential to the definition of the function as is the name or the body.

Rule 2 -- when you have a "problem" or can't return a proper result, raise an exception.

def x(foo):
    if 'bar' in foo:
        return (foo, 'bar')
     raise Exception( "oh, dear me." )

You can break the above rules, but the cost of long-term maintainability and comprehensibility is astronomical.

"Wouldn't it be cheaper memory wise to return a None?" Wrong question.

The point is not to optimize memory at the cost of clear, readable, obvious code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...