How to create package in python 3.5.1? - python-3.x

I have tried to create a package using python 3.5.1 , but got the error when i import the package.
Traceback (most recent call last):
File "Pack.py", line 2, in
import Com
File "C:\Users\admin\Document\Python\packages\Com__init__.py",
line 2, in
from Algebra import *
ImportError: No module named 'Algebra'

To import a package you created named Algebra, your folder structure should look similar to this:
C:\Users\admin\Document\Python\packages\
Com__init__.py
Algebra\
__init__.py
.
.
.
Alternatively, you can put the Algebra packages parent directory on python's sys.path.
You'll likely run into another issue once you resolve this, which is you cannot import * from the Algebra package without specifying the all trait in Algebra's init.py file. Specifying this done like the following, but replacing the values of the list with your module names:
__all__=['add', 'subtract', 'multiply']
Source: https://docs.python.org/3/tutorial/modules.html#packages

Related

Python Relative Imports but I copied the documentation

I read all the other SO posts about this and it either doesn't work or uses sys.path.append.
Below is a replica of the official documentation:
All other files not shown are empty
moduleA.py
from ..subB.moduleB import MyClass
moduleB.py
class MyClass:
def __init__(self):
pass
package/subB/__init__.py
from .moduleB import MyClass
Traceback from running moduleA.py
Traceback (most recent call last):
File "path\to\my\projects\folder\package\subA\moduleA.py", line 1, in <module>
from ..subB.moduleB import MyClass
ImportError: attempted relative import with no known parent package
File Structure
The Python docs unfortunately forget to mention that their example only works if you run your code in a very specific way using the '-m' switch. So you would have to do python -m subA.moduleA and you need to ensure that your current working directory is package. Otherwise it will fail.
If you don't like these restrictions (like me), I've created an experimental import library: ultraimport
It gives you more control over your imports and lets you do file system based imports.
In moduleA.py you could then write:
import ultraimport
MyClass = ultraimport('__dir__/../subB/moduleB.py', 'MyClass')
This will always work, no matter how you run your code or what is your current working directory. Also no need to change sys.path. It will actually go to the file system and load the very file you've specified.

how to import custom modules in Cloud Composer

I created a local project with apache Airflow and i want to run it in cloud composer. My project contains custom modules and a main file that calls them.
Example : from src.kuzzle import KuzzleQuery
Structure:
main.py
src
kuzzle.py
I have imported my project folder in data storage and when i refreshed the UI of airflow composer i've got this error:
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/airflow/gcs/dags/quality-control/main.py", line 8, in <module>
from src.kuzzle import KuzzleQuery, Tag
ModuleNotFoundError: No module named 'src' ```
Try adding an __init__.py file inside src directory to make it a module.
GCP Composer is loading the dags folder as a python module, so you can just put your code there in a separate file or folder and it will work as usual referencing it from the dags.
dags/
dag1.py
util.py
Then you can reference util and import it from dag1 as:
from util import custom_function
If dags folder does not work for you composer also loads more directories like the ones for loading modules.
You can also check this question since it is also related.
Airflow dag dependencies not available to dags when running Google's Cloud Compose
You could check these options:
The path of the module is not correct
Probably, you would want to import a module file, but this module is not in the same directory.
For example:
Project Structure
core.py
folder_1
---module.py
We want to import the module.py
Core.py
import module.py #incorrect
Output:
ModuleNotFoundError: No module named 'module'
Core.py
import folder_1.module.py #correct
Output:
...Program finished with exit code 0
The library not Installed
If you want to import a module of a library which is not installed in your virtual environment before importing a library's module, you need to install it with the pip command. You could see this documentation:
For example, import Beautifulsoup4 library it is not installed
>>> from bs4 import BeautifulSoup
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'bs4'
Now, let's install the library and try to re-import it
Installing:
pip install beautifulsoup4
Collecting beautifulsoup4
Using cached https://files.pythonhosted.org/packages/d1/41/e6495bd7d3781cee623ce23ea6ac73282a373088fcd0ddc809a047b18eae/beautifulsoup4-4.9.3-py3-none-any.whl
Requirement already satisfied: soupsieve>1.2; python_version >= "3.0" in /home/py/Desktop/seo_pro/seo_env/lib/python3.6/site-packages (from beautifulsoup4) (1.9.5)
Installing collected packages: beautifulsoup4
Successfully installed beautifulsoup4-4.9.3
Re-importing:
>>> from bs4 import BeautifulSoup
>>>
Setup your files as packages and modules
You need to properly set up your files as packages and modules.
Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A. Just like the use of modules saves the authors of different modules from having to worry about each other’s global variable names, the use of dotted module names saves the authors of multi-module packages like NumPy or Pillow from having to worry about each other’s module names.
sound/ Top-level package
__init__.py Initialize the sound package
formats/ Subpackage for file format conversions
__init__.py
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
auread.py
auwrite.py
...
effects/ Subpackage for sound effects
__init__.py
echo.py
surround.py
reverse.py
...
filters/ Subpackage for filters
__init__.py
equalizer.py
vocoder.py
karaoke.py
You could see more information.

Import don't run in python

I am developing a Django project and I am trying to run a test file but an error in the import occurre.
My folder hierarchy to be like the image:
see the image of function process_data inside of core.py
I am in the test directory trying to run my test file.
My import to be like the code:
from coordenadas.core import process_data
but, when I run my code an error is showed:
Traceback (most recent call last):
File "tests_class_moviment.py", line 1, in <module>
from coordenadas.core import process_data
ModuleNotFoundError: No module named 'coordenadas'
I am tryed use relative import
from .coordenadas.core import process_data
from .core import process_data
from ..coordenadas.core import process_data
from ..core import process_data
but the only way that no error is showed in pycharm is the
from coordenadas.core import process_data
Some idea how can I solve it?
On a partially unrelated note, absolute imports are definitely recommended over relative imports. PEP8:
Relative imports for intra-package imports are highly discouraged. Always use the absolute package path for all imports. Even now that PEP 328 [7] is fully implemented in Python 2.5, its style of explicit relative imports is actively discouraged; absolute imports are more portable and usually more readable.
As for the module error itself, adding an __init__.py file to the "coordenadas" directory will turn it into a module, which is exactly what you need.

Python module not recognizing files in the same folder

I've made (at least tried) a package using setuptools and attempted to use it from another python-file. However, the modules within the packages don't seem to recognize each other.
Tree
pkg
|-- pkg
| |-- __init__.py
| \-- module.py
\-- setup.py
__init__.py:
import module
#code
pyfile.py
import pkg
#code
When I attempt to run pyfile.py, I get
Traceback (most recent call last):
File "/.../py/pyfile.py", line 1, in <module>
import pkg
File "/.../pkg/pkg/__init__.py", line 1, in <module>
import module
ModuleNotFoundError: No module named 'module'
It works fine if I write import pkg.module, but I don't see why self.referential code would be practical.
Change the import in your __init__ to
from . import module
You can read more about intra-package references in the python documentation.
(BTW, as far as I can tell, setuptools is not involved here.)

Imports not found when running script outside of Pycharm?

I have a project structured this way...
main.py imports scripts from subfolders like so:
from controllers.available_balances_controller import available_balances_controller
Subfolders:
models
views
controllers
When running main.py in Pycharm it works find.
When I try to run in terminal I get import errors:
Traceback (most recent call last):
File "main.py", line 6, in <module>
from controllers.available_balances_controller import available_balances_controller
ImportError: No module named controllers.available_balances_controller
Am I importing the scripts wrong in main.py?
What is the proper way to do the importing?
Try running your script with the -m flag:
$ python -m main
That means that you are running your main.py as a module inside a python package, not as a simple script. PyCharm makes it easy for you by assuming so when you create a project. When you are in the terminal, you need to specify it yourself. You don't need __init__.py files inside your directories in Python3.
Check out:
https://docs.python.org/3/reference/import.html
Relative imports in Python 3

Resources