Having a class instance as an optional input field for a function

Viewed 28

Is there a cleaner way than using if/else statements to add an class instance as an optional field inside a function? Below is an example of using if/else statements to create an optional field for class instances:

  class hi:
    def __init__(self):
      self.ii = "foo"
      self.kk = "bar"



  def foo(myClass = None,**kwargs):
      if myClass.ii:
          print(myClass.ii)
      else:
          print("Nothing")

p=hi()
foo(p) #returns "foo"
foo() #returns "Nothing"

This can get difficult to read if there are lots of optional instances in the function. Is there a clean way to rewrite the if/else part of the function to be cleaner similar to the kwargs.get part in the example below:

  def foo(**kwargs):
       print (kwargs.get("aa", "Nothing"))

  foo(aa = "pii") #output: "pii"
  foo()#output: "Nothing"
1 Answers

You're probably looking for getattr:

getattr(myClass, 'ii', 'Nothing')

This will also prevent your code from raising an AttributeError when the attribute doesn't exist, which is what would otherwise happen with your original code.

Related