6

I need to make one function in a module platform-independent by offering several implementations, without changing any files that import it. The following works:

do_it = getattr(__import__(__name__), "do_on_" + sys.platform)

...but breaks if the module is put into a package.

An alternative would be an if/elif with hard-coded calls to the others in do_it().

Anything better?

4 Answers 4

6

Put the code for platform support in different files in your package. Then add this to the file people are supposed to import from:

if sys.platform.startswith("win"):
    from ._windows_support import *
elif sys.platform.startswith("linux"):
    from ._unix_support import *
else:
    raise ImportError("my module doesn't support this system")
Sign up to request clarification or add additional context in comments.

Comments

2

Use globals()['do_on_' + platform] instead of the getattr call and your original idea should work whether this is inside a package or not.

Comments

1

If you need to create a platform specific instance of an class you should look into the Factory Pattern: link text

Comments

1

Dive Into Python offers the exceptions alternative.

2 Comments

Link is broken. Could you replace it?
Cannot suggest edit so here's a link linux.die.net/diveintopython/html/file_handling/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.