Rectangle 27 2

if Connection_Type == '1':
    conn = 'Telnet()' 
elif Connection_Type == '2':
    conn = 'SSH2()'
'Telnet()'.connect
'SSH2()'.connect

If you have imported SSH or Telnet from somewhere and presuming they are classes then remove the single quotes and you will create an instance which should work once the classes have a connect method.

if Connection_Type == '1':
    conn = Telnet()
elif Connection_Type == '2':
    conn = SSH2()

yes, conn is string type variable and string variable do not have connect method.

Thanks guys. Made perfect sense once it was pointed out to me.

Python EXscript - AttributeError: 'str' object has no attribute 'conne...

python
Rectangle 27 1

How about simply checking if your dictionary value does provide the method/attribute you need?

for keys in interfaces:
      counters = interfaces[keys].get(u'interfaceCounters', {})
      if hasattr(counters, 'get'): 
          # Only print if counters supports `get`
          print keys, "inOctets:", counters.get(u'inOctets', {}), "outOctets:", counters.get(u'outOctets',  {})

Thank you I love this fix, very helpful for what we are doing with gathering nested output from switches.

Cheers, but performance wise Martijn Pieters answer is better, but less explicit ;-)

python - AttributeError: 'str' object has no attribute 'get' - Stack O...

python
Rectangle 27 1

If some of your interfaceCounters keys reference a string instead of a nested dictionary, just use exception handling to ignore those:

for keys in interfaces:
    counters = interfaces[keys].get(u'interfaceCounters', {})
    try:
        print keys, "inOctets:", counters.get(u'inOctets', {}), "outOctets:", counters.get(u'outOctets',  {})
    except AttributeError:
        # counters is not a dictionary, ignore and move on
        pass

This is the ask forgiveness principle; if most of your entries do have the .get() method this is simply faster than the look before you leap principle, where you test if the method is available.

@Wilken: glad we were both of help! Note that you can only mark one of the answers as accepted; pick the one you feel helped you the best! (And yes, it is fine if that is SmCaterpillar's answer, it is your choice).

I've been going back and forth on which one to choose, Both are very good answers that help a lot!

python - AttributeError: 'str' object has no attribute 'get' - Stack O...

python
Rectangle 27 3

Looks like you have a typo:

driver = webdriver.PhantomJS=("c:|phantomjs-2.1.1/windows/bin/phantomjs")
                            ^

web scraping - Python AttributeError: 'str' object has no attribute 'g...

python web-scraping attributes
Rectangle 27 115

You have mutual top-level imports, which is almost always a bad idea.

If you really must have mutual imports in Python, the way to do it is to import them within a function:

# In b.py:
def cause_a_to_do_something():
    import a
    a.do_something()

Now a.py can safely do import b without causing problems.

(At first glance it might appear that cause_a_to_do_something() would be hugely inefficient because it does an import every time you call it, but in fact the import work only gets done the first time. The second and subsequent times you import a module, it's a quick operation.)

Thank you! I know for the first time that importing in different places make such a difference.

Please be aware that this adds over-head when the function is called, as you put the import logic at function call time, rather than program load time.

Interesting; I wonder why the interpreter does not give a proper error message in this case?

python - AttributeError: 'module' object has no attribute - Stack Over...

python attributeerror
Rectangle 27 114

You have mutual top-level imports, which is almost always a bad idea.

If you really must have mutual imports in Python, the way to do it is to import them within a function:

# In b.py:
def cause_a_to_do_something():
    import a
    a.do_something()

Now a.py can safely do import b without causing problems.

(At first glance it might appear that cause_a_to_do_something() would be hugely inefficient because it does an import every time you call it, but in fact the import work only gets done the first time. The second and subsequent times you import a module, it's a quick operation.)

Thank you! I know for the first time that importing in different places make such a difference.

Please be aware that this adds over-head when the function is called, as you put the import logic at function call time, rather than program load time.

Interesting; I wonder why the interpreter does not give a proper error message in this case?

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

python - AttributeError: 'module' object has no attribute - Stack Over...

python attributeerror
Rectangle 27 2

Your assumption that runAnalytics is running is correct since the function is executed when binding it to the button the way you did.

According to the effbot docs you need to use a lambda function in order to bind a function with passed arguments to a button like this:

import tkinter

def test_func(val):
    print(type(val))
    print(val)
    share_id = val.get()
    print(share_id)


loadApplication = tkinter.Tk()
loadApplication.title("Stock Analytics")
loadApplication.geometry("1080x720")

label1 = tkinter.Label(loadApplication, text = "Ticker")
input1 = tkinter.Entry(loadApplication)

loadAnalytics = tkinter.Button(loadApplication, text="Load Analytics", command=lambda: test_func(input1))


loadAnalytics.pack()
label1.pack()
input1.pack()

loadApplication.mainloop()

However, there is a second thing to keep in mind:

input1 = tkinter.Entry(loadApplication)

creates an Entry widget called input1 which is then passed to the function. The thing is that input1 does not contain the string you typed into the entry widget but a reference to the widget (widget ID). In order to get the widget's content you need to call its .get() method as shown in my code snippet.

Okay thank you! That fixed the issue of them both running! As I said earlier, I am new to this. Can you explain what the "def test_func(val): print(val)" is doing?

I commented it out and the program still ran.

You need to bind a callback function to a button which is executed whenever the button is clicked. Since I was in need of a simple sample callback and do not have the yahoo_fincance module installed on my system I decided to go this way. The porgramm code is not updated 'on-line' like live-reloading. So to make any changes working and see what's the difference you need to start and restart the whole script.

After reading your edit, I changed ticker = Share(input1) to ticker = Share(input1.get()) and my problem was resolved! I wish I could upvote your answer twice. Thank you so much, I was working on this all day and the simplest error got me tied up. @albert

string - Python AttributeError: 'str' object has no attribute 'get_pri...

python string tkinter python-3.5 attributeerror
Rectangle 27 60

I have also seen this error when inadvertently naming a module with the same name as one of the standard Python modules. E.g. I had a module called commands which is also a Python library module. This proved to be difficult to track down as it worked correctly on my local development environment but failed with the specified error when running on Google App Engine.

I used abc.py to write a test to demonstrate the import behavior in python, that bites me a lot...

I suspected this and deleted the .py module but forgot to delete the .pyc which was still causing the error.

I created a math module , which is already standard module.

python - AttributeError: 'module' object has no attribute - Stack Over...

python attributeerror
Rectangle 27 60

I have also seen this error when inadvertently naming a module with the same name as one of the standard Python modules. E.g. I had a module called commands which is also a Python library module. This proved to be difficult to track down as it worked correctly on my local development environment but failed with the specified error when running on Google App Engine.

I used abc.py to write a test to demonstrate the import behavior in python, that bites me a lot...

I suspected this and deleted the .py module but forgot to delete the .pyc which was still causing the error.

I created a math module , which is already standard module.

python - AttributeError: 'module' object has no attribute - Stack Over...

python attributeerror
Rectangle 27 106

This works in Python 2.x.

import urllib.request
with urllib.request.urlopen("http://www.python.org") as url:
    s = url.read()
#I'm guessing this would output the html source code?
print(s)

Hi Eumiro, using the 'with' statement in Python I'm guessing it closes the connection automatically once it's done using it? Similar to a use statement in C#?

@Sergio: exactly! And through the indentation you see where your file is still opened.

Hello @eumiro, I have an error of "IndentationError: expected an indented block" when I type s = url.read(), may I ask how can I solve it please? x

s=url.read()

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

python python-3.x urllib
Rectangle 27 31

The problem is the circular dependency between the modules. a imports b and b imports a. But one of them needs to be loaded first - in this case python ends up initializing module a before b and b.hi() doesn't exist yet when you try to access it in a.

Thank you! It is what I guessed. But I cannot find some documents mention it. If I do need two modules import some attributes from each other, what should I do?

@Stephen Hsu: Breaking circular dependencies is easy. It's already been asked on SO several times. stackoverflow.com/search?q=%5Bpython%5D+circular+dependency

@S.Lott: Thank you. I just know that it is a circular dependencies problem.

python - AttributeError: 'module' object has no attribute - Stack Over...

python attributeerror
Rectangle 27 30

The problem is the circular dependency between the modules. a imports b and b imports a. But one of them needs to be loaded first - in this case python ends up initializing module a before b and b.hi() doesn't exist yet when you try to access it in a.

Thank you! It is what I guessed. But I cannot find some documents mention it. If I do need two modules import some attributes from each other, what should I do?

@Stephen Hsu: Breaking circular dependencies is easy. It's already been asked on SO several times. stackoverflow.com/search?q=%5Bpython%5D+circular+dependency

@S.Lott: Thank you. I just know that it is a circular dependencies problem.

python - AttributeError: 'module' object has no attribute - Stack Over...

python attributeerror
Rectangle 27 13

I got this error by referencing an enum which was imported in a wrong way, e.g.:

from package import MyEnumClass
# ...
# in some method:
return MyEnumClass.Member
from package.MyEnumClass import MyEnumClass

Hope that helps someone

python - AttributeError: 'module' object has no attribute - Stack Over...

python attributeerror
Rectangle 27 13

I got this error by referencing an enum which was imported in a wrong way, e.g.:

from package import MyEnumClass
# ...
# in some method:
return MyEnumClass.Member
from package.MyEnumClass import MyEnumClass

Hope that helps someone

python - AttributeError: 'module' object has no attribute - Stack Over...

python attributeerror
Rectangle 27 3

>>> import tkinter as tk
>>> tk.canvas
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'canvas'
>>> tk.Canvas
<class 'tkinter.Canvas'>

python - Why do I keep getting AttributeError: 'module' object has no ...

python attributeerror
Rectangle 27 5

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).

@Bruce ah sorry, I was close though. I just noticed that urllib3 does an from http.client import HTTPConnection, HTTPException. It seems your http.py file is shadowing that instead? Try renaming it.

Yes! That was it! Thanks for the advice.

'module' object has no attribute 'post'
email.py

python - AttributeError: 'module' object has no attribute - Stack Over...

python python-requests attributeerror
Rectangle 27 124

I'm adding this solution for people who make the same mistake as I did.

In most cases: rename your project file 'serial.py' and delete serial.pyc if exists, then you can do simple 'import serial' without attribute error.

Wow, didn't see that coming. Spent 45 minutes pulling hair out.

Additional point for GAE users - try flushing memcache. Somehow ran into this and got stumped for ages after moving a model to a different file. Not sure what was cached that caused it, but it flush fixed it.

AttributeError: 'module' object has no attribute 'SerialException

Python AttributeError: 'module' object has no attribute 'Serial' - Sta...

python serial-port raspberry-pi
Rectangle 27 119

I'm adding this solution for people who make the same mistake as I did.

In most cases: rename your project file 'serial.py' and delete serial.pyc if exists, then you can do simple 'import serial' without attribute error.

Wow, didn't see that coming. Spent 45 minutes pulling hair out.

Additional point for GAE users - try flushing memcache. Somehow ran into this and got stumped for ages after moving a model to a different file. Not sure what was cached that caused it, but it flush fixed it.

AttributeError: 'module' object has no attribute 'SerialException

Python AttributeError: 'module' object has no attribute 'Serial' - Sta...

python serial-port raspberry-pi
Rectangle 27 329

You can use hasattr() or catch AttributeError, but if you really just want the value of the attribute with a default if it isn't there, the best option is just to use getattr():

getattr(a, 'property', 'default value')

This solves both aforementioned problems: a) The ambiguity of the source of a possible AttributeError, b) Preserving the EAFP approach.

It's also 25% of the lines of code. Surely this has to be the best solution.

This is the best solution "if you really just want the value of the attribute with a default." Although I believe this is what many people actually want when they say they want to detect whether an attribute is present, the OP actually asked for the latter, so it's reasonable for the direct answers to that question (hasattr, AttributeError) to be listed higher.

How to know if an object has an attribute in Python - Stack Overflow

python attributes
Rectangle 27 329

You can use hasattr() or catch AttributeError, but if you really just want the value of the attribute with a default if it isn't there, the best option is just to use getattr():

getattr(a, 'property', 'default value')

This solves both aforementioned problems: a) The ambiguity of the source of a possible AttributeError, b) Preserving the EAFP approach.

It's also 25% of the lines of code. Surely this has to be the best solution.

This is the best solution "if you really just want the value of the attribute with a default." Although I believe this is what many people actually want when they say they want to detect whether an attribute is present, the OP actually asked for the latter, so it's reasonable for the direct answers to that question (hasattr, AttributeError) to be listed higher.

How to know if an object has an attribute in Python - Stack Overflow

python attributes