Reputation: 83
If suppose I have a file full of functions in python naming basics.py which does not have a class inside it. and there's no __init__() function too. Now if I want to access the functions of basics.py inside the views.py . How can I do that?
Upvotes: 1
Views: 6490
Reputation: 4137
This is a common mistake because python 3 have stricter rules when it comes to relative imports.
I assume you have a structure like this.
myapp
├── basics.py
└── views.py
.. where myapp
is in the root of your project.
Let's assume basics.py
looks like this.
def do_stuff():
pass
The ways you can import things from basic would then be (views.py
)
from myapp import basics
from myapp.basics import do_stuff
from . import basics
from .basics import do_stuff
# View code ...
I assumed here that basics.py
and views.py
are located in the same package (app
).
When you run a python project your current directory is added to the python path. You will either have to import all the way from the root of your project or use .
to import from the local package/directory.
Also notice in the example that you can import the entire module or just single functions/objects. When importing the entire basics
module you access it using basics.do_stuff()
in the view.
Upvotes: 2