16

Is there any preferred order when declaring multiple functions and classes in the same python file? Should functions or classes be declared first? What are the best practices?

PEP8 does not seems to give any recommendation

1
  • 6
    That's because it depends - if there's a function that's needed at class definition time, it must appear first. Superclasses must appear before subclasses. Decorators must appear before the functions/classes they decorate. Commented Feb 6, 2015 at 12:02

1 Answer 1

15

Generally, there is no preferred order. Depending on the program, a order can be needed:

  • You can decorate classes with functions. Then the decorator function must be defined before the class.
  • OTOH, you can decorate functions with classes. Then the decorator class must be defined before the function.
  • You can have classes be assigned class attributes which are determined by calling a function. Again, this function must be defined before the class.
Sign up to request clarification or add additional context in comments.

2 Comments

Also, type hints may require a class to be defined before a function. And to elaborate on the third point of @glglgl: default kwargs as well as attributes can call object constructors and functions, so it's possible to create a dependence on an arbitrarily specific ordering. Good reference for how to handle these situations: mail.python.org/pipermail/tutor/2009-August/071271.html
I guess a rule of thumb is those with fewer dependencies first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.