Why can't iterable objects cant use the next() method directly?
I have tried the following code:
ite_obj = ["sudosuraz"]
#new_obj = iter(ite_obj)
while True:
try:
item = next(`ite_obj`)
print(item)
except StopIteration:
print("done!")
break
Output:
Traceback (most recent call last):
File "/home/suraz/python-learn/functions.py", line 5, in <module>
item = next(ite_obj)
TypeError: 'list' object is not an iterator
Related
As a starting developer in Python I've seen this error message many times appearing in my console but I don't fully understand what does it means.
Could anyone tell me, in a general way, what kind of action produces this error?
That error occurs when you try to call, with (), an object that is not callable.
A callable object can be a function or a class (that implements __call__ method). According to Python Docs:
object.__call__(self[, args...]): Called when the instance is “called” as a function
For example:
x = 1
print x()
x is not a callable object, but you are trying to call it as if it were it. This example produces the error:
TypeError: 'int' object is not callable
For better understaing of what is a callable object read this answer in another SO post.
The other answers detail the reason for the error. A possible cause (to check) may be your class has a variable and method with the same name, which you then call. Python accesses the variable as a callable - with ().
e.g. Class A defines self.a and self.a():
>>> class A:
... def __init__(self, val):
... self.a = val
... def a(self):
... return self.a
...
>>> my_a = A(12)
>>> val = my_a.a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>>
The action occurs when you attempt to call an object which is not a function, as with (). For instance, this will produce the error:
>>> a = 5
>>> a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
Class instances can also be called if they define a method __call__
One common mistake that causes this error is trying to look up a list or dictionary element, but using parentheses instead of square brackets, i.e. (0) instead of [0]
The exception is raised when you try to call not callable object. Callable objects are (functions, methods, objects with __call__)
>>> f = 1
>>> callable(f)
False
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
I came across this error message through a silly mistake. A classic example of Python giving you plenty of room to make a fool of yourself. Observe:
class DOH(object):
def __init__(self, property=None):
self.property=property
def property():
return property
x = DOH(1)
print(x.property())
Results
$ python3 t.py
Traceback (most recent call last):
File "t.py", line 9, in <module>
print(x.property())
TypeError: 'int' object is not callable
The problem here of course is that the function is overwritten with a property.
I want to convert the final list as tuple. However i am receiving an error.How can i get rid of this?
li= [(19343160,),(39343169,)]
def render_list_sql(li):
l = []
for index, tuple in enumerate(li):
idd = str(tuple[0])
l.append(idd)
return tuple(l)
print(render_list_sql(li))
Expected value to be returned is:
(19343160,39343169)
Error
Traceback (most recent call last):
File "test.py", line 20, in <module>
print(render_list_sql(list))
File "test.py", line 14, in render_list_sql
return tuple(l)
TypeError: 'tuple' object is not callable
As commented, don't use names for variables that mean other things to Python. This is called "shadowing" and you lose the meaning of the original name.
Example:
>>> tuple # This is the class used to create tuples.
<class 'tuple'>
>>> for index,tuple in enumerate([1,2,3]): # This is similar to your code
... print(index,tuple)
...
0 1
1 2
2 3
>>> tuple # tuple is no longer a class, but an instance of an integer.
3
>>> tuple([1,2,3]) # so this fails
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: 'int' object is not callable
>>> 3([1,2,3]) # You are basically doing this:
<interactive input>:1: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: 'int' object is not callable
So don't do that:
li = [(19343160,),(39343169,)] # don't reassign list
def render_list_sql(li):
l = []
for index, tup in enumerate(li): # don't reassign tuple
idd = str(tup[0])
l.append(idd)
return tuple(l) # now this will work
print(render_list_sql(li))
Output:
('19343160', '39343169')
FYI, a shorter version using a generator:
li = [(19343160,),(39343169,)]
tup = tuple(str(i[0]) for i in li)
print(tup)
Why is every time I set a variable as a list, it always comes back as TraceBack error when I try to append to the list:
>>> a = list
>>> a.append('item1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: descriptor 'append' requires a 'list' object but received a 'str'
>>> type(a)
<class 'type'>
list is not the attribute to define lists but it is a method to convert to lists. It is explained here.
What is the python attribute to define a variable as a list?
To initialize a var with a certain type, use () after the name of the class:
a = list()
You can also instatiate a list like this:
mylist = []
I am having issues with
AttributeError: 'filter' object has no attribute 'sort'
Below is the whole error message:
Using TensorFlow backend.
Traceback (most recent call last):
File "D:/Data/PROMISE2012/Vnet3d_data/promise12_Unet_segmentation-master/promise12_segmentation-master/codes/train.py", line 231, in <module>
n_imgs=15*10**4, batch_size=32)
File "D:/Data/PROMISE2012/Vnet3d_data/promise12_Unet_segmentation-master/promise12_segmentation-master/codes/train.py", line 166, in keras_fit_generator
data_to_array(img_rows, img_cols)
File "D:/Data/PROMISE2012/Vnet3d_data/promise12_Unet_segmentation-master/promise12_segmentation-master/codes/train.py", line 48, in data_to_array
fileList.sort()
AttributeError: 'filter' object has no attribute 'sort'
Process finished with exit code 1
def data_to_array(img_rows, img_cols):
clahe = cv2.createCLAHE(clipLimit=0.05, tileGridSize=(int(img_rows/8),int(img_cols/8)) )
fileList = os.listdir('TrainingData/')
fileList = filter(lambda x: '.mhd' in x, fileList)
fileList.sort()
In python 3 filter returns iterable. and you are calling sort method on iterable hence getting an error.
Either wrap iterable in list
fileList = list(filter(lambda x: '.mhd' in x, fileList))
or instead of fileList.sort() pass iterable in a sorted method
fileList= sorted(fileList)
Python 3 doc for filter
You are using Python 3. Filter returns an iterable filter object, but it has not sort method. Wrap the filter object in list.
fileList = list(filter(lambda x: '.mhd' in x, fileList))
I'm trying to get count of affected elements by my css query. But I couldn't able to get count.
browser = webdriver.Firefox()
browser.get("http://just-a-example.site")
td_weeks = browser.find_element_by_css_selector("td.status")
# there is 4 elements that have "status" class
print(len(td_weeks)) # it gives me error
Error:
Traceback (most recent call last):
File "main.py", line 59, in <module>
print(len(td_weeks))
TypeError: object of type 'FirefoxWebElement' has no len()
Thanks for any kind of help.
To find multiple elements (these methods will return a list):
find_elements_by_name
find_elements_by_xpath
find_elements_by_link_text
find_elements_by_partial_link_text
find_elements_by_tag_name
find_elements_by_class_name
find_elements_by_css_selector
so your code should be like this
browser = webdriver.Firefox()
browser.get("http://just-a-example.site")
td_weeks = browser.find_elements_by_css_selector("td.status")#this will return list of class
print(len(td_weeks))