3
# 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?

Warz
  • 7,386
  • 14
  • 68
  • 120

3 Answers3

4

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
Edwin van Mierlo
  • 2,398
  • 1
  • 10
  • 19
2

In File 2 perform import of the me object:

from file1 import me


class Book(me.Document):
    pass
    # ...
Alex Bausk
  • 690
  • 5
  • 29
  • This works great but if i then want to use the `Book` class in File1, I run into a circular reference. File 1 in this example is my `main.py`? – Warz Feb 12 '18 at 23:21
  • 1
    This has less to do with passing Python variables and more to do with the structure of your application. Apply standard circular resolution methods, for example import file2 at function level, or better yet remove implementation that depends upon `file2.py` from `file1.py` into a separate implementation file, thus breaking the circular dependency. – Alex Bausk Feb 13 '18 at 13:18
  • Also, you can simply avoid the `from x import y` construct to resolve circular imports automatically. This is a recommended answer on how Python imports work and how `import` differs from `from`: https://stackoverflow.com/questions/744373/circular-or-cyclic-imports-in-python – Alex Bausk Feb 13 '18 at 13:26
  • it seems to me that file1 is the script which is executed, hence I would not import file1 into file2, I would do it the opposite way. This also explains the circular reference problem. No need for circular references/imports – Edwin van Mierlo Feb 15 '18 at 14:35
1

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!

Mr.Zeus
  • 424
  • 8
  • 25