Python: Relative imports - python

I'm trying to use a package that has the following structure:
The file prova.py contains only the following line:
import bipartite_class
while bipartite_class.py has the following initial lines:
from .nes import *
from .mod import *
from .graphs import *
from .contrib import *
from .null import *
from .tests import *
from getref import *
import pickle
import tempfile
import os
import numpy as np
import networkx as nx
import os.path
When I try to compile prova.py I get the following error:
Traceback (most recent call last):
File "prova.py", line 1, in <module>
import bipartite_class
File "/Desktop/CD_BEST/Bipartito/bipy-master/bipy/bipartite_class.py", line 1, in <module>
from .nes import *
ValueError: Attempted relative import in non-package
If I try to remove the dots in bipartite_class.py I get:
Traceback (most recent call last):
File "prova.py", line 1, in <module>
import bipartite_class
File "/Desktop/CD_BEST/Bipartito/bipy-master/bipy/bipartite_class.py", line 1, in <module>
from nes import *
File "/Desktop/CD_BEST/Bipartito/bipy-master/bipy/nes/_init_.py", line 5, in <module>
from nodf import *
File "/Desktop/CD_BEST/Bipartito/bipy-master/bipy/nes/nodf.py", line 3, in <module>
from ..mainfuncs import *
ValueError: Attempted relative import beyond toplevel package
What should I do?

It looks like you're using this: https://github.com/tpoisot/bipy and that prova.py is your addition (it would be nice if you include this kind of information in your question in future questions!)
The problem is that bipartite_class is not a free-standing module, but is a part of the package bipy. That means you need to import it from outside the package. You need to move prova.py one directory up, to bipy-master, and change its contents to:
from bipy import bipartite_class
and then you should be able to run prova.py.
Even better would be to actually install bipy. Because the project includes a setup.py, you can run:
python setup.py install
Then you can import bipy from anywhere, so you can put your programs that use it in their own directory.

Related

ValueError: source code string cannot contain null bytes - Error after scipy.io import

After updating scipy, numpy and pandas to the newest versions, I receive the following error whenever I attempt to run my code on a Windows 10 machine with Python 3.7.4:
Traceback (most recent call last):
...
File "Path\To\MyClass.py", line 3, in <module>
import scipy.io as sio
File "Path\To\Anaconda\lib\site-packages\scipy\__init__.py", line 68, in <module>
from ._lib.deprecation import _deprecated
File "Path\To\Anaconda\lib\site-packages\scipy\_lib\__init__.py", line 12, in <module>
from scipy._lib._testutils import PytestTester
ValueError: source code string cannot contain null bytes
This is how the last file looks like:
"""
Module containing private utility functions
===========================================
The ``scipy._lib`` namespace is empty (for now). Tests for all
utilities in submodules of ``_lib`` can be run with::
from scipy import _lib
_lib.test()
"""
from scipy._lib._testutils import PytestTester
test = PytestTester(__name__)
del PytestTester
Am I running into a bug or is my setup broken?
I managed to solve this issue by reinstalling Anaconda. I still don't know the source of the problem though.

ModuleNotFoundError: No module named 'model'

I have a package with the following structure:
model\
__init__.py (from model.main_trainer import *, etc.)
main_trainer.py
snn.py
splitter.py
The main_trainer.py script takes at least three arguments as inputs:
#main_trainer.py
import numpy as np # Linear algebra
import pandas as pd # Data wrangling
import re # Regular expressions
import matplotlib
# Avoid plotting graphs
matplotlib.use('Agg')
# Custom dependencies
from model.snn import *
from model.splitter import *
def main_trainer(dataset_name, model_dict = None, train_dict = None,
how = 'k-fold cross-validation', save = True):
etc.
if __name__ == '__main__':
dataset_name, model_dict, train_dict, how = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
main_trainer(dataset_name, model_dict, train_dict, how)
However, if I run in the terminal the following:
python main_trainer.py dataset_name model_dict train_dict 'k-fold cross-validation'
I get the following error:
Traceback (most recent call last):
File "main_trainer.py", line 17, in <module>
from model.snn import *
ModuleNotFoundError: No module named 'model'
On the other hand, if I use the relative path as such:
# Custom dependencies
from .snn import *
from .splitter import *
I get this error:
Traceback (most recent call last):
File "main_trainer.py", line 17, in <module>
from .snn import *
ModuleNotFoundError: No module named '__main__.snn'; '__main__' is not a package
I have also tried running it as:
python -m main_trainer ...
and then I get this error:
Traceback (most recent call last):
File "/home/kdqm927/miniconda3/envs/siamese/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/home/kdqm927/miniconda3/envs/siamese/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/projects/cc/kdqm927/PythonNotebooks/model/main_trainer.py", line 17, in <module>
from .snn import *
ImportError: attempted relative import with no known parent package
I have checked these posts to no avail:
ModuleNotFoundError: What does it mean __main__ is not a package?,
Relative imports in Python 3
Append your script/module path with sys module then import your sub modules.
sys.path.append('/path/to/your/model/modules/')
Hope this will solve your problem.
Edit:
Modified your main_trainer file
#main_trainer.py
import numpy as np # Linear algebra
import pandas as pd # Data wrangling
import re # Regular expressions
import sys
import matplotlib
# Avoid plotting graphs
matplotlib.use('Agg')
# Custom dependencies
sys.path.append('/projects/cc/kdqm927/PythonNotebooks/model/') #folder which contains model, snn etc.,
from snn import *
from splitter import *

Cant import random python

I am having trouble importing random and randint in python
Here is the error I get when I "from random import randint"
Traceback (most recent call last):
File "/Users/Noah/Desktop/math.py", line 2, in <module>
from random import randint
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.py", line 45, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
File "/Users/Noah/Desktop/math.py", line 2, in <module>
from random import randint
ImportError: cannot import name randint
and here is the error I get when "import random"
Traceback (most recent call last):
File "/Users/Noah/Desktop/math.py", line 2, in <module>
import random
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.py", line 45, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
TypeError: 'module' object is not callable
when I go to /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7 to check the files it has random.py random.pyc and random.pyo
python is using this as the path
>>> print random.__file__
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.pyc
Edit: I have no clue what could be happening
The traceback is relatively clear:
you attempt to import randint from random;
inside the python random module it attempts to import names from math;
unfortunately, you chose to name one of your own modules in the working directory math as well and so it finds that first;
when importing your math, it attempts to import random ... now you have an circular import ... and it fails.
Conclusion:
In Python 2, don't name your modules identically to core python modules ...
In the same folder you have a file named math.py. You should delete this file, that is the reason it is not working.
My suggestion you may delete everything in that folder.
You should have save some file name random so the code is opening that file so try changing the name of that file

initialization of multiarray raised unreported exception python

I am a new programmer who is picking up python. I recently am trying to learn about importing csv files using numpy.
Here is my code:
import numpy as np
x = np.loadtxt("abcd.py", delimiter = True, unpack = True)
print(x)
The idle returns me with:
>> True
>> Traceback (most recent call last):
>> File "C:/Python34/Scripts/a.py", line 1, in <module>
import numpy as np
>> File "C:\Python34\lib\site-packages\numpy\__init__.py", line 180, in <module>
from . import add_newdocs
>> File "C:\Python34\lib\site-packages\numpy\add_newdocs.py", line 13, in <module>
from numpy.lib import add_newdoc
>> File "C:\Python34\lib\site-packages\numpy\lib\__init__.py", line 8, in <module>
from .type_check import *
>> File "C:\Python34\lib\site-packages\numpy\lib\type_check.py", line 11, in <module>
import numpy.core.numeric as _nx
>> File "C:\Python34\lib\site-packages\numpy\core\__init__.py", line 14, in <module>
from . import multiarray
>> SystemError: initialization of multiarray raised unreported exception
Why do I get the this system error and how can I remedy it?
I have experienced this problem too. This is cuased by a file named "datetime.py" in the same folder (exactly the same problem confronted by Bruce). Actually "datetime" is an existing python module. However, I do not know why running my own script, e.g. plot.py will invoke my datetime.py file (I have seen the output produced by my datetime.py, and there will be an auto-generated datetime.cpython-36.pyc in the __pycache__ folder).
Although I am not clear about how the error is triggered, after I rename my datetime.py file to other names, I can run the plot.py immediately. Therefore, I suggest you check if there are some files whose name collides with the system modules. (P.S. I use the Visual Studio Code to run python.)
As there is an error at the import line, your installation of numpy is broken in some way. My guess is that you have installed numpy for python2 but are using python3. You should remove numpy and attempt a complete re-install, taking care to pick the correct version.
There are a few oddities in the code:
You are apparently reading a python file, abcd.py, not a csv file. Typically you want to have your data in a csv file.
The delimiter is a string, not a boolean, typically delimiter="," (Documentation)
import numpy as np
x = np.loadtxt("abcd.csv", delimiter = ",", unpack = True)

Import error python

In Python, when I use this import statement breze.learn.mlp import iter_minibatches, am getting the following errors.
Here iter_minibatches is a function defined in mlp.py.
Traceback (most recent call last):
File "/home/vinod/PycharmProjects/MLPonTheano/MLPbreze.py", line 15, in <module>
from breze.learn.mlp import Mlp, FastDropoutNetwork
File "/home/vinod/breze/breze/learn/mlp.py", line 22, in <module>
from breze.learn.base import SupervisedModel
File "/home/vinod/breze/breze/learn/base.py", line 21, in <module>
from breze.learn.mlp import iter_minibatches
ImportError: cannot import name iter_minibatches
You have a circular import; mlp imports base imports mlp:
# executing mlp.py
File "/home/vinod/breze/breze/learn/mlp.py", line 22, in <module>
from breze.learn.base import SupervisedModel
# executing base.py
File "/home/vinod/breze/breze/learn/base.py", line 21, in <module>
# this tries to import from mlp again, but mlp isn't done yet
from breze.learn.mlp import iter_minibatches
Any line after the from breze.learn.base import SupervisedModel will not yet have been executed so importing any object defined by those lines will fail.
Avoid circular imports, or if you must have them, delay importing in one of the modules to make sure the objects you need in the other are defined.

Categories

Resources