Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import python class file from same directory?

I have a directory in my Python 3.3 project called /models.

from my main.py I simply do a

from models import * 

in my __init__.py:

__all__ = ["Engine","EngineModule","Finding","Mapping","Rule","RuleSet"] from models.engine import Engine,EngineModule from models.finding import Finding from models.mapping import Mapping from models.rule import Rule from models.ruleset import RuleSet 

This works great from my application.

I have a model that depends on another model, such that in my engine.py I need to import finding.py in engine.py. When I do: from finding import Finding

I get the error No Such Module exists.

How can I import class B from file A in the same module/directory?

like image 866
Yablargo Avatar asked Jan 15 '14 13:01

Yablargo


People also ask

How do you access a class from another file in Python?

Python modules can get access to code from another module by importing the file/function using import. The import statement is that the commonest way of invoking the import machinery, but it's not the sole way. The import statement consists of the import keyword alongside the name of the module.

How do I import a file from one directory to another in Python?

We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.

Should I put Python classes in separate files?

As Python is not an OO language only, it does not make sense do have a rule that says, one file should only contain one class. One file (module) should contain classes / functions that belong together, i.e. provide similar functionality or depend on each other. Of course you should not exaggerate this.


2 Answers

Since you are using Python 3, which disallows these relative imports (it can lead to confusion between modules of the same name in different packages).

Use either:

from models import finding 

or

import models.finding 

or, probably best:

from . import finding  # The . means "from the same directory as this module" 
like image 83
RemcoGerlich Avatar answered Sep 22 '22 16:09

RemcoGerlich


Apparently I can do: from .finding import Finding and this works.

And the answer below reflects this as well so I guess this is reasonably correct.

I've fixed up my file naming and moved my tests to a different directory and I am running smoothly now. Thanks!

like image 25
Yablargo Avatar answered Sep 26 '22 16:09

Yablargo