I'm trying to use a lambda
to check if an object (self
)'s attribute problematic_object
is None
. If it is, it should return a ""
(an empty string), and if not, str(self.problematic_object)
. I've tried doing it in 3 ways:
1:
def __str__(self):
return "string1" + str(self.object) + "\n" + "string2" + self.another_object + "\n" + "string3" + exec(lambda self: str(self.problematic_object) if self.problematic_object!=None else "")
2:
def __str__(self):
return "string1" + str(self.object) + "\n" + "string2" + self.another_object + "\n" + "string3" + (lambda self: str(self.problematic_object) if self.problematic_object!=None else "")
3:
def __str__(self):
return "string1" + str(self.object) + "\n" + "string2" + self.another_object + "\n" + "string3" + lambda self: str(self.problematic_object) if self.problematic_object!=None else ""
I get this error in all the cases:
SyntaxError: invalid syntax
I know that this can be done using a normal if-else
, but is there any way I can do it using a lambda
? This is my first time using a lambda
and this kind of an if-else
. What is the mistake I'm making? Can a lambda
be used like this?