I'm designing a python module that interfaces with several parts of a simulation API (via windows dll). I would like to make full use of python so that the library is both clean and simple to use.
When implementing my own class to interface with a part of the API, I found myself wanting to implement __getitem__
and __setitem__
as accessors to the API's getValue()
and setValue()
methods. It provides a cleaner interface to the internal hex values within the simulation software, but is this bad practice or perhaps not pythonic?
Below is an example of what I would like to implement:
# Note that each word is identified by a unique integer and each has a
# settable/retrievable hex value within the simulation software.
class sim:
...
...
def __getitem__(self, key):
''' check for valid key range (int)'''
''' else throw exception '''
val = simAPI.getValue(key) # returns the value of the word at the key in the
# software, None on failure
if val:
return val
'''else throw exception '''
def __setitem__(self, key, value):
''' check for valid key range and value (int, int)'''
''' else throw exception '''
if not simAPI.setValue(key, value): # sets the value of the word at the key in the
''' throw exception''' # software, None on failure
...
...
This would allow for:
Word = sim()
Word[20] = 0x0003 # set word 20 to hex value 0x0003 in the simulation software
if Word[23] == 0x0005: # check if word 23 is equal to 0x0005
pass
and maybe with more development, slicing to set multiple words:
Word[1:5] = 0x0004 # set words 1-5 to 0x0004
Although I have described my specific case, I sincerely welcome a general discussion on what implementations/uses of special methods are bad practice.
In advance, thank you for your time in answering my question!