[Tutor] method could be a function warning

Cameron Simpson cs at cskk.id.au
Wed Dec 22 20:22:30 EST 2021


First: "method could be a function warning" looks like a linter warning.  
Is it?

On 23Dec2021 11:59, Phil <phillor9 at gmail.com> wrote:
>I've been in the habit of mixing methods and functions within the GUI 
>class and to get the functions to work I've had to prefix the call to 
>the function with .self and add self as a function argument. The 
>function dummy in the following code is an an example of this.

Yes. If your linter's complaining, that is because the method does not 
use self. So it does not need to be a method. That does not not mean it 
_should _not_ be a method. A function which is tightly associated with a 
class conceptually does belong in the class. For example, perhaps you've 
got a method which constructs a string in a way specificly for use with 
this class. That would naturally be a method.

Python has a couple of decorators for methods which don't use self: 
@classmethod and @staticmethod. You would define dummy() like this and 
_still_ call it via self.

    @staticmethod
    def dummy():
        print('hello')

and linters will know you don't expect to use self. These have to do 
with the context needed for the method. _Mostly_ methods need self 
because they utilise the object state. Some might just need the class 
(for example to use some constants defined by the class) - they would 
need a classmethod:

    @classmethod
    def dummy2(cls):
        return cls.SOMETHING + 1

where SOMETHING is a class attribute. A staticmethod is just a function, 
and does not need the class or instance for context.

>It makes more sense to me, and I think it's correct, to define and 
>call the functions outside the GUI class as I've done with my_function 
>below.

A function outside a class is a general purpose utility function. I 
don't have many static methods, but those which are are conceptually 
related to the class. Here's an example from my Tag class:

    @staticmethod
    def is_valid_name(name):
        ''' Test whether a tag name is valid: a dotted identifier.
        '''
        return is_dotted_identifier(name)

So there's a Tag.is_valid_name(name) method for checking that a tag name 
is valid. It doesn't use the class or instance, but how it is 
implemented is a direct feature of the class. So it is a static method.

>Also, I'm thinking that the GUI class should be in a file of it's own 
>because the total number of lines of code exceeds 500 thus making 
>scrolling tedious.

You want a tags file, or whatever the equivalent is for your editor.  
Most code editors have a facility to jump to a symbol definition in your 
code. This reduces the concern with file size.

I prefer to break things up based on their conceptual structure. But 
there does come a size related time for breaking things up.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list