This seems to be a common error in Python, and I've found many instances of people asking about similar but spent the last (long amount of time) trying those solutions where they seemed applicable and have had no luck, so resorting to asking to find out what I'm missing.
I'm receiving AttributeError: WebHandler instance has no attribute 'search_str'
It seems to be this one particular method, any time I call any of the class variables set in ___init___ from this method I receive this error. I've extracted it to a test file as a simple function rather than a class method and it works fine, and I've tried re-indenting everything a few times to make sure it wasn't that, so I'm at a loss on this.
I'm using Python 2.7 and TextWrangler if either of these are helpful (TextWrangler hasn't given me any problems in 3 years like this, but figured anything should be included)
import requests
import re
class WebHandler():
def ___init___(self):
self.urllist = []
self.search_str = re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_#.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', re.I|re.M)
def set_urls(self, test, data):
for line in test[11:]:
if (("even" in line) or ("odd" in line)):
match = re.search(self.search_str, line)
self.urllist.append(match.group(0))
Another thing I tried, if I copy the attributes from ___init___ and simply make them local to set_urls() and call them without self that way it works properly and doesn't throw any errors, which is confusing me even more.
No idea what I'm missing. Thanks!
Your init function has three underscores:
def ___init___(self):
It should have only two:
def __init__(self):
As it is written now, it is not being called when you create a new object.
This that you have:
def ___init___(self):
Is not the same as this that gets called when an object is instantiated:
def __init__(self):
The difference is that you have three underscores on either side of init, while two are required.
Related
I am trying to simulate the rolling of a die and have used this code
class dicesimulator:
def __init__(self, list = [0,0,0,0,0,0]):
self.list = list
#staticmethod
def diceroller():
outcome = random.randit(0,5)
print outcome + 1
mydice = dicesimulator()
print mydice.diceroller
However when I run the code it returns rather then a number. Why is this happening. Also as far as I am aware I should also be able to call the class itself on a static method ie dicesimulator.diceroller. However, it also returns
So there's a couple of issues. Firstly, there's not really a terribly good reason to use static methods. It's essentially no different than just making a function. Secondly, you aren't actually returning the number from within your diceroller() method. Thirdly, you aren't actually calling diceroller because you forgot to put parens so instead you're just printing the function directly (the string representation of it).
You forgot the parens.
mydice.diceroller()
I'm glad you found the indentation repair.
(1) You asked for the diceroller object, rather than calling the method.
(2) There is no "randit". Try "randint".
import random
class dicesimulator:
def __init__(self, list = [0,0,0,0,0,0]):
self.list = list
This yields output
6
None
Note that you have not returned anything from the function diceroller. You also haven't used dicesimulator.list for anything yet.
Consider searching the internet for implementations.
There's no need to complicate things by unnecessarily using classes and static methods.
from random import randint
print(randint(1,6))
RESOLVED: Okay, you guys probably won't believe this. I did a lot of digging and it turns out that all the files we are loading and using were created incorrectly. The files fail to conform with the code we are writing — the things we want to do in our program are simply not possible based on the current state of the files we load. I am currently working on fixing this. Sorry about the non-question, guys!
In Python I have code that essentially reads as follows:
partsList = getPartsList() # this function returns a list
for part in partsList:
...
bar(partsList)
def bar(partsList):
for part in partsList:
...
But when I run the code I get the following TypeError:
TypeError: iteration over non-sequence
This TypeError is in reference to the noted line:
def bar(partsList):
for part in partsList: # this is the line with the TypeError
...
How can this be? I know that partsList is not a non-sequence because just before my program calls bar(partsList), I explicitly iterate over partsList.
My function does not modify partsList before interacting with it, and I do not modify partsList when iterating through it prior to calling the function, yet somehow it changes from a list to a non-sequence when the function is called.
I am working entirely within a class so these are all methods actually; I just thought it would be easier to read if I present the code this way.
The following is in response to the comments:
I wish I could provide you all with the full code, but at the moment the program requires exactly 275 files to run and has 20+ .py files. I will mention that the method in question does employ recursion after iteration through its given list. I thought this may be linked to the error, but when when attempting to print the list itself and its contents, the program gave the same TypeError before making it through the method even once, so I know that this is not due to the recursion; it never even recursed.
Ok I have inserted print statements as follows (keep in mind these are within methods in a class):
def someMethod(self):
...
partsList = self.getPartsList() # this function returns a list
for part in partsList:
...
print partsList # prints [object(1), object(2)]
self.bar(partsList)
def bar(self, partsList):
print partsList # prints <filename.class instance at 0x04886148>
for part in partsList: # still gives me the TypeError
...
When I say filename.class I don't literally mean filename and class. You guys know what I mean.
Is the second print statement printing <filename.class instance at 0x04886148> because it is pointing to the actual partsList? I'm not entirely sure how pointers and references work in Python.
You don't define bar correctly; its first argument is a reference to the object that calls it, and the second argument is the list you pass as the explicit argument.
def bar(self, partsList):
for part in partsList:
...
Your answer is there in the print lines.
def bar(self, partsList):
print partsList # prints <filename.class instance at 0x04886148>
for part in partsList: # still gives me the TypeError
...
partsList isn't a list going into this method. Here is some tweaked, functioning, example code from your code:
class myClass():
def someMethod(self):
partsList=self.getPartsList()
for part in partsList:
print part
self.bar(partsList)
def bar(self, pList):
print pList
for part in pList:
print part
def getPartsList(self):
return ['a', 'b', 'c']
Running this interactively gets me this:
from fake_try import myClass
x = myClass()
x.someMethod()
a
b
c
['a', 'b', 'c']
a
b
c
You'll notice that when I called "print pList" I received a pretty print output of the list. You are receiving an object of your class type.
I understand and empathize with your situation. Having a large, complex program throwing errors can be quite painful to debug. Unfortunately without seeing your entire code I don't think anyone here will be able to debug your issue because my guess is that you are calling 'someMethod' in a way that is unexpected in the actual code(or in an unexpected place) which is causing you to have issues.
There are a couple of ways you can debug this.
I am assuming that everything ran UNTIL you added the someMethod functionality? Revert your code to a state prior to the error and add lines on at a time(with dummy functions if neccesary) to find exactly where the unexpected value is coming from. If you cannot revert my first step would be to simplify all logic surrounding this issue. You have a function 'getPartsList()' that's supposed to return a list. It looks like it is here, but make it even easier to check. Make a dummy function that simply returns a fake list and see what the behavior is. Change things one step at a time until you iron out where the issue is.
You may not be familiar with the inspect module. Try importing inspect in your module and using inspect.getmember(x) with x being the object you want more information about. I would probably use this in place of you print partsList in the bar method( something like inspect.getmember(partsList) ) I would guess that you're somehow passing a class there instead of the list, this should tell you what that class has been instantiated as.
Sorry novice beginner programmers question about having only one instance of a class run at one time; and now struggling to find right way to structure the code.
I've researched but struggling to find the right approach, but lots of argument as to the right pythonic approach be that modules or Singltons e.g. Ensure that only one instance of a class gets run
I have some code (python 2.7.2) that continually logs 3 variables (2 temperatures and a pressure sensor) and then based on some logic looking at trends in the variables, moves a valve (if statements that if true, call defs in the module with lots of globals scattered around as I actually want all my defs to look at the same datasets and move the same valve). At the minute this all works fine in a module file.
However, so others in the lab can run my code, it needs to be launched from a general GUI and therefore my code needs to be threaded so that the process doesn’t tie up the GUI and command line.
I'd started to re-write the code into a Class (with threading superclass), and wanted to add some logic to that only one instance of the Class was called, so that >1 thread isn’t trying to control the same valve.
Now, I've discovered that this isn’t so easy in python and read that the notion of 'Singletons' are bad, and am struggling to find a solution on how to structure my code.
I would be grateful if someone could point me in the right direction, as I guess this must have been answered.
you should initalize one instance and access only your initialized constant
and for safety, raise exception in case someone tries to create another instance
class Singletone(object):
__initialized = False
def __init__(self):
if Singletone.__initialized:
raise Exception("You can't create more than 1 instance of Singletone")
Singletone.__initialized = True
MY_SINGLETONE_INSTANCE = Singletone()
From http://norvig.com/python-iaq.html:
def singleton(object, instantiated=[]):
"Raise an exception if an object of this class has been instantiated before."
assert object.__class__ not in instantiated, \
"%s is a Singleton class but is already instantiated" % object.__class__
instantiated.append(object.__class__)
class YourClass:
"A singleton class to do something ..."
def __init__(self, args):
singleton(self)
...
Not sure how you'd have to adapt that for multithreaded applications, though.
First, if you guys think the way I'm trying to do things is not Pythonic, feel free to offer alternative suggestions.
I have an object whose functionality needs to change based on outside events. What I've been doing originally is create a new object that inherits from original (let's call it OrigObject()) and overwrites the methods that change (let's call the new object NewObject()). Then I modified both constructors such that they can take in a complete object of the other type to fill in its own values based on the passed in object. Then when I'd need to change functionality, I'd just execute myObject = NewObject(myObject).
I'm starting to see several problems with that approach now. First of all, other places that reference the object need to be updated to reference the new type as well (the above statement, for example, would only update the local myObject variable). But that's not hard to update, only annoying part is remembering to update it in other places each time I change the object in order to prevent weird program behavior.
Second, I'm noticing scenarios where I need a single method from NewObject(), but the other methods from OrigObject(), and I need to be able to switch the functionality on the fly. It doesn't seem like the best solution anymore to be using inheritance, where I'd need to make M*N different classes (where M is the number of methods the class has that can change, and N is the number of variations for each method) that inherit from OrigObject().
I was thinking of using attribute remapping instead, but I seem to be running into issues with it. For example, say I have something like this:
def hybrid_type2(someobj, a):
#do something else
...
class OrigObject(object):
...
def hybrid_fun(self, a):
#do something
...
def switch(type):
if type == 1:
self.hybrid_fun = OrigObject.hybrid_fun
else:
self.fybrid_fun = hybrid_type2
Problem is, after doing this and trying to call the new hybrid_fun after switching it, I get an error saying that hybrid_type2() takes exactly 2 arguments, but I'm passing it one. The object doesn't seem to be passing itself as an argument to the new function anymore like it does with its own methods, anything I can do to remedy that?
I tried including hybrid_type2 inside the class as well and then using self.hybrid_fun = self.hybrid_type2 works, but using self.hybrid_fun = OrigObject.hybrid_fun causes a similar error (complaining that the first argument should be of type OrigObject). I know I can instead define OrigObject.hybrid_fun() logic inside OrigObject.hybrid_type1() so I can revert it back the same way I'm setting it (relative to the instance, rather than relative to the class to avoid having object not be the first argument). But I wanted to ask here if there is a cleaner approach I'm not seeing here? Thanks
EDIT:
Thanks guys, I've given points for several of the solutions that worked well. I essentially ended up using a Strategy pattern using types.MethodType(), I've accepted the answer that explained how to do the Strategy pattern in python (the Wikipedia article was more general, and the use of interfaces is not needed in Python).
Use the types module to create an instance method for a particular instance.
eg.
import types
def strategyA(possible_self):
pass
instance = OrigObject()
instance.strategy = types.MethodType(strategyA, instance)
instance.strategy()
Note that this only effects this specific instance, no other instances will be effected.
You want the Strategy Pattern.
Read about descriptors in Python. The next code should work:
else:
self.fybrid_fun = hybrid_type2.__get__(self, OrigObject)
What about defining it like so:
def hybrid_type2(someobj, a):
#do something else
...
def hybrid_type1(someobj, a):
#do something
...
class OrigObject(object):
def __init__(self):
...
self.run_the_fun = hybrid_type1
...
def hybrid_fun(self, a):
self.run_the_fun(self, a)
def type_switch(self, type):
if type == 1:
self.run_the_fun = hybrid_type1
else:
self.run_the_fun = hybrid_type2
You can change class at runtime:
class OrigObject(object):
...
def hybrid_fun(self, a):
#do something
...
def switch(self):
self.__class__ = DerivedObject
class DerivedObject(OrigObject):
def hybrid_fun(self, a):
#do the other thing
...
def switch(self):
self.__class__ = OrigObject
I am trying to compare two modules/classes/method and to find out if the class/method has have changed. We allow users to change classes/methods, and after processing, we make those changes persistent, without overwriting the older classes/methods. However, before we commit the new classes, we need to establish if the code has changed and also if the functionally of the methods has changed e.g output differ and performance also defer on the same input data. I am ok with performance change, but my problem is changes in code and how to log - what has changed. i wrote something like below
class TestIfClassHasChanged(unittest.TestCase):
def setUp(self):
self.old = old_class()
self.new = new_class()
def test_if_code_has_changed(self):
# simple case for one method
old_codeobject = self.old.area.func_code.co_code
new_codeobject = self.new.area.func_code.co_code
self.assertEqual(old_codeobject, new_codeobject)
where area() is a method in both classes.. However, if I have many methods, what i see here is looping over all methods. Possible to do this at class or module level?
Secondly if I find that the code objects are not equal, I would like to log the changes. I used inspect.getsource(self.old.area) and inspect.getsource(self.new.area) compared the two to get the difference, could there be a better way of doing this?
You should be using a version control program to help manage development. This is one of the specific d=features you get from vc program is the ability to track changes. You can do diffs between current source code and previous check-ins to test if there were any changes.
if i have many methods, what i see
here is looping over all methods.
Possible to do this at class or module
level?
i will not ask why you want to do such thing ? but yes you can here is an example
import inspect
import collections
# Here i will loop over all the function in a module
module = __import__('inspect') # this is fun !!!
# Get all function in the module.
list_functions = inspect.getmembers(module, inspect.isfunction)
# Get classes and methods correspond .
list_class = inspect.getmembers(module, inspect.isclass)
class_method = collections.defaultdict(list)
for class_name, class_obj in list_class:
for method in inspect.getmembers(class_obj, inspect.ismethod):
class_method[class_name].append(method)