quantifiedcode / python-anti-patterns

An open collection of Python anti-patterns and worst practices.
https://quantifiedcode.github.io/python-anti-patterns
Other
1.71k stars 249 forks source link

Method could be a function #130

Open hjp opened 5 years ago

hjp commented 5 years ago

I couldn't get python (neither 2.7, nor 3.5 or 3.7) to raise a Method could be a function error on your example (or reasonable variations, like actually calling Rectangle.area). If this is obsolete, please update the page to describe the behaviour of current python versions. Otherwise, update the example to reproduce the error.

Also, you refer to self and cls as keywords. At least in Python 3 they aren't. There is just a (pretty strong) convention to call the first parameter of an instance method self and the first parameter of a class method cls.

qbedard commented 3 years ago

Yeah, the is section is just wrong. "Method could be a function" comes from Pylint, not Python itself, and cls and self are not keywords.

qbedard commented 3 years ago
  1. This section and the section following it ("Method has no argument") present several examples as anti-patterns that are really just logical errors. The user will find out pretty quickly that not including self as an argument means that you can't reference self. We should nuke those examples.

  2. The actual anti-pattern here is creating methods that should be functions, like so:

    class Foo:
        def bar(self, a, b):  # should be a function
            return a + b
    def bar(a, b):
        return a + b
    
    class Foo:
        ...

    If it doesn't need the instance (or class in the case of @classmethod), it shouldn't be a method.

  3. We should also note that the use of @staticmethod is discouraged. Guido has even pointed out that @staticmethod was a mistake.