1

I have the following statement:

if Game.item_can_move(item_target) == True:
    return True + ""

else:
    return False + ", error"

but this doesn't seem to work. I would like to return a bool, str in both of the return.

Red
  • 26,798
  • 7
  • 36
  • 58
code_legend
  • 3,547
  • 15
  • 51
  • 95

2 Answers2

1

You can use three strategies here,

  1. Use Object Class
class Foo:
    def __init__(self): 
        self.foo = "foo"
        self.is_bar = True   
    
def my_method(): 
    return Foo() 
          
tmp = my_method()  
print(tmp.foo) 
print(tmp.is_bar)
  1. Use Tuple
def my_method(): 
    foo = "foo"
    is_bar = True
    return foo, is_bar
  1. Use a list/dic/..
def my_method(): 
    foo = "foo"
    is_bar = True
    return [foo, is_bar]

Reference

HadiRj
  • 1,015
  • 3
  • 21
  • 41
0

You can return multiple things at once with commas:

if Game.item_can_move(item_target) == True:
    return True, ""

else:
    return False, "error"

The reason your code didn't work is because you cannot concat a python str with a bool type. You can, however, do:

if Game.item_can_move(item_target) == True:
    return str(True) + ", "

else:
    return str(False) + ", error"

BTW, your code can be simplified:

b = Game.item_can_move(item_target)
if b:
    return b, ""
return b, "error"
Red
  • 26,798
  • 7
  • 36
  • 58
  • 1
    Further simplified: `return b, ("" if b else "error")` – wjandrea Jul 05 '20 at 18:53
  • Can be further simplified by removing `else` and going directly to the `return` statement – jdaz Jul 05 '20 at 18:53
  • @jdaz How, taking into account the different strings that need to be returned? – Red Jul 05 '20 at 19:02
  • 1
    To be clear, keep `return b, "error"`, but just take it out of the `else` block. If `b`, then it returns `b, ""` and the function ends. Then the only way it can get to the next line of `return b, "error"` is if `b` is falsey. So you don’t need `else`. – jdaz Jul 05 '20 at 19:08