python - AttributeError: 'module' object has no attribute - python

I'm trying this simple code:
import requests
print requests.__file__
r = requests.get('https://github.com/timeline.json')
It works flawlessly on the command line when I type the lines one by one, but not whenen when I execute it as a script or in Sublime Text 2. Here's the stack trace:
C:\Python27\lib\site-packages\requests\__init__.pyc
Traceback (most recent call last):
File "C:\Users\Bruce\Desktop\http.py", line 1, in <module>
import requests
File "C:\Python27\lib\site-packages\requests\__init__.py", line 53, in <module>
from requests.packages.urllib3.contrib import pyopenssl
File "C:\Python27\lib\site-packages\requests\packages\__init__.py", line 3, in <module>
from . import urllib3
File "C:\Python27\lib\site-packages\requests\packages\urllib3\__init__.py", line 16, in <module>
from .connectionpool import (
File "C:\Python27\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 15, in <module>
from http.client import HTTPConnection, HTTPException
File "C:\Users\Bruce\Desktop\http.py", line 3, in <module>
r = requests.get('https://github.com/timeline.json')
AttributeError: 'module' object has no attribute 'get'
[Finished in 0.2s with exit code 1]
Answers on 'Module object has no attribute 'get' Python error Requests? didn't help much.
Could this be some error in my ST2 Python build system? I tried removing all requests modules in case there were multiples of them by using pip and reinstalled them.

Edit After reading the stacktrace again, you can see that urllib3 tries to import something from the http module. Your file is called http.py and is thus imported instead of the expected one.
The actual error happens because of the circular nature of the import. Since requests hasn't finished importing completely yet. The get function in requests isn't defined yet when the http import reaches import requests again.
Note: You will also want to always guard your entry point with the if __name__ == '__main__' construct. This will often avoid nasty errors for unsuspecting future developers (including yourself).

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.

It is a simple source code, but it does not run

import tailer
test = tailer.tail(open("test.txt"), 1)
#print(lines[1])
It's as simple as the code above, but it doesn't work.
(I saved it because it was successful once during the experiment, but an error occurs when I run it again later.)
Error content:
Traceback (most recent call last):
File "c:\Users\user\Documents\VSCODE\python\V1\tailer.py", line 1, in <module>
import tailer
File "c:\Users\user\Documents\VSCODE\python\V1\tailer.py", line 3, in <module>
test = tailer.tail(open("test.txt"), 1)
AttributeError: partially initialized module 'tailer' has no attribute 'tail' (most likely due to a circular import)
Looks like your file is called tailer.py, so when it does import tailer, it tries to load itself, which is usually a recipe for confusion.
You named your program tailer.py. When you do an import tailer the local folder has priority over all other folders and you will import tailer.py again. Creating an import circle.
In other words: you have a name clash between your program and the library you are trying to import. Just rename the file to something else and try again.

Python. from dateutil.relativedelta import * works in shell but not in a script [duplicate]

This question already has answers here:
Importing installed package from script with the same name raises "AttributeError: module has no attribute" or an ImportError or NameError
(2 answers)
Closed 5 years ago.
When I go to run
from datetime import *; from dateutil.relativedelta import *
from a python script I get a error which to me seems to indicate a problem with the module itself.
Traceback (most recent call last):
File "C:\Users\Tom\Documents\datetime.py", line 1, in <module>
from datetime import *
File "C:\Users\Tom\Documents\datetime.py", line 2, in <module>
from dateutil.relativedelta import *
File "C:\Users\Tom\AppData\Local\Programs\Python\Python35\lib\site-packages\python_dateutil-2.0-py3.5.egg\dateutil\relativedelta.py", line 11, in <module>
import calendar
File "C:\Users\Tom\AppData\Local\Programs\Python\Python35\lib\calendar.py", line 47, in <module>
class _localized_month:
File "C:\Users\Tom\AppData\Local\Programs\Python\Python35\lib\calendar.py", line 49, in _localized_month
_months = [datetime.date(2001, i+1, 1).strftime for i in range(12)]
File "C:\Users\Tom\AppData\Local\Programs\Python\Python35\lib\calendar.py", line 49, in <listcomp>
_months = [datetime.date(2001, i+1, 1).strftime for i in range(12)]
AttributeError: module 'datetime' has no attribute 'date'
This however, does not happen when I use the exact same statement in the python shell, if used in the shell it works perfectly.
I did find that it directly related to relativedelta part of dateutil, as
from dateutil import *
works fine.
I have tried reinstalling dateutil but thats pretty much it.
Running python 3.5.1 with dateutil 2.0 if it matters.
EDIT: SORRY I'M AN IDIOT, my file was called datetime.py which was what caused the problem.
I believe it's the source file name. I am guessing when python interpreter tries to find datetime module it would search the local directory first and the datetime module would be your source file than the datetime global package. this post explains more
Once you would rename your file to say dd.py instead of "C:\Users\Tom\Documents\datetime.py" it should work out.

python3 ImportError: cannot import name 'rand_str'

Im getting this error when starting my software i dont know how to repair this
Traceback (most recent call last):
File "/root/findex/lib/python3.5/site-packages/findex_gui/main.py", line 208, in web
run_async()
File "/root/findex/lib/python3.5/site-packages/findex_gui/main.py", line 201, in run_async
from findex_gui.web import app
File "/root/findex/lib/python3.5/site-packages/findex_gui/web.py", line 41, in <module>
from findex_gui.orm.connect import Database
File "/root/findex/lib/python3.5/site-packages/findex_gui/orm/connect.py", line 12, in <module>
from findex_gui.orm.models import BASE
File "/root/findex/lib/python3.5/site-packages/findex_gui/orm/models.py", line 22, in <module>
from findex_common.utils import rand_str
ImportError: cannot import name 'rand_str'
I'm not familiar with the libraries in question, but it seems the maintainer renamed this function in 0.15.14 of findex-common here: development
This has been adjusted for in findex-gui on the master branch though it seems it has not seen a release. Here's the commit which fixes the import: Forgot what I was doing - Ill just push it all ¯_(ツ)_/¯
One short term fix would be to downgrade to findex-common==0.15.13 and perhaps follow up by raising an issue on either project since the change seems non-ideal.

Getting AttributeError: 'module' object has no attribute 'DEFAULT_MAX_REDIRECTS' when running Google Sheets API quickstart

I'm following this guide https://developers.google.com/sheets/api/quickstart/python
Upon running the sample code they provided (The only thing I changed was the location of the api secret since we already had one set up and the APPLICATION_NAME) I get this error
AttributeError: 'module' object has no attribute 'DEFAULT_MAX_REDIRECTS'
Log before the error
File "generate_report.py", line 2, in <module>
import httplib2
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/httplib2/__init__.py", line 42, in <module>
import calendar
File "/Users/HarshaGoli/Git/PantherBot/scripts/calendar.py", line 1, in <module>
from oauth2client.service_account import ServiceAccountCredentials
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/oauth2client/service_account.py", line 25, in <module>
from oauth2client import client
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/oauth2client/client.py", line 39, in <module>
from oauth2client import transport
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/oauth2client/transport.py", line 255, in <module>
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
I got the same error and investigated on the problem.
In my case, it was caused by a file named ''calendar.py" in the same directory.
It's said you should avoid using general names that can be used for standard python library.
It may be versioning problem. It could be python3 version of httplib2 which cause troubles, try to follow answer from this post

Categories

Resources