Thanks @Vic_T that’s great to hear 
I’ve been caught out by indentation on subclasses more than once myself – pretty confusing when it works but does the exact opposite of what is written!
It’s often class attributes that get lost in another function – this can be helped by always following the same structure for your classes, e.g.
class MyClass:
<attribute definitions>
<dunder methods>
<other methods>
…at least then you can’t accidentally do…
class MyClass:
def __init__(self):
# something here
attribute1 = 1
def another_method(self):
# ....
With methods the only advice I can give is –
- keep your methods short
- keep indentation to a minimum (see below)
- avoid having multiple blank lines in the method body (easily looks like a gap to slot something into).
…this can be quite a bit different from other languages, but you’ll get used to it.
For indentation the following examples should give some ideas. Starting from a function, then removing indentation (same result).
def another_method(x, y, z):
if x > 5:
return True
else:
return False
def another_method(x, y, z):
if x > 5:
return True
return False
def another_method(x, y, z):
return x > 5
The main path through a function should (generally) be unindented. This is the default path – check your conditions before and return
if needed. Using return
without a parameter is the same as falling out the bottom of a function (returns None
).
def another_method(x, y, z):
if x > 5:
if y > 3:
# blah blah blah
# blah blah blah
# blah blah blah
def another_method(x, y, z):
if not (x > 5 and y > 3):
return
# blah blah blah
# blah blah blah
# blah blah blah
You can do this even if you have multiple steps, eg.
def another_method(x, y, z):
if x > 5:
# blah blah blah
if y > 3:
# blah blah blah
# blah blah blah
def another_method(x, y, z):
if not x > 5:
return
# blah blah blah
if not y > 3:
return
# blah blah blah
# blah blah blah
It can feel a bit backwards – you’re checking for what you don’t want. Think of it as checking whether “something is wrong” and you need to pull the ejector seat.
The side effect of all this is that the last line of your function (or method) will not be indented so it’s harder to accidentally add something inside it.
This went on a bit, but I hope it was useful 