2

I'm using the coc-pyright extension of CoC in neovim.

There are cases where we have an instance method in a class that doesn't need to access self variables. For example, I may have some variables in __init__ method which do not need to be accessed anywhere else in the class. As a toy example, consider,

class Example:
    def __init__(self, some_var):
        self.another_var = self.process_var(some_var)

    def process_var(self, some_var):
        return some_var*2

Now, here pyright warns me that self is not accessed. Is there a way to set Pyright to not give a warning in such cases?

P.S. The variable being passed is an instance-specific variable. So self would be required to make it an instance variable, right?

Abhinav
  • 103
  • 2
  • 9

1 Answers1

4

So you're passing some_var to the method instead of using it as an instance variable, meaning you don't actually need self. You are using process_var as a static method, as it is being passed all of the data it needs. You can use the static method decorator and remove self like so:

class Example:
    def __init__(self, some_var):
        self.another_var = self.process_var(some_var)

    @staticmethod
    def process_var(some_var):
        return some_var*2

If you were to instead use the instance variable it would look like this

class Example:
    def __init__(self, some_var):
        self.some_var = some_var
        self.another_var = self.process_var()

    def process_var(self):
        return self.some_var*2

The static method approach is much cleaner here as by using instance variables you need to be aware of what the current state of some_var is before you call process_var, otherwise the results will vary.

You can set reportUnusedVariable to false in your pyrightconfig.json file, but I wouldn't recommend this as pyright is giving you valuable information about how to restructure your code.

  • What do you do if you're using a framework that calls your method with extra parameters you don't need. Usually I do `*args` and `**kwargs` to suck these up and not use them, but pyright complains about this, even with `reportUnusedVariable=false`. – Marcel Apr 04 '21 at 18:44
  • Generally I will put a `del unused_one, unused_two` towards the top of the function to delete the arguments and be clear that they are not used. It's the second recommendation in [this post](https://stackoverflow.com/questions/10025680/how-can-i-denote-unused-function-arguments) – Ethan Wright Apr 05 '21 at 01:07
  • What if the argument is a reference to something important? – Marcel Apr 05 '21 at 03:30
  • It just deletes it within the scope of your function, meaning you can't use the variable later on in the function. It doesn't delete it from the context of the caller. – Ethan Wright Apr 05 '21 at 03:48