Dhanushka Amarakoon
Dhanushka Amarakoon

Reputation: 3762

Python - return or print none types on exception

   return str(self.id)+"-Vacancy for "+self.title+" at "+self.company.company_name or str(self.id)+"-Vacancy for "+self.title or self.id

I have a few variables some of which can be of None type. How can I print them without throwing exceptions or having try catch blocks.

Upvotes: 0

Views: 30

Answers (1)

rafaelc
rafaelc

Reputation: 59274

You could build a response string like the following

ret = ""
ret += str(self.id) if self.id is not None else ""
ret += "-Vacancy for "
ret += self.title if self.title is not None else ""
ret += self.company.company_name if self.company.company_name is not None else ""
return ret

Or define a function and parse each item, like the following:

def parsed(string):
   return string if string is not None else ""

(...)

return parsed(str(self.id))+"-Vacancy for "+parsed(self.title)+" at "+parsed(self.company.company_name or str(self.id))+"-Vacancy for "+parsed(self.title or self.id)

Upvotes: 1

Related Questions