So, I've been using Ruby on Rails for some time, and I'm wondering if there is something like .presence in Python/Django.
Presence returns the receiver if it is present otherwise returns nil.
object.presence is equivalent to:
object.present? ? object : nil
For example, something like:
state = params[:state] if params[:state].present?
country = params[:country] if params[:country].present?
region = state || country || 'US'
becomes
region = params[:state].presence || params[:country].presence || 'US'
Anthony
In Python, you can achieve this by doing the following, assuming
paramsis adict:The method
dict.get(key)will return the value associated to the key that has been passed. If no such key exists, it returnsNone.If you need to replace the empty values with actual empty strings, you may do this instead:
Overall, the "Pythonic" way of doing this is to use a Form:
By creating a custom AddressForm class you can do this processing automatically on the instance before saving it. This is the precise role of Form classes.