pythonpython-3.xcorrectness

Most correct way to define a function with variations for platforms


Today I ran across this answer, which defines a function after determining the system platform.

I had always assumed (or rather, never really considered otherwise) that the conditional for determining correct behavior for cross-platform functions should be placed inside the definition.

import subprocess
import sys

def show_file(path):
    if sys.platform == "darwin":
        subprocess.check_call(["open", "--", path])
    elif sys.platform == "linux":
        subprocess.check_call(["xdg-open", "--", path])
    elif sys.platform == "win32":
        subprocess.check_call(["explorer", "/select", path])

I am curious, is it more efficient to do it the way @Dietrich Epp has?

if sys.platform == "darwin":
    def show_file(path):
        subprocess.check_call(["open", "--", path])
elif sys.platform == "linux":
    def show_file(path):
        subprocess.check_call(["xdg-open", "--", path])
elif sys.platform == "win32":
    def show_file(path):
        subprocess.check_call(["explorer", "/select", path])

I have no idea if either of the above snippets work, but that isn't really part of the question regardless.


Solution

  • One consequence of putting the show_file() function definition within the conditional is that trying to use this function on an unsupported platform will raise a NameError. Putting the conditionals inside the show_file function will cause it to silently fail unless you also include a raise in the final else block.

    Up to you which is better. Personally I'd prefer a clear error on an unsupported platform, but I think for clarity this is probably best handled as a final else condition so the cause of the exception is very clear.

    Efficiency between the two cases is negligible. I would be much more concerned with code readability and handling of exceptions.