Adapting code to multiple platforms

Michael Spencer mahs at telcopartners.com
Fri Mar 11 19:42:31 EST 2005


Jeffrey Barish wrote:

> 
> class super:
>     '''All the generic stuff goes here'''

Better not to call the class super: it's a built-in type
> 
> class linux_subclass(super):
>     def func(self):
>         '''linux-specific function defined here'''
> 
> class windows_subclass(super):
>     def func(self):
>         '''windows-specific function defined here'''

but the general idea of specializing is sound

> 
> And then in main I have:
> 
> inst = eval('%s_subclass' % sys.platform)(args)
> 
It would be better to make this an explicit mapping:

clsmap = {'win32': windows_subclass, 'linux': linux_subclass}
try:
     inst= clsmap[sys.platform]()
except KeyError:
...

However, you will also run into the problem that sys.platform can report all 
sorts of different strings - and not all the differences may be meaningful to 
you.  For example, I gather that sys.platform on linux can return something like 
linux-i386.  So you'll probably end up doing something like:


clsmap = {'win': windows_subclass, 'lin': linux_subclass}
try:
     inst= clsmap[sys.platform[:3]]()
except KeyError:
...

Michael




More information about the Python-list mailing list