2

I am new in python and trying to figure out how to modularize my functions. My project is a unit testing framework for Restful APIs. For brevity I've simplified the code.

type_parser.py

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--type', help='a or b')
args = parser.parse_args()

def A(func):
    def return_func():
        if args.type == "b":
          return func()
        else:
          pass
    return return_func

def B(func):
    def return_func():
        if args.type == "a":
          return func()
        else:
          pass
    return return_func

api_funcs.py

from type_parser import *

class ApiFunctions:

    @A
    def login():
        print "cool"
    @B
    def logout()
        print "not cool"

main.py

from api_funcs import *

api = ApiFunctions()

def __main__():
    api.login()
    api.logout()

__main__()

CLI

python main.py --type=a

Outcome

Expected:

cool

Actual:

TypeError: return_func() takes no arguments

It works if I take api functions out of a class and call it straight up, but I would want to make it more abstract since there will be 3 sets of APIs

Update - I figured out the answer

class ApiFunctions:

    @A
    def login(self):
        print "cool"
    @B
    def logout(self)
        print "not cool"


def A(func):
        def return_func(self):
            if args.type == "b":
              return func(self)
            else:
              pass
        return return_func
teddybear123
  • 2,314
  • 6
  • 24
  • 38
  • 2
    Well, `login` and `logout` are methods of `api`, and they're not static methods, so they have at least one argument..... –  Jan 25 '17 at 17:38
  • 1
    There's something missing in your methods. In particular note [What is the purpose of self](http://stackoverflow.com/questions/2709821/what-is-the-purpose-of-self) – dhke Jan 25 '17 at 17:38
  • I think it would be clearer if you posted your solution as an answer instead of editing your own post – TrakJohnson Jan 25 '17 at 18:06

1 Answers1

1

In python the object itself has to be explicitely part of method singature. Thus you need to write: def login(self):

Writing self.login is kinda like ()* writing login(self). Since login() takes no argument you get an error.


(*) said kinda like, don't write it


api_funcs.py

from type_parser import *

class ApiFunctions:

    @A
    def login(self):
        print "cool"
    @B
    def logout(self)
        print "not cool"
pltrdy
  • 2,069
  • 1
  • 11
  • 29