Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way set variables if none in __init__

Tags:

python

What's the most pythonic or elegant way of achieving this?

def __init__(self, connection=None, some=None, thing=None, else=None):
   if connection is None:
      self.connection = SetConnection()
   else:
      self.connection = connection
.
.

If I have multiple input args like above for which I would like to call another class to instantiate. Any good way to keep it clean looking without being verbose?

like image 343
Joel Avatar asked Jan 26 '26 11:01

Joel


1 Answers

You could use a binary operator:

def __init__(self, connection=None, some=None, thing=None, else=None):
    self.connection = connection or SetConnection()

If connection is None (False) it will run SetConnection().

like image 66
Jab Avatar answered Jan 28 '26 00:01

Jab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!