Reputation: 2642
I have a program which will require different variables for each OS (Linux and Windows). Would it be better to have a dictionary for each variable like so:
# 'win'dows and 'lin'ux
system_root = { "win" : r"C:",
"lin" : r"/" }
data_folder = { "win" : r"C:\Program Files",
"lin" : r"/usr/share/applications" }
or a separate dictionary for each OS variables like this:
vars_win = { "system_root" : r"C:",
"data_folder" : r"C:\Program Files" }
vars_lin = { "system_root" : r"/",
"data_folder" : r"/usr/share/applications" }
And sorry if the question title wasn't very clear about my intentions, I couldn't think of a better way to put it.
Upvotes: 0
Views: 36
Reputation: 46626
I would prefer the second solution since you can do:
if platform == windows:
vars = win_vars
elif platform == posix:
vars = lin_vars
And then later in you application you don't have to deal with de branching. Just use the vars
variable.
Note: I haven't specified the way to check for the platform since there are multiple ways depending on what you need. You can either check the sys.platform
, use the platform
module or check if posix
, nt
... is in sys.builtin_module_names
.
Upvotes: 2
Reputation: 95722
It looks as though most or all of the access to these 'variables' will use constant keys, so a better solution would be to use a class hierarchy:
class CommonVars:
pass
class WindowsVars(CommonVars):
system_root = "C:\\"
data_folder = "C:\\ProgramData"
class LinuxVars(CommonVars):
system_root = "/"
data_folder = "/usr/share/applications"
if platform == windows:
vars = WindowsVars
elif platform == posix:
vars = LinuxVars
... do something with vars.system_root ...
If it seems useful you could expand these into full-blown classes with methods for system-specific behaviour.
The base class isn't used in this example, so it might be entirely superfluous, but I would include it anyway in case at some point you want to include system attributes that are actually the same between both platforms but might vary if you added support for a third.
Upvotes: 0