Joel
Joel

Reputation: 1690

Pythonic way set variables if none in __init__

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?

Upvotes: 3

Views: 1847

Answers (5)

keepAlive
keepAlive

Reputation: 6655

Just for fun, why not do

def __init__(self, **kwargs):
    self.connection = kwargs.get('connection', SetConnection())

Which puts aside problems related to falsy values while being pythonic. That being said, it has other drawbacks for sure, e.g. those related to the idea of auto-documentability of the code.

Upvotes: 0

Pedro Lobito
Pedro Lobito

Reputation: 98901

My 2c using isinstance :

def __init__(self, connection=None, some=None, thing=None, else=None):
   if isinstance(connection, "class/type of connection") :
       self.connection = connection    
   else:
       self.connection = SetConnection()

Old answer:

self.connection = connection if connection else SetConnection()

PS: I'm not aware of the class or type of connection, if you also don't know it, usetype(connection)

Upvotes: 0

jez
jez

Reputation: 15349

If you don't need to record, for any further reason, the fact that connection was originally passed as None, then you could overwrite that name:

if connection is None: connection = SetConnection()
self.connection = connection

Upvotes: 1

Daniel
Daniel

Reputation: 42748

Use ternary operator

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

Upvotes: 1

Jab
Jab

Reputation: 27485

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().

Upvotes: 4

Related Questions