Меню

Bool object is not iterable ошибка

I am having a strange problem. I have a method that returns a boolean. In turn I need the result of that function returned again since I cant directly call the method from the front-end. Here’s my code:

# this uses bottle py framework and should return a value to the html front-end
@get('/create/additive/<name>')
def createAdditive(name):
    return pump.createAdditive(name)



 def createAdditive(self, name):
        additiveInsertQuery = """ INSERT INTO additives
                                  SET         name = '""" + name + """'"""
        try:
            self.cursor.execute(additiveInsertQuery)
            self.db.commit()
            return True
        except:
            self.db.rollback()
            return False

This throws an exception: TypeError(«‘bool’ object is not iterable»,)

I don’t get this error at all since I am not attempting to «iterate» the bool value, only to return it.

If I return a string instead of boolean or int it works as expected. What could be an issue here?

Traceback:

Traceback (most recent call last):
  File "C:Python33libsite-packagesbottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

The python error TypeError: argument of type ‘bool’ is not iterable happens when the membership operators evaluates a value with a boolean variable. The python membership operator (in, not in) tests a value in an iterable objects such as set, tuple, dict, list etc. If the iterable object in the membership operator is passed as a boolean variable then the error is thrown.

The membership operator shall detect a boolean value as an iterable object. The boolean value is a single object. The member operator returns true if the value is found in an iterable object. 

The Member Operator (in, not in) is used to check whether or not the given value is present in an iterable object. If the value exists in the iterable object then it returns true. If the iterable object is a boolean variable then the value is hard to verify. The error TypeError: argument of type ‘bool’ is not iterable is due to checking the value in Boolean variable.

If the right iterable object is passed in the membership operator, such as tuple, set, dictionary, list etc., then the error will not occur.

Exception

When the error TypeError: argument of type ‘bool’ is not iterable happens, this error displays the stack trace as shown below.

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 3, in <module>
    print x in y
TypeError: argument of type 'bool' is not iterable
[Finished in 0.1s with exit code 1]

How to reproduce this error

To verify a value the membership operator needs an iterable object. If the iterable object is passed as a boolean variable then it is difficult to check the value. Therefore, the error TypeError: argument of type ‘bool’ is not iterable will be thrown.

In the example below, two variables are assigned to x and y with a boolean value. The x value is verified with the y value used by the membership operator (in, not in). Since the y value is a boolean type, it will throw an error.

x = True
y = True
print x in y

Output

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 3, in <module>
    print x in y
TypeError: argument of type 'bool' is not iterable
[Finished in 0.1s with exit code 1]

Solution 1

The membership operator (in, not in) requires an iterable object to search for a present or not present value. To check the value, the iterable object such as list, tuple, or dictionary should be used. If a valid iterable object is passed in the membership operator, then the error will be resolved.

x = True
y = [ True ]
print x in y

Output

True
[Finished in 0.1s]

Solution 2

If you wish to compare a boolean value with another boolean value, you should not use the Membership Operator. The logical operator is often used to equate two boolean values. In python the logical operator can compare two values. The code below shows how the value can be used for comparison.

x = True
y = True
print x == y

Output

True
[Finished in 0.1s]

Solution 3

If the iterable object in the Membership Operator is an invalid boolean value, then you can change it to execute in alternate flow. This will fix the error. The iterable object must be validated before proceed with the membership operator.

x = True
y = True
if isinstance(y, bool) : 
	print "Value is boolean"
else:
	print x == y

Output

Value is boolean
[Finished in 0.1s]

Solution 4

If the iterable object is unknown, the expected iterable object should be checked before the membership operator is invoked. If the object is an iterable object, the membership operator is called with the python value. Otherwise, take an alternate flow.

x = True
y = True
if type(y) in (list,tuple,dict, str): 
	print x in y
else:
	print "not a list"

Output

not a list
[Finished in 0.1s]

Solution 5

The try and except block is used to capture the unusual run time errors. If the python variable contains iterable object, then it will execute in the try block. If the python variable contains the uniterable value, then the except block will handle the error.

x = True
y = True
try : 
	print x in y
except :
	print "not a list"

Output

not a list
[Finished in 0.1s]

Понятие приведения типов в Python

Поскольку Python относится к языкам программирования с динамической типизацией данных, ответственность за предоставление данных нужного типа практически
полностью ложится на плечи программистов. Как следствие, им довольно часто приходится осуществлять преобразование объектов одного типа данных в другой. Например, когда пользователь вводит
с клавиатуры данные для вычислений, они поступают на обработку в строковом виде, а значит перед вычислениями возникает необходимость преобразования строкового типа данных в числовой. Если
этого не сделать, будет получена ошибка либо совсем неожиданный результат.

Да, в операциях с различными типами чисел или же в условных инструкциях и выражениях интерпретатор неявно (автоматически) преобразует объекты к общему типу. Однако в большинстве случаев это
не так, поэтому следует внимательно следить за текущим типом переменной и при необходимости самостоятельно осуществлять явное приведение к нужному типу.

Приведением типа называется процесс преобразования значения одного типа данных в значение другого типа.

Как уже упоминалось ранее, для преобразования различных типов данных между собой в Python доступен целый ряд встроенных функций (конструкторов типов):

  • bool() – приведение к логическому типу,
  • int() – приведение к целочисленному типу,
  • float() – приведение к вещественному типу,
  • complex() – приведение к комплексному числу,
  • str() – приведение к строковому типу,
  • tuple() – приведение к кортежу,
  • list() – приведение к списку,
  • dict() – приведение к словарю,
  • set() – приведение к множеству.

Использование для приведения типов всех перечисленных функций, подразумевает еще и знание правил, по которым происходят такие преобразования. Например, не каждую строку можно преобразовать в
число, хотя обратное преобразование возможно всегда. И таких нюансов можно перечислить довольно много. Поэтому будет не лишним рассмотреть порядок приведения типов более детально.

Ниже описаны общие правила приведения типов для конструкторов без дополнительных параметров. Если вдруг возникнет необходимость в более экзотических приемах преобразования, следует обращаться
к описаниям конструкторов в справочнике встроенных функций стандартной библиотеки.

Приведение к типу bool

Во время преобразования к типу bool (логический тип данных) следующие значения рассматриваются как
False:

  • само значение False,
  • значение None,
  • нулевые числовые значения 0, 0.0 и 0+0j,
  • пустая строка «»,
  • пустые объекты: [], tuple(), {}, dict().

Все остальные значения преобразуются в значение True, включая число -1, поскольку оно представляет собой обычное
отрицательное число, отличное от нуля (см. пример №1). Тоже самое касается коллекций с одним нулевым значением, например,
[0], {0.0}, (0,), а также непустых строк, например,
‘0’ или ‘0.0’.

# False.        
print('bool(None):', bool(None))       
# False.        
print('bool(0):', bool(0))         
# False.        
print('bool(0.0):', bool(0.0))        
# False.        
print('bool(0+0j):', bool(0+0j))        
# False.        
print('bool(""):', bool(''))        
# False.        
print('bool([]):', bool([]))        
# False.        
print('bool({}):', bool({}))        
# False.        
print('bool(tuple()):', bool(tuple()))        
# False.        
print('bool(dict()):', bool(dict()))        

print()

# True.        
print('bool("0"):', bool('0'))        
# True.        
print('bool(-1):', bool(-1)) 
# True.        
print('bool([False]):', bool([False])) 
# True.        
print('bool({0,}):', bool({0,}))        
# True.        
print('bool((0,)):', bool((0,)))
bool(None): False
bool(0): False
bool(0.0): False
bool(0+0j): False
bool(""): False
bool([]): False
bool({}): False
bool(tuple()): False
bool(dict()): False

bool("0"): True
bool(-1): True
bool([False]): True
bool({0,}): True
bool((0,)): True














		
			

Пример №1. Приведение к типу bool.

Приведение к типу int

В случае приведения к типу int (целые числа):

  • Логическое значение True преобразуется в 1,
    False – в 0.
  • Вещественные числа просто усекаются до целой части. Например, в случае приведения вещественного числа -37.9
    к целочисленному типу оно будет преобразовано в число -37.
  • Если строка содержит верную запись целого числа в десятичной системе счисления, то интерпретатор в процессе приведения строки к целочисленному типу вернет это число.
  • Если строка num_str содержит верное представлением целого числа в системе счисления с указанным основанием base,
    то преобразовать ее можно в целое число при помощи конструктора типа с двумя аргументами int(num_str, base=10)
    (подробнее здесь).

Для других типов данных приведение к целочисленному типу не определено, поэтому попытка такого преобразования приведет к ошибке (см. пример №2).

# 1.        
print('int(True): ', int(True))          
# 0.        
print('int(False): ', int(False))       
# 53.        
print('int("+53"): ', int('+53'))            
# -7.        
print('int(-7.33): ', int(-7.33))        
# 0.        
print('int(.33): ', int(.33))        

# int() argument must be a ...        
# print('int(5.2+1.3j): ', int(5.2+1.3j))        
        
# int() argument must be a ...        
# print('int(None): ', int(None))         
        
# invalid literal for ...        
# print('int(""): ', int(''))        

# invalid literal for ...        
# print('int("3.7"): ', int('3.7'))         

# int() argument must be a ...        
# print('int([5]): ', int([5]))
int(True): 1
int(False): 0
int("-53"): -53
int(-7.33): -7
int(.33): 0


















		
			

Пример №2. Приведение к типу int.

Приведение к типу float

В случае приведения к типу float (вещественные числа):

  • Логическое значение True преобразуется в 1.0,
    False – в 0.0.
  • Целые числа преобразуются в вещественные простым добавлением нулевой дробной части. Например, целое отрицательное число -37
    будет преобразовано в число -37.0.
  • Если строка содержит верное представление целого числа в десятичной системе счисления, то интерпретатор в процессе приведения строки к вещественному типу вернет это число, добавив к нему
    нулевую дробную часть. При этом допускаются начальные и конечные пробельные символы, а также знаки плюса и минуса. Например, строка, содержащая запись целого отрицательного числа
    с пробелами ‘ -105 ‘ будет преобразовано в число -105.0.
  • Если строка содержит верное представление вещественного числа в десятичной системе счисления, то интерпретатор в процессе приведения строки к вещественному типу вернет это число.
    При этом допускаются начальные и конечные пробельные символы, а также знаки плюса и минуса. Например, строка, содержащая запись вещественного отрицательного числа с пробелами
    ‘ -1.5 ‘ будет преобразовано в число -1.5.
  • Также строка может представлять значения ‘NaN’, ‘Infinity’ или ‘-Infinity’.

Для других типов данных приведение к вещественному типу не определено, поэтому попытка такого преобразования приведет к ошибке (см. пример №3).

# 1.0.        
print('float(True): ', float(True))          
# 0.0.        
print('float(False): ', float(False))       
# 53.0.        
print('float(" +53"): ', float(' +53'))            
# -7.33.        
print('float("-7.33"): ', float('-7.33'))        
# 0.013.        
print('float("1.3e-2 "): ', float('1.3e-2 '))        
# nan.        
print('float("NaN"): ', float('NaN'))        
# -inf.        
print('float(" -Infinity "): ', float(' -Infinity '))        

# float() argument must be a string...        
# print('float(5.2+1.3j): ', float(5.2+1.3j))        
        
# float() argument must be a string...        
# print('float(None): ', float(None))         
        
# could not convert string to float...        
# print('float(""): ', float(''))        

# float() argument must be a string...        
# print('float([5]): ', float([5]))
float(True): 1.0
float(False): 0.0
float(" +53"): 53.0
float("-7.33"): -7.33
float("1.3e-2 "): 0.013
float("NaN"): nan
float(" -Infinity "): -inf

















		
			

Пример №3. Приведение к типу float.

Приведение к типу complex

В случае приведения к типу complex (комплексные числа):

  • Логическое значение True преобразуется в (1+0j),
    False – в 0j.
  • Целые и вещественные числа преобразуются в комплексные простым добавлением нулевой мнимой части +0j. Например, отрицательное вещественное число
    -3.7 будет преобразовано в комплексное число (-3.7+0j).
  • Если строка содержит верное представление комплексного числа, то интерпретатор в процессе приведения строки к комплексному типу вернет это число. При этом допускаются начальные и
    конечные пробельные символы, а также знаки плюса и минуса как перед действительной, так и мнимой частью. Однако пробелов между действительной и мнимой частями быть не должно! Например,
    строка, содержащая запись комплексного числа с пробелами ‘ -5.5+0.2j ‘ будет преобразовано в число (-5.5+0.2j).

Для других типов данных приведение к комплексному типу не определено, поэтому попытка такого преобразования приведет к ошибке (см. пример №4).

# (1+0j).        
print('complex(True):', complex(True))          
# 0j.        
print('complex(False):', complex(False))       
# (5.9-3.2j).        
print('complex(" +5.9-3.2j"):', complex(' +5.9-3.2j'))        
# (53+0j).        
print('complex(" 53"):', complex(' 53'))            
# (-7.33+0j).        
print('complex(" -7.33 "):', complex(' -7.33 '))        
# (0.013+0j).        
print('complex("1.3e-2 "):', complex('1.3e-2 '))        
# (nan+0j).        
print('complex("NaN"):', complex('NaN'))        
# (-inf+0j).        
print('complex(" -Infinity "):', complex(' -Infinity '))        
        
# complex() arg is a malformed string.       
# print('complex("5.2 + 1.3j"):', complex('5.2 + 1.3j'))        
        
# complex() first argument must be...        
# print('complex(None):', complex(None))         
        
# complex() arg is a malformed string.        
# print('complex(""):', complex(''))        

# complex() first argument must be...        
# print('complex([5]):', complex([5]))
complex(True): (1+0j)
complex(False): 0j
complex(" +5.9-3.2j"): (5.9-3.2j)
complex(" 53"): (53+0j)
complex(" -7.33 "): (-7.33+0j)
complex("1.3e-2 "): (0.013+0j)
complex("NaN"): (nan+0j)
complex(" -Infinity "): (-inf+0j)


















		
			

Пример №4. Приведение к типу complex.

Приведение к типу str

В случае приведения к типу str (строки) интерпретатор просто вернет строковое представление объекта, которое представлено методом приводимого объекта
object.__str__() (см. пример №5).

# True.        
print('str(True):', str(True))          
# False.        
print('str(False):', str(False))       
# (5.9-3.2j).        
print('str+5.9-3.2j:', str(+5.9-3.2j))        
# 53.        
print('str(53):', str(+53))            
# -7.33.        
print('str(-7.33):', str(-7.33))        
# 0.013.        
print('str(1.3e-2):', str(1.3e-2))        
# None.        
print('str(None):', str(None))        
# [0.5, 1,5].        
print('str([0.5, 1,5]):', str([0.5, 1,5]))                
# {'one', 'two'}.        
print("str({'one', 'two'}):", str({'one', 'two'}))                 
# (2, '3').        
print("str((2, '3')):", str((2, '3')))        
# {1: [2, True]}.        
print('str({1: [2, True]}):', str({1: [2, True]}))
str(True): True
str(False): False
str+5.9-3.2j: (5.9-3.2j)
str(53): 53
str(-7.33): -7.33
str(1.3e-2): 0.013
str(None): None
str([0.5, 1,5]): [0.5, 1, 5]
str({'one', 'two'}): {'one', 'two'}
str((2, '3')): (2, '3')
str({1: [2, True]}): {1: [2, True]}









		
			

Пример №5. Приведение к типу str.

Приведение к типу tuple

К типу tuple (кортежи) могут быть преобразованы только итерируемые объекты. При этом словари преобразуются в кортежи с ключами, теряя свои значения
(см. пример №6).

# ('a', 'b', 'c').        
print("tuple('abc'):", tuple('abc'))         
# (1, 2, 3).        
print('tuple([1, 2, 3]):', tuple([1, 2, 3]))                
# ('one', 'two').        
print("tuple({'one', 'two'}):", tuple({'one', 'two'}))                 
# (1, 2).        
print("tuple({1: 'one', 2: 'two'}):", tuple({1: 'one', 2: 'two'}))                
# ('one', 'two').        
print("tuple({'one': 1, 'two': 2}):", tuple({'one': 1, 'two': 2}))         
# (1, 2, 3).        
print("tuple(range(1, 4)):", tuple(range(1, 4)))        

# bool object is not iterable.        
# print('tuple(True): ', tuple(True))
          
# int object is not iterable.        
# print('tuple(53): ', tuple(53))
            
# NoneType object is not iterable.        
# print('tuple(None): ', tuple(None))
tuple('abc'): ('a', 'b', 'c')
tuple([1, 2, 3]): (1, 2, 3)
tuple({'one', 'two'}): ('one', 'two')
tuple({1: 'one', 2: 'two'}): (1, 2)
tuple({'one': 1, 'two': 2}): ('one', 'two')
tuple(range(1, 4)): (1, 2, 3)













		
			

Пример №6. Приведение к типу tuple.

Приведение к типу list

К типу list (списки) могут быть преобразованы только итерируемые объекты. При этом словари преобразуются в списки с ключами, теряя свои значения
(см. пример №7).

# ['a', 'b', 'c'].        
print("list('abc'):", list('abc'))         
# [1, 2, 3].        
print('list((1, 2, 3)):', list((1, 2, 3)))                
# ['one', 'two'].        
print("list({'one', 'two'}):", list({'one', 'two'}))                 
# [1, 2].        
print("list({1: 'one', 2: 'two'}):", list({1: 'one', 2: 'two'}))                
# ['one', 'two'].        
print("list({'one': 1, 'two': 2}):", list({'one': 1, 'two': 2}))         
# [1, 2, 3].        
print("list(range(1, 4)):", list(range(1, 4)))        

# bool object is not iterable.        
# print('list(True): ', list(True))          

# int object is not iterable.        
# print('list(53): ', list(53))            

# NoneType object is not iterable.        
# print('list(None): ', list(None))
list('abc'): ['a', 'b', 'c']
list((1, 2, 3)): [1, 2, 3]
list({'one', 'two'}): ['one', 'two']
list({1: 'one', 2: 'two'}): [1, 2]
list({'one': 1, 'two': 2}): ['one', 'two']
list(range(1, 4)): [1, 2, 3]













		
			

Пример №7. Приведение к типу list.

Приведение к типу set

К типу set (множества) могут быть преобразованы только итерируемые объекты. При этом словари преобразуются в множества с ключами, теряя свои значения
(см. пример №8).

# {'a', 'b', 'c'}.        
print("set('abc'):", set('abc'))         
# {1, 2, 3}.        
print('set((1, 2, 3)):', set((1, 2, 3)))                
# {1, 2}.        
print("set({1: 'one', 2: 'two'}):", set({1: 'one', 2: 'two'}))                
# {'one', 'two'}.        
print("set({'one': 1, 'two': 2}):", set({'one': 1, 'two': 2}))         
# {1, 2, 3}.        
print("set(range(1, 4)):", set(range(1, 4)))        

# bool object is not iterable.        
# print('set(True): ', set(True))          

# int object is not iterable.        
# print('set(53): ', set(53))            

# NoneType object is not iterable.        
# print('set(None): ', set(None))
set('abc'): {'b', 'a', 'c'}
set((1, 2, 3)): {1, 2, 3}
set({1: 'one', 2: 'two'}): {1, 2}
set({'one': 1, 'two': 2}): {'one', 'two'}
set(range(1, 4)): {1, 2, 3}












		
			

Пример №8. Приведение к типу set.

Приведение к типу dict

К типу dict (словари) напрямую могут быть преобразованы только итерируемые объекты, содержащие пары значений, в которых первые элементы становятся ключами
словаря, а вторые – его значениями. Например, это могут быть списки, кортежи или множества, содержащие в качестве своих элементов другие списки, кортежи или множества из двух элементов
(см. пример №9). При этом следует помнить, что только хешируемые (неизменяемые) объекты могут быть ключами словаря или элементами множества.

# {1: 'a', 2: 'b'}.        
print("dict([[1, 'a'], (2, 'b')]):", dict([[1, 'a'], (2, 'b')]))         
# {1: 'a', 2: 'b'}.        
print("dict([(1, 'a'), {2, 'b'}]):", dict([(1, 'a'), {2, 'b'}]))         

# {1: 'a', 2: 'b'}.        
print("dict(((1, 'a'), {2, 'b'})):", dict(((1, 'a'), {2, 'b'})))              
# {1: 'a', 2: 'b'}.        
print("dict(({1, 'a'}, [2, 'b'])):", dict(({1, 'a'}, [2, 'b'])))              

# {1: 'a', 2: 'b'}.        
print("dict({(1, 'a'), (2, 'b')}):", dict({(1, 'a'), (2, 'b')}))        


# unhashable type: list (списки не могут быть ключами).        
# print("dict([[[1], 'a'], (2, 'b')]):", dict([[[1], 'a'], (2, 'b')]))        

# unhashable type: list (список - недопустимый эл-т мн-ва).        
# print("dict({[1, 'a'], (2, 'b')}):", dict({[1, 'a'], (2, 'b')}))                

# dictionary update sequence element #0 has length 3; 2 is required.        
# print("dict([(1, 'a'), {2, 'b'}]):", dict([(1, 'a', 3), {2, 'b'}]))        

# bool object is not iterable.        
# print('dict(True): ', dict(True))
dict([[1, 'a'], (2, 'b')]): {1: 'a', 2: 'b'}
dict([(1, 'a'), {2, 'b'}]): {1: 'a', 2: 'b'}
dict(((1, 'a'), {2, 'b'})): {1: 'a', 2: 'b'}
dict(({1, 'a'}, [2, 'b'])): {1: 'a', 2: 'b'}
dict({(1, 'a'), (2, 'b')}): {2: 'b', 1: 'a'}


















		
			

Пример №9. Приведение к типу dict.

Краткие итоги параграфа

  • Для преобразования различных типов данных между собой в Python доступен целый ряд встроенных функций (конструкторов типов):
    bool() – приведение к логическому типу, int() – приведение к целочисленному типу,
    float() – приведение к вещественному типу, complex() – приведение к комплексному числу,
    str() – приведение к строковому типу, tuple() – приведение к кортежу,
    list() – приведение к списку, dict() – приведение к словарю,
    set() – приведение к множеству.
  • В операциях, например, с различными типами чисел или же в условных инструкциях и выражениях интерпретатор неявно (автоматически) преобразует объекты к общему типу. Однако в большинстве
    случаев это не так, поэтому следует внимательно следить за текущим типом переменной и при необходимости самостоятельно осуществлять явное приведение к нужному типу.

Помогите проекту, подпишитесь!

Подписка на учебные материалы сайта оформляется сроком на один год и стоит около 15 у.е. После
подписки вам станут доступны следующие возможности.

  • Доступ ко всем ответам на вопросы и решениям задач.
  • Возможность загрузки учебных кодов и программ на свой компьютер.
  • Доступ ко всем тренажерам и видеоурокам (когда появятся).
  • Возможность внести свой скромный вклад в развитие проекта и мира во всем мире,
    а также выразить свою благодарить автору за его труд. Нам очень нужна ваша поддержка!

Python для начинающих
На страницу подписки

Вопросы и задания для самоконтроля

1. Каким будет результат сложения двух переменных a = 5 и b = ‘7’? А если их
перемножить?

Показать решение.

Ответ. В первом случае мы получим ошибку, т.к. оператор сложения подразумевает наличие операндов одного типа, но интерпретатор в общем случае
не занимается автоматическим приведением типов, оставляя эту обязанность программистам. А вот умножение строки на число предусмотрено заранее, поэтому на выходе мы получим строку
‘77777’.

2. Приведите пример ситуации, в которой интерпретатор осуществляет неявное приведение к нужному типу.

Показать решение.

Ответ. Примерами могут служить: преобразование к вещественному типу при сложении целого и вещественного числа
(5 + 0.3) или же преобразование объектов к логическому типу в условных инструкциях и выражениях (1 if ‘ok’ else 0).

3. Какой важной особенностью должны обладать объекты, которые явно преобразуются в кортежи, списки или множества?

Показать решение.

Ответ. В кортежи, списки или множества при явном приведении типа могут быть преобразованы только итерируемые объекты. Преобразовать, например,
число в список не получится.

4. В каких случаях интерпретатор возбудит ошибки?

Показать решение.

print(bool([False]))     

print(int('7.5'))         

print(float(None))          
                       
print(float('0.55'))          
        
print(str(None))          
        
print(list(range(1, 5)))            
        
print(dict([[[5], 'пять']]))             
        
print(dict([[5, 'пять']]))

# True.        
print('bool([False]):', bool([False]))     

# invalid literal for ...        
# print('int("7.5"): ', int('7.5'))         

# float() argument must be a string...        
# print('float(None): ', float(None))          
                       
# 0.55.        
print('float("0.55"): ', float('0.55'))          
        
# None.        
print('str(None):', str(None))          
        
# [1, 2, 3, 4].        
print("list(range(1, 5)):", list(range(1, 5)))            
        
# unhashable type: list (списки не могут быть ключами).        
# print("dict([[[5], 'пять']]):", dict([[[5], 'пять']]))             
        
# {5: 'пять'}.        
print("dict([[5, 'пять']]):", dict([[5, 'пять']]))
bool([False]): True
float("0.55"):  0.55
str(None): None
list(range(1, 5)): [1, 2, 3, 4]
dict([[5, 'пять']]): {5: 'пять'}

















			

Быстрый переход к другим страницам

over 8 years

Here is my code:

def purify(numbers):
    new = []
    for item in numbers:
        if item%2 == 0:
            return True
        else:
            return False
    if is_even(item) == False:
        new = numbers.remove(item)
    return new

I’m getting the error:

“Oops, try again. Your function crashed on [1] as input because your function throws a “‘bool’ object is not iterable” error.”

Could someone please explain to me why this is happening and how to fix it? Thansk

Answer 536cec66282ae362f100001f

I don’t think you should make it complex by adding booleans here. Your condition is quite correct but you should not return true there but instead try appending it to your new list. Another thing your item is not getting a value of boolean i.e True or False. Returning means it will be printed only when the whole function is called i.e purify() i.e True or False is getting saved to your function but not your parameter.One more thing — there is no function named is_even() there so you can’t use it. Hope that helped !! Remember – Don’t go for removing stuff and booleans , Just append the stuff that are required in your list. Tell me if you feel any difficulties.

points

over 8 years

Answer 5371055752f8631a5600097b

Great thanks,

Here’s what I ended up with:

def purify(numbers):
    new = []
        for item in numbers:
            if item % 2 == 0:
                new.append(item)
    return new

points

over 8 years

1 comments

Nice , this is the one I was talking about

Уведомления

  • Начало
  • » Python для новичков
  • » SQLAlchemy внесение данных при помощи цикла ?

#1 Март 27, 2015 14:07:33

SQLAlchemy внесение данных при помощи цикла ?

Доброго времени суток.
Возник вопрос, о том как добавить в БД, при помощи алхимии данные из списка(словаря).
Моя попытка сделать это при помощи цикла for приводит к ошибке TypeError: ‘bool’ object is not iterable
Собственно код:

...
class University(Base):
    __tablename__ = 'univer'
    id = Column(Integer, primary_key=True, autoincrement=False)
    title = Column(Unicode)
    def __init__(self, id, title):
    	self.id = id
    	self.title = title
# имеются 2 списка universities_id и universities_title
# вариант №1
univers=dict(zip(universities_id, universities_title)) # делаю словарь из списков
for id,title in (univers.items()):
   session.add(University(id, title))
   session.commit()

после чего получаю: TypeError: ‘bool’ object is not iterable, а если вместо session.add написать print(id+’ : ‘+title), то нормально распечатает содержимое на экран.
ЧЯДНТ?
Заранне благодарю, товарищи.

Офлайн

  • Пожаловаться

#2 Март 27, 2015 14:12:14

SQLAlchemy внесение данных при помощи цикла ?

Зачем так над базой издеваться. Для этого есть метод add_all. Он получает последовательность объектов (список или набор) и их обрабатывает. Т.е. просто создаете список из объектов и передаете этому методу.

P.S. Мог бы написать в скайп…

Офлайн

  • Пожаловаться

#3 Март 27, 2015 14:58:41

SQLAlchemy внесение данных при помощи цикла ?

4kpt_III
Зачем так над базой издеваться. Для этого есть метод add_all. Он получает последовательность объектов (список или набор) и их обрабатывает. Т.е. просто создаете список из объектов и передаете этому методу.P.S. Мог бы написать в скайп…

Все оказалось плачевнее, чем было на самом деле: в классе, была строчка с relationship, в которой я опять допустил одну и ту же ошибку — backref = True, вместо названия таблицы. Оттого и получал такую ошибку.
ПС: Сейчас с машины пишу, на которой его нет

Отредактировано Astronaut (Март 27, 2015 14:58:51)

Офлайн

  • Пожаловаться

  • Начало
  • » Python для новичков
  • » SQLAlchemy внесение данных при помощи цикла ?

Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

So I looked it up and found a post about how a bool needs to be converted to a string to be iterated. After that I noticed that I was using .values(), instead of .items(). I fixed that and now my bool iterates fine. Any clarification would be great. Here is a snipet of my code that works as intended.

def employed(job):
    employed = input("emplyed in {}? Y/n ".format(job)).lower()
    if employed == "y":
        employed = "employed as {} is {}".format(job, True)
    else:
        employed = "employed as {} is {}".format(job, False)
    return employed

1 Answer

Jason Anello October 11, 2016 9:55pm

I think there must have been some other code that produced your error.

I get a different error when I try the following:

>>> me = {"Name": "Joe", "Job": "janitor", "Employed": True}
>>> for key, value in me.values():
...     print(key, value)
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)

Anyways, in the working version you’re iterating over a dictionary. One of the values happens to be a boolean but that’s not considered iterating over a boolean.

Here’s an example of trying to iterate over a bool and also an int and you get similar error messages as what you posted.

>>> for index in True:
...     print(index)
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bool' object is not iterable
>>> for index in 10:
...     print(index)
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

I’m not saying that’s what you did but you must have been using a boolean value somewhere that an iterable was expected in order to get 'bool' object is not iterable error

@ybnd

Hi,

I can’t get gitinspector to run from the npmpackage; after a clean install it crashes with

$ gitinspector -h
Traceback (most recent call last):
  File "/home/ybnd/.npm/node_modules/bin/gitinspector", line 21, in <module>
    from gitinspector import gitinspector
  File "/home/ybnd/.npm/node_modules/lib/node_modules/gitinspector/gitinspector/gitinspector.py", line 26, in <module>
    from .blame import Blame
  File "/home/ybnd/.npm/node_modules/lib/node_modules/gitinspector/gitinspector/blame.py", line 28, in <module>
    from .changes import FileDiff
  File "/home/ybnd/.npm/node_modules/lib/node_modules/gitinspector/gitinspector/changes.py", line 29, in <module>
    from . import extensions, filtering, format, interval, terminal
  File "/home/ybnd/.npm/node_modules/lib/node_modules/gitinspector/gitinspector/format.py", line 28, in <module>
    from . import basedir, localization, terminal, version
  File "/home/ybnd/.npm/node_modules/lib/node_modules/gitinspector/gitinspector/version.py", line 23, in <module>
    localization.init()
  File "/home/ybnd/.npm/node_modules/lib/node_modules/gitinspector/gitinspector/localization.py", line 71, in init
    __translation__.install(True)
  File "/usr/lib/python3.8/gettext.py", line 352, in install
    for name in allowed & set(names):
TypeError: 'bool' object is not iterable

Environment:

  • 5.8.0-2-Manjaro
  • Python 3.8.5
  • npm 6.14.4

@ybnd

@FeXd

This should be re-opoened. gitinspector has supported Python 3 for a long time.

It appears this is a recent break due to Python 3.8.x.

I can run everything fine using Python 3.6.6 but today I upgraded to 3.8.5 and am getting the same error you were.

Traceback (most recent call last):
  File "/Users/arlin/.nvm/versions/node/v12.18.1/bin/gitinspector", line 21, in <module>
    from gitinspector import gitinspector
  File "/Users/arlin/.nvm/versions/node/v12.18.1/lib/node_modules/gitinspector/gitinspector/gitinspector.py", line 26, in <module>
    from .blame import Blame
  File "/Users/arlin/.nvm/versions/node/v12.18.1/lib/node_modules/gitinspector/gitinspector/blame.py", line 28, in <module>
    from .changes import FileDiff
  File "/Users/arlin/.nvm/versions/node/v12.18.1/lib/node_modules/gitinspector/gitinspector/changes.py", line 29, in <module>
    from . import extensions, filtering, format, interval, terminal
  File "/Users/arlin/.nvm/versions/node/v12.18.1/lib/node_modules/gitinspector/gitinspector/format.py", line 28, in <module>
    from . import basedir, localization, terminal, version
  File "/Users/arlin/.nvm/versions/node/v12.18.1/lib/node_modules/gitinspector/gitinspector/version.py", line 23, in <module>
    localization.init()
  File "/Users/arlin/.nvm/versions/node/v12.18.1/lib/node_modules/gitinspector/gitinspector/localization.py", line 71, in init
    __translation__.install(True)
  File "/Users/arlin/.pyenv/versions/3.8.2/lib/python3.8/gettext.py", line 352, in install
    for name in allowed & set(names):
TypeError: 'bool' object is not iterable

Environment:

  • MacOS: 10.15.7
  • Python: 3.8.5
  • npm: 6.14.7

@adam-waldenberg

@rkochar

I too use Python 3.8.5 and was getting the same error as others on this post, tried the old faithful delete and re-installed, get this error. I am not sure if this is or not related to this post but I suspect it’s related to the python version.

sudo pip install gitinspector --no-cache-dir

Collecting gitinspector
  Downloading gitinspector-0.3.2.tar.gz (227 kB)
     |████████████████████████████████| 227 kB 332 kB/s 
    ERROR: Command errored out with exit status 1:
     command: /usr/bin/python3.8 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-hm1t9cld/gitinspector/setup.py'"'"'; __file__='"'"'/tmp/pip-install-hm1t9cld/gitinspector/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'rn'"'"', '"'"'n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-ntap7ime
         cwd: /tmp/pip-install-hm1t9cld/gitinspector/
    Complete output (16 lines):
    Traceback (most recent call last):
      File "/tmp/pip-install-hm1t9cld/gitinspector/gitinspector/version.py", line 25, in <module>
        localization.init()
    AttributeError: module 'localization' has no attribute 'init'
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-hm1t9cld/gitinspector/setup.py", line 22, in <module>
        from gitinspector.version import __version__
      File "/tmp/pip-install-hm1t9cld/gitinspector/gitinspector/version.py", line 27, in <module>
        import gitinspector.localization
      File "/tmp/pip-install-hm1t9cld/gitinspector/gitinspector/localization.py", line 22, in <module>
        import basedir
    ModuleNotFoundError: No module named 'basedir'
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

@ezhukovskiy

@adam-waldenberg

Not yet @ezhukovskiy . Until its included in a release — temporary fix available in in #216 and the comment above. I need to make sure it works with all versions of the gettext dependency.

Jehops

pushed a commit
to Jehops/freebsd-ports-legacy
that referenced
this issue

Mar 30, 2021

@sunpoet

uqs

pushed a commit
to freebsd/freebsd-ports
that referenced
this issue

Mar 30, 2021

uqs

pushed a commit
to freebsd/freebsd-ports
that referenced
this issue

Mar 30, 2021

@sunpoet

dch

pushed a commit
to cabal7/ports
that referenced
this issue

Mar 31, 2021

@sunpoet

@nishanthkumar23

Hi,

I am getting the same error running on latest python version ‘3.9.4’ with below ‘gitinspector’ command. can you please help me with this?

Environment:

windows: 10 Enterprise
Python: 3.9.2
npm: 7.7.6

Logs:

Traceback (most recent call last):
  File "C:Usersdevops_mgrgitinspector-0.4.4gitinspectorgitinspector.py", line 25, in <module>
    localization.init()
  File "C:Usersdevops_mgrgitinspector-0.4.4gitinspectorlocalization.py", line 76, in init
    __translation__.install(True)
  File "C:Usersdevops_mgrAppDataLocalProgramsPythonPython39libgettext.py", line 354, in install
    for name in allowed & set(names):
TypeError: 'bool' object is not iterable ```

@thiagodp

@0xBYTESHIFT

Wow, it’s almost a year since this issue was created, and it just happened to me too 😞

@abij

He, same here! waiting on a proper fix.

Azure DevOps hosted ubuntu agent:

  • Py 3.9.6
  • gitinspector (0.5.0dev) installed with npm

My «fix» inspired by maccuaa and thiagodp

# Note: I have hardcoded the path, this might be different for you.
#
# If this file exists, chain on success with &&...
#     sed -i  means: inline replace (overwrite file)
#         replace .install(True) with .install()

[ -f /usr/local/lib/node_modules/gitinspector/gitinspector/localization.py ] 
          && sed -i s'/.install(True)/.install()/' /usr/local/lib/node_modules/gitinspector/gitinspector/localization.py

@fuhrmanator

Going a step further from abij:

My «fix» inspired by maccuaa and thiagodp

Here’s something for Windows 10 using %USERPROFILE% for global install of gitinspector. (works in git bash):

#!/bin/bash
# If this file exists
#     sed -i  means: inline replace (overwrite file)
#         replace .install(True) with .install()

PATCHFILE="${USERPROFILE}/AppData/Roaming/npm/node_modules/gitinspector/gitinspector/localization.py"
POSIX_PATH=`cygpath $PATCHFILE`
if test -f $POSIX_PATH; then
    echo $POSIX_PATH
    sed -i s'/.install(True)/.install()/' $POSIX_PATH
fi

@wesleyyoung

Still happening

Ubuntu 20.04
Python 3.8

Traceback (most recent call last):
  File "/usr/bin/gitinspector", line 11, in <module>
    load_entry_point('gitinspector==0.4.4', 'console_scripts', 'gitinspector')()
  File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 490, in load_entry_point
    return get_distribution(dist).load_entry_point(group, name)
  File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 2854, in load_entry_point
    return ep.load()
  File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 2445, in load
    return self.resolve()
  File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 2451, in resolve
    module = __import__(self.module_name, fromlist=['__name__'], level=0)
  File "/usr/lib/python3/dist-packages/gitinspector/gitinspector.py", line 25, in <module>
    localization.init()
  File "/usr/lib/python3/dist-packages/gitinspector/localization.py", line 76, in init
    __translation__.install(True)
  File "/usr/lib/python3.8/gettext.py", line 352, in install
    for name in allowed & set(names):
TypeError: 'bool' object is not iterable

@ElvenSpellmaker

Going a step further from abij:

My «fix» inspired by maccuaa and thiagodp

Here’s something for Windows 10 using %USERPROFILE% for global install of gitinspector. (works in git bash):

#!/bin/bash
# If this file exists
#     sed -i  means: inline replace (overwrite file)
#         replace .install(True) with .install()

PATCHFILE="${USERPROFILE}/AppData/Roaming/npm/node_modules/gitinspector/gitinspector/localization.py"
POSIX_PATH=`cygpath $PATCHFILE`
if test -f $POSIX_PATH; then
    echo $POSIX_PATH
    sed -i s'/.install(True)/.install()/' $POSIX_PATH
fi

This worked for me Windows 10, Cygwin, Python 3.8.10.

@sparksmith

Still happening when using the search making mylar3 unusable.

Python Version : 3.9.7
Docker running on RaspberyPi4 with Dietpi v8_1

500 Internal Server Error
The server encountered an unexpected condition which prevented it from fulfilling the request.

Traceback (most recent call last):
  File "/usr/lib/python3.9/site-packages/cherrypy/_cprequest.py", line 638, in respond
    self._do_respond(path_info)
  File "/usr/lib/python3.9/site-packages/cherrypy/_cprequest.py", line 697, in _do_respond
    response.body = self.handler()
  File "/usr/lib/python3.9/site-packages/cherrypy/lib/encoding.py", line 223, in __call__
    self.body = self.oldhandler(*args, **kwargs)
  File "/usr/lib/python3.9/site-packages/cherrypy/_cpdispatch.py", line 54, in __call__
    return self.callable(*self.args, **self.kwargs)
  File "/app/mylar3/mylar/webserve.py", line 996, in searchit
    for x in searchresults:
TypeError: 'bool' object is not iterable

@jcdufourd

still happens even with the patch on localization.py…
Python version 3.9.13
Mac m1 12.4

@mkschreder

Still happening (latest ubuntu). However localization fix fixed it.

Other warnings though:
image

У меня странная проблема. У меня есть метод, который возвращает логическое значение. В свою очередь мне нужен результат этой функции, возвращенный снова, поскольку я не могу напрямую вызвать метод из front-end. Здесь мой код:

# this uses bottle py framework and should return a value to the html front-end
@get('/create/additive/<name>')
def createAdditive(name):
    return pump.createAdditive(name)



 def createAdditive(self, name):
        additiveInsertQuery = """ INSERT INTO additives
                                  SET         name = '""" + name + """'"""
        try:
            self.cursor.execute(additiveInsertQuery)
            self.db.commit()
            return True
        except:
            self.db.rollback()
            return False

Это создает исключение: TypeError (объект ‘bool’ не является итерабельным «,)

Я не получаю эту ошибку вообще, так как я не пытаюсь «перебирать» значение bool, а только возвращать ее.

Если я возвращаю строку вместо boolean или int, она работает так, как ожидалось. Что может быть проблемой здесь?

Traceback:

Traceback (most recent call last):
  File "C:Python33libsite-packagesbottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Я пытаюсь запустить список файлов в каталоге через исполняемый файл UNIX с помощью python. Я бы выводил исполняемый файл для каждого файла, записанного в другой каталог, но сохраняя исходное имя файла.

Я использую python 2.7, поэтому использую метод subprocess.call. Я получаю сообщение об ошибке, в котором говорится, что «объект ‘bool’ не является итерируемым», что, как я предполагаю, связано с той частью, где я пытаюсь записать выходные файлы, как когда я запускаю следующий скрипт через консоль, я получаю ожидаемый результат к исполняемому файлу в окне консоли:

import subprocess
import os

for inp in os.listdir('/path/to/input/directory/'):
    subprocess.call(['/path/to/UNIX/executable', inp])

Мой код в настоящее время таков:

import subprocess
import os

for inp in os.listdir('/path/to/input/directory/'):
    out = ['/path/to/output/directory/%s' % inp]
    subprocess.call(['/path/to/UNIX/executable', inp] > out)

Однако эта вторая партия кода возвращает ошибку «bool не является итерируемой».

Я предполагаю, что решение довольно тривиальное, поскольку это не сложная задача, однако, как новичок, я не знаю, с чего начать!

РЕШЕНО: после ответа @barak-itkin для тех, кто может столкнуться с этой проблемой в будущем, код успешно запустился, используя следующее:

import subprocess
import os

for inp in os.listdir('/path/to/input/directory/'):
    with open('/path/to/output/directory/%s' % inp, 'w') as out_file:
        subprocess.call(['/path/to/UNIX/executable', inp], stdout=out_file)

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Bool object is not callable ошибка
  • Bookworm 5791f53b far cry 5 ошибка