Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python declaration order: classes or functions first?

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

like image 539
devhallo Avatar asked Feb 06 '15 11:02

devhallo


People also ask

Does order of function declaration matter in Python?

So in general, yes, the order does matter; there's no hoisting of names in Python like there is in other languages (e.g JavaScript). Save this answer.

Are functions considered first class objects in Python?

In Python, functions behave like any other object, such as an int or a list. That means that you can use functions as arguments to other functions, store functions as dictionary values, or return a function from another function. This leads to many powerful ways to use functions.

Which method executed first in Python?

Python follows depth-first order to resolve the methods and attributes. So in the above example, it executes the method in class B.

Can a function be called before it is defined in Python?

It is not possible. Python does not allow calling of a function before declaring it like C. This is possible in some languages like JavaScript but not in Python. This means Python does not allows calling before declaring.


1 Answers

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.
like image 96
glglgl Avatar answered Sep 24 '22 07:09

glglgl