1

I have this function code

   def getList(self, cursor=self.conn_uat.cursor()):
        from pprint import pprint
        cursor.execute(...)

I am getting this error

NameError: name 'self' is not defined

The reason i am using in args is so that i dont put any dependency inside any function to make testing easier

user3113427
  • 415
  • 1
  • 6
  • 16

2 Answers2

3

self is only available inside the method getList. However, you are trying to access outside of the method in the function declaration line. Hence, you get a NameError.

I think the easiest/cleanest solution would be to do this instead:

def getList(self, cursor=None):
    from pprint import pprint
    cursor = self.conn_uat.cursor() if cursor is None else cursor
    cursor.execute(...)

The functionality of the above code is identical to what you were trying to use.

Also, here is a reference on conditional operators if you want it.

Community
  • 1
  • 1
0

The function is defined in the class declaration, so the specific instance isn't known. The arguments are created at definition, not at run

Here's another example of it: "Least Astonishment" and the Mutable Default Argument

Community
  • 1
  • 1
mhlester
  • 21,143
  • 10
  • 49
  • 71