1
\$\begingroup\$

I have a function consisting of one line of code:

def trimString(string):
    """ Remove unnecessary whitespace. """
    return re.sub('\s+', ' ', string).strip()

But I've been debating with myself whether the following would be better, seeing as explicit > implicit.

def trimString(string):
    """ Remove unnecessary whitespace. """
    string = re.sub('\s+', ' ', string).strip()
    return string

So which is preferable, the former or the latter? And why is that the case?

The question may be off-topic but I find myself asking it often enough and thought this was the place to ask.

\$\endgroup\$
  • 1
    \$\begingroup\$ I think anyone reading this who understands what re.sub and .strip() do will understand that this will return a string. The doctring and type hints as suggested by @eric.m make it even clearer without adding an extra variable. \$\endgroup\$ – QuantumChris Jul 31 at 10:39
  • \$\begingroup\$ @HoboProber I'll keep this in mind going forward as I don't want to bloat the code while still keeping things explicit. Thanks for your input! \$\endgroup\$ – Crayo Jul 31 at 10:48
4
\$\begingroup\$

I think the shorter, the better. Since you are in Python 3, if you really want to make explicit that the function is returning a string, you can use type hints:

def trimString(string) -> str:

You can also specify it in the parameter:

def trimString(string: str) -> str:

(keep in mind that Python will ignore type hints, but some IDEs like PyCharm use it to detect warnings and errors)

On a side note, you should try to follow the PEP 8 styling conventions; the function name should be in camel case, so trim_string.

\$\endgroup\$
  • \$\begingroup\$ I hadn't thought of type hints before but it seems like something I'll be very into. I've seen people deliberately avoiding the naming conventions suggested by PEP 8, namely on this thread and figured I'd do the same simply because of habit and preference. But I still have my doubts. Anyways, good answer :) \$\endgroup\$ – Crayo Jul 31 at 10:33
  • 1
    \$\begingroup\$ I used to avoid the naming conventions before, because I was used to programming Java. Now when I look at my old Python code it looks ugly since it's not what my brain expects to see in Python. I guess it's a matter of habit. \$\endgroup\$ – eric.m Jul 31 at 10:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.