Say I have a python class which may set a dictionary upon instantiating:
class myClass():
def __init__(self, some_dict=None):
self.some_dict = some_dict
and then in another place in my code, I want to look up a key in that dict - but of course only if it exists. Is the best Python style then to 1) make a "checking method" in the class, even if it's only one line, or 2) directly reference the class' dictionary attribute? Let's say the class was instantiated as myClassInstance
the options are then
1) Class method:
def is_key_in_dict(self, query_key):
return self.some_dict and query_key in self.some_dict
which is then used as
if myClassInstance.is_key_in_dict(query_key):
do_something()
or, 2) directly reference in the code where its used.
if myClassInstance.some_dict and query_key in myClassInstance.some_dict:
do_something()
Is it okay (style-wise) to reference class attributes directly or is it considered bad/unsafe practice? I am somewhat familiar with the @property
decorator, as discussed in this post: What's the pythonic way to use getters and setters?, but not sure if that answers my question.