r/learnpython • • Mar 12 '24

Is python OOP the real thing ?

Hello, I'm currently writing a report on a project where I used python with the OOP paradigm and I want to be sure to not talk nonsense in it.

So, here is my question : Is python really fully respecting the OOP paradigm ?

I mean, for exemple when I want to make an abstract class, the concept doesn't really seem to exist. When I write an abstract method, I am obligated to use a decorator and it doesn't even prevent from calling the parent method. So i need to have a default behavior in it...

Also another question : I have seen that only mutable parameters can be updated in the body of a function. Is it specific to python or something generalized to other languages ?

4 Upvotes

35 comments sorted by

View all comments

9

u/Bobbias Mar 12 '24

OOP

The reply by u/cyberjellyfish is the best one as of writing this comment.

OOP is a nebulous concept, and modern definitions have strayed a fair bit from the intention of the creator.

However, ignoring that, Python still allows for modern OOP style programming.

It lacks some of the attributes some languages consider to be a core part of OOP, but that does not mean it automatically isn't OOP.

Abstract classes are nothing more than a class you cannot instantiate. From that perspective all your class needs to do is throw an exception when you try to instantiate it and it is now an abstract class.

The standard python equivalent to abstract classes (or interfaces, as they are sometimes referred to) are Protocols. Protocols cannot be instantiated by default (you could technically add __init__(), but that defeats the purpose of making it a Protocol in the first place).

If you have no default implementation for your abstract method, you raise a NotImplemented exception in the Protocol class definition, and leave it up to the subclasses to implement.

Python might not enforce the same rules that a language like Java, C++, or C# might, with regards to OOP, but that doesn't mean you can't write OOP code in Python.

Much of the difference with those languages comes from the fact that Python is dynamically typed. Consider the following code:

from typing import Protocol

class FooBar(Protocol):
    def foo(self) -> str:
        return "BAR1"


class A(FooBar):
    pass


class B:
    def foo(self) -> str:
        return "BAR2"


def fun(val: FooBar) -> None:
    print(val.foo())


fun(B()) # Prints "BAR2"

This code is perfectly valid in python, because as the documentation I linked describes, python supports structural subtyping, meaning as long as B has whatever attributes FooBar describes, this code will function as expected, even if B was never explicitly named as a subtype of FooBar.

By comparison, this would not work in any of the previously mentioned static languages because none of them support structural subtyping. B would be required to explicitly derive from FooBar. That doesn't change the fact that we are passing one of two subtypes to a function which expects objects of the parent class, which is a pattern commonly used in OOP.

This demonstrates that while Python may be different from some of the languages people think of when they think of OOP these days, you can still program the same kind of code that you typically use in those languages. In fact, you are less restricted in some ways due to the structural subtyping.

Mutable parameters

Most functions don't change their arguments. Methods often change the instance they are attached to, but freestanding functions should generally speaking not change their arguments with minor exceptions. Even then, you don't strictly need to mutate the list. You could just as easily build a new one with the required changes instead and return that. If your function mutates its input, it becomes more difficult to reason about:

from typing import List

def foo(lst: List[int]) -> List[int]:
    return [*lst, 5]


def bar(lst: List[int]) -> None:
    lst.append(5)


the_list = [1, 2, 3, 4]

# return a new list
print(foo(the_list))

# mutate the_list in place
bar(the_list)
print(the_list)

I would argue that foo makes a lot more sense than bar. It's more clear about what's happening (we're building a new list starting with the contents of the old one and inserting the value 5 at the end), and it creates a new object. We could replace the_list with if we wanted, or we could save it to a different variable, or pass it directly to another function as I do here.

With bar we have no such control, it mutates the_list and there is nothing we can do to avoid that. If we wanted to keep the original list around, we would need to copy it to another variable before calling bar. It's return type also tells us nothing useful. Since there's no documentation we'd need to go read the definition to see what it's even doing. If bar were a complex function which happens to work this way, it could take a fair bit of time to work out what's going on.

Of course, the other kind of mutable parameter is mutable default arguments, but those are a foot gun that you should generally avoid unless you absolutely need to use one. They are instantiated exactly once, at the beginning of the script, and their state persists throughout the entire life of the script. Any changes you make to a mutable default parameter persist between function calls (unlike local variables).

In the case of immutable values like Tuples, consider the following code:

the_tuple = (1, 2)

def foo(tpl: Tuple[int, int]) -> None:
    tpl = (5, 5)

foo(the_tuple)
print(the_tuple) # prints (1, 2)

At first glance it looks like this should work the same as changing the list in the function bar above, but because tuples are immutable, there is no way to mutate the value of a tuple once it's created. Any change to the_tuple must come from creating a new object and binding the name the_tuple to that new object, rather than modifying the existing object it points to at the start of the code.

1

u/MonsieurBouclier Mar 12 '24

Thank you for having taken the time to write this much of details in your answer, it was really heplful

1

u/Bobbias Mar 12 '24

No problem, I hope this helps.