1

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?

8
  • use an import statement in views.py import basics Commented Jun 26, 2017 at 12:20
  • 3
    docs.python.org/3/tutorial/modules.html You should read more about Python. Commented Jun 26, 2017 at 12:21
  • 1
    Not having a class is usual. There is absolutely no need for one if you're not keeping state. And __init__() methods are only used within classes anyway. Commented Jun 26, 2017 at 12:22
  • Are you using Python 2 or 3? Commented Jun 26, 2017 at 12:43
  • If you can share your project structure, that would help a lot. Commented Jun 26, 2017 at 12:45

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

use:

import basics

than use all the functions you want :)

2 Comments

This assumes the person is using a relative import in python 2 or the module is in the root of the python path.
it gives me an error saying unresolved reference 'basics'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.