7

I'm writing custom django commands under my apps management/commands directory. At the moment I have 6 different files in that directory. Each file has a different command that solves a unique need. However, there are some utilities that are common to all of them. What is the best way to abstract away this common code?

Below is an example:

load_colors

class Command(BaseCommand):
   def handle(self, *args, **options)
      ....code unique to colors
   def check_validity(self, color)
      ....#code common to both shades and colors

load_shades

 class Command(BaseCommand):
   def handle(self, *args, **options)
      ....#code unique to shades
   def check_validity(self, color)
      ....#code common to both shades and colors
1
  • Maybe you should keep the common code in a .py file and import that wherever you want to use. That way you don't repeat your code. just call the existing. Commented Oct 29, 2015 at 4:11

1 Answer 1

7

In the management/commands folder create the file _private.py:

#_private.py
from django.core.management.base import BaseCommand, CommandError

class SharedCommand(BaseCommand):
   def check_validity(self, color):
      ...

The in other files import this file and inherit SharedCommand:

# command01.py
from ._private import *

class Command(SharedCommand):
    def handle(self, *args, **options):
        ...
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.