Search code examples
pythongoogle-app-enginecode-formattingproject-structurecode-structure

How to organize Python source code files?


I am developing a Python App Engine app, where I want to split the content of a source code file Models.py into separate files for each model, but I want to put it all in a folder called Models. The problem is that when I do that, my app can't find the classes anymore. What should I do?

This question is not about MVC but another question with the same title is.


Solution

  • Put an empty __init__.py file in the Models directory.

    Then, in your app; presumably one level up, you reference modules in the Models directory like this:

    import Models
    

    and do something with it like this:

    Models.my_model.MyClassName
    

    You can also use the from keyword like this:

    from Models import my_model
    

    and reference like this:

    my_model.MyClassName
    

    If you only need one method from a module, you could also do this:

    from Models.my_model import my_method_name
    my_method_name()
    

    Obligatory link to the documentation.