Warz
Warz

Reputation: 7766

Define Python class in separate file

# File 1
me = MongoEngine(app) # I want to use my instance of MongoEngine to define new classes like the example in File 2

# File 2
class Book(me.Document):
    title = StringField(null=False, unique=True)
    year_published = IntField(null=True)

How can i pass the instance me.Document as an Object definition when creating my new classes in a new file. It works if i put them in the same file?

Upvotes: 3

Views: 14772

Answers (3)

Mr.Zeus
Mr.Zeus

Reputation: 464

Just like any Python object in a file, me can be imported. You can do it like so:

import file1
class Book(file1.me.Document):
    #Do what you want here!

Hope I have helped!

Upvotes: 1

Edwin van Mierlo
Edwin van Mierlo

Reputation: 2488

I believe that the answer choosen as answer is not fully correct.

It seems that File1.py is your main script which is executed, and File2.py is a module which contains a class you wish to use in File1.py

Also based on a previous question of the OP I would like to suggest the following structure:

File1.py and File2.py are located in the same direcory

File1.py

import MongoEngine
from File2 import Book

me = MongoEngine(app)

# according to the documentation
# you do need to pass args/values in the following line
my_book = Book(me.Document(*args, **values))
# then do something with my_book
# which is now an instance of the File2.py class Book

File2.py

import MongoEngine

class Book(MongoEngine.Document):

    def __init__(self, *args, **kwargs):
        super(Book, self).__init__(*args, **kwargs)
        # you can add additional code here if needed

    def my_additional_function(self):
        #do something
        return True

Upvotes: 5

Alex Bausk
Alex Bausk

Reputation: 718

In File 2 perform import of the me object:

from file1 import me


class Book(me.Document):
    pass
    # ...

Upvotes: 2

Related Questions