stevendesu
stevendesu

Reputation: 16781

How to "namespace" methods in Python class

I want a class in Python with an interface like the following:

import myclass

client = myclass.Client("user", "password")

client.users.create("user1")
client.posts.create("user1", "Hello, World!")

Note that instead of just create_user or create_post, I want to specify the method using two dots: users.create / posts.create

I want this particular interface to mimic an HTTP API I'm trying to work with (which has endpoints like "/api/users/create" and "/api/posts/create")

If I define my class as follows in myclass.py:

class Client(object):
    def __init__(self, user, pass):
        self.user = user
        self.pass = pass

Then how do I create these dot-namespaced methods? My first thought is to create subclasses like so:

class Client(object):
    def __init__(self, user, pass):
        self.user = user
        self.pass = pass
        self.users = ClientUserAPI()
        self.posts = ClientPostAPI()

class ClientUserAPI(object):
    def create(self):
        # Do some cURL magic

class ClientPostAPI(object):
    def create(self):
        # Do some cURL magic

However if I do this, then I run into one of two problems (one serious, the other just philosophical / ideological)

  1. If ClientUserAPI extends "Client" then the __init__ method creates an infinite loop
  2. If ClientUserAPI extends "object" then it won't directly have access to the self.user and self.pass variables. This means I must create __init__ methods on both of the helper classes which do nothing but assign self.user and self.pass. This is redundant not only in code, but also in memory

Is there a better solution?

Upvotes: 2

Views: 2930

Answers (1)

internet_user
internet_user

Reputation: 3279

class Client:
  def __init__(self):
    self.users = ClientUserAPI(self)
    self.posts = ClientPostAPI(self)

class ClientUserAPI:
  def __init__(self, client):
    self.client = client

class ClientPostAPI:
  def __init__(self, client):
    self.client = client

Upvotes: 5

Related Questions