1

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?

The Amateur Coder
  • 789
  • 3
  • 11
  • 33
  • 1
    Show a stack trace in all cases. What is actually causing the error? Check for unclosed parens on the previous line btw – Mad Physicist Mar 25 '22 at 03:34
  • 1
    Can you add the lambda you are trying to use to your question please? – Emrah Diril Mar 25 '22 at 03:56
  • There's no reason I can see for using an anonymous function here. Use a ternary expression. – ddejohn Mar 25 '22 at 05:27
  • `lambda` creates an anonymous function object -- it needs to be called in order to return anything. This is not a situation where you should use a lambda, period. – ddejohn Mar 25 '22 at 05:29
  • I guess this is related too and is a way other than using f-strings: https://stackoverflow.com/a/19213688/16136190. – The Amateur Coder Jul 16 '22 at 13:45

1 Answers1

0

If self.problematic_object is possibly None, and in that case you just want an empty string, simply use f-strings to add it to your overall string. No need for any boolean logic:

def __str__(self):
    return f"string1{self.object}\nstring2{self.another_object}\nstring3{self.problematic_object}"

If self.problematic_object is None then nothing will be added to the end of the string. If it's not None then its value will be added.

ddejohn
  • 8,775
  • 3
  • 17
  • 30