2

I have some python code that contains unit tests like below:

class SunCalcTestCases(unittest.TestCase):
    """Tests for `suncalc.py`."""
    def near(val1, val2):
        return abs(val1 - val2) < (margin or 1E-15)

    def test_getPositions(self):
        """Get sun positions correctly"""
        sunPos = suncalc.getPosition(self.date, self.lat, self.lng)
        az = sunPos["azimuth"]
        res = self.near(az, -2.5003175907168385) 

But when I run this I get the error:

Traceback (most recent call last):
  File "test.py", line 64, in test_getPositions
    res = self.near(az, -2.5003175907168385)
TypeError: near() takes exactly 2 arguments (3 given)

I am new to python so I apologize if I am missing something here, but as far as I can tell I am only passing in two parameters when I call the function: self.near(az, -2.5003175907168385)

Can anyone tell me why it thinks I'm passing in 3 parameters?

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486

3 Answers3

6

You forgot to pass self in near function

def near(self, val1, val2):

Meaning of @classmethod and @staticmethod for beginner?

What is the difference between @staticmethod and @classmethod in Python?

Community
  • 1
  • 1
LittleQ
  • 1,860
  • 1
  • 12
  • 14
  • Oh - this is probably a stupid question, but why do I have to pass in `self` to my near function if I'm not referencing it there? – Abe Miessler Jul 21 '15 at 05:43
  • 3
    @AbeMiessler [refer](http://stackoverflow.com/questions/2709821/what-is-the-purpose-of-self-in-python) – Nagaraj Tantri Jul 21 '15 at 05:46
  • There are three kinds of method of a python class-object. @AbeMiessler https://docs.python.org/2/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls – LittleQ Jul 21 '15 at 05:47
2

It has been mentioned before but my answer would be "your method near should be static". Rather than passing self, I would make the method static using the @staticmethod decorator. This is given the fact that passing self has no benefits. Even more, if you pass self as an argument, a quality checker like Sonar Python Lint combination will flag it as "it should be static". This is something I often forget about it (Module function vs staticmethod vs classmethod vs no decorators: Which idiom is more pythonic?).

Also, I would recommend passing margin as a variable as well rather than making it a global variable which I imagine it is at the moment.

Community
  • 1
  • 1
zom-pro
  • 1,571
  • 2
  • 16
  • 32
1

The first variable in any class method is a reference to the class instance. Your method is expecting two variables: val1 and val2, but when you call self.near(val1, val2) it is the equivalent of calling a function with self, val1, and val2 as the arguments.

From Python Docs on Classes, second paragraph:

the method function is declared with an explicit first argument representing the object, which is provided implicitly by the call

bozdoz
  • 12,550
  • 7
  • 67
  • 96