Error nonetype object is not iterable симс 4

Ответили на вопрос 1 человек. Оцените лучшие ответы! И подпишитесь на вопрос, чтобы узнавать о появлении новых ответов.

На стадии ввода имени в тг боте выдает ошибку:
for row in result:
TypeError: ‘NoneType’ object is not iterable

Код db:

import sqlite3
class Database:
    def __init__(self, db_file):
        self.connection = sqlite3.connect(db_file)
        self.cursor = self.connection.cursor()
    def add_user(self, user_id):
        with self.connection:
             return self.cursor.execute("INSERT INTO 'users' ('user_id') VALUES (?)",(user_id,))

    def user_exist(self, user_id):
        with self.connection:
            result = self.cursor.execute("SELECT * FROM 'users' WHERE 'user_id' = ?",(user_id,)).fetchall()
            return bool(len(result))

    def set_nickname(self,user_id,nickname):
        with self.connection:
            return self.cursor.execute("UPDATE 'users' SET 'nickname' = ? WHERE 'user_id' = ?",(nickname,user_id))

    def get_signup(self,user_id):
        with self.connection:
            result = self.cursor.execute("SELECT 'signup' FROM 'users' WHERE 'user_id' = ?", (user_id,)).fetchone()
            for row in result:
                signup = str(row[0])
                return signup

    def set_signup(self,user_id, signup):
        with self.connection:
            return self.cursor.execute("UPDATE 'users' SET 'signup' = ? WHERE 'user_id' = ?",(signup,user_id))

Код main:

import logging
from aiogram import Bot, Dispatcher, executor, types
import markups as nav
from db import Database

TOKEN = "5103821559:AAGL20hGYw8wUvBdu7u_vNeUQlhVxjmQIQs"

logging.basicConfig(level = logging.INFO)

bot = Bot(token = TOKEN)
dp = Dispatcher(bot)

db = Database('database.db')

@dp.message_handler(commands = ['start'])
async def start(message: types.Message):
    if(not db.user_exist(message.from_user.id)):
        db.add_user(message.from_user.id)
        await bot.send_message(message.from_user.id, "Укажите ваш ник")
    else:
        await bot.send_message(message.from_user.id, "Вы уже зарегистрированы", reply_markup = nav.mainMenu)

@dp.message_handler()
async def bot_message(message: types.Message):
    if message.chat.type == 'private':
        if message.text == 'Профиль':
            pass
        else:
            if db.get_signup(message.from_user.id) == "setnickname":
                if len(message.text) > 15:
                    await bot.send_message(message.from_user.id, "Никнейм не должен превышать 15 символов")
                elif '@' in message.text or '/' in message.text:
                    await bot.send_message(message.from_user.id, "Вы ввели запрещеный символ")
                else:
                    db.set_nickname(message.from_user.id, message.text)
                    db.set_signup(message.from_user.id, "done")
                    await bot.send_message(message.from_user.id, "Регистрация прошла успешно", reply_markup = nav.mainMenu)
            else:
                await bot.send_message(message.from_user.id, "Я не понял")

if __name__ == "__main__":
    executor.start_polling(dp, skip_updates = True)

Прежде чем писать в тему, прочтите:

При описании своей проблемы, во избежание ненужной выясняловки, занимающее немало времени и места, пишите сразу:

1. Тип ОС (Windows XX, MacOS), разрядность ОС

Версия Sims 4

Указание какая игра, лицензия, пиратка, Legacy (некоторые моды, например BD, не поддерживают такую версию)

Версии основных модов с датой их выпуска

WickedWhims (WW)

Nisa’s Wicked Perversions (NWP)

Basemental Drugs  (BD)

McCmdCenter (MCCC)

Указать, имеется ли DeviousDesires (Wicked Whims Kinky, CNWW более не существует)

Указать, играете ли вы со включенным антивирусником AWAST

Указать после обновления 1.58, прогоняли ли вы свои моды через S4S на тест «Slot195» 

Если вопрос касается конкретного мода, указывайте его версию и дату

2. Полное описание проблемы,

желательно прикладывать графику, на которой видна ваша проблема, это поможет быстрее ее понять.

3. Приложить lastException.txt (в дальнейшем LE), если таковой имеется, а также WickedWhims.log, BE-ExceptionReport.html, (находятся в корне папки Electronic ArtsThe Sims 4), BE-PatchScannerReport.html, (последний находится в папке The Sims 4ModsTMEX-Settings), mc_lastexception.html, (находится в одной папке с модом МССС ) и др логи. Логи паковать в архиве rar, zip, 7z, (размещать в посту сам текст LE, в виду некоторых проблем, не надо) и прикладывать к посту.

Просьба отписываться, если проблема решилась и каким образом. Это поможет другим.

Примечание: обладателям Legacy убедиться, что ваши моды поддерживают Legacy

Правило: 

Если играешь с DeviousDesires и видишь ошибки, прежде чем писать сюда, первым делом удали, этот самый глючный из всех, мод вместе с его библиотекой.

Скорей всего, у вас все наладится.

——————————————————————————————————————

Прежде чем давать описание проблемы прочитайте про типовые проблемы, (имеющие наиболее частые однотипные вопросы) см. скрытый текст.

— прежде чем писать о своей проблеме, проверьте ее на так называемом чистом сохранении. Создание его: старую игровую папку переименовать, например, The Sims 41. Игра при запуске БЕЗ МОДОВ создаст новую папку The Sims 4. Создаете семью, сохраняетесь и выходите. Это называется ЧИСТОЕ СОХРАНЕНИЕ. Именно оно поможет легко вычислить глюки и проблемы с любым модом или папкой модов. 

— проблемы сразу после обновления игры. После обновления игры или установки дополнения, всегда обновляйте моды, ошибки гарантированы. Подготовьте обновленную отдельную папку Mods, и только после этого обновляйте игру. 

— если проблема началась после установки новых модов, удалите их все и устанавливайте по одному, контролируя на каком этапе возникает проблема. Для этого перед установкой модов всегда делайте бэкап своей игровой папки в укромном месте.

Wicked Whims Kinky (CNWW)  не пишется под Patreon-версии WW! Только под его публичные  версии с LL. Причем каждой публичной версии WW соответствует своя версия Wicked Whims Kinky (CNWW) . Проверяйте по датам выпуска. Дата выпуска Wicked Whims Kinky (CNWW) всегда должна быть позже выпуска соответствующего WW. Несоблюдение этого правила приводит не только к появлению оранжевых сообщений и LE, но и к проблемам в игре.

-Nisa’s Wicked Perversions (NWP) всегда выпускается вслед за версией WW. Проверяйте по датам выпуска. Дата выпуска NWP всегда должна быть позже выпуска соответствующего WW. Несоблюдение этого правила приводит к появлению оранжевых сообщений и LE.

— в виду требований Patreon в части отношений подростков со взрослыми и инцеста, данные настройки были удалены из Patreon-версий мода WW, но не удалены, (и не будут удаляться) из публичных версий LL, теперь для Patreon-версий WW необходим патч, разблокирующий данные настройки  TURBODRIVER_WickedWhims_InappropriateUnlock. Этот патч НЕ ТРЕБУЕТСЯ для публичных версий WW.

— если появилась цензура на обнаженных телах, удалите патч Turbodriver_WickedWhims_StreamerMode или TURBODRIVER_WickedWhims_Censorship (старое название того же мода). Этот патч требуется для подготовки видео для различных ресурсов, где имеются такие требования . Если у вас такой необходимости нет, удалите этот патч, для WW он не требуется.

— дыры в телах симок в верхней половине — это следствие грудных слайдеров. Удалите их или обновите их, если обновления существуют. Либо смиритесь с их появлением, но не следует сюда писать, если нет сил читать тему.

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

— При пустых строках в русских переводах, или когда перевод полностью не виден, выполняйте следующие правила:

убедитесь, что перевод соответствует версии мода

перевод должен быть всегда в одной папке с модом

перевод должен должен читаться первым в прямом алфавитном порядке (для Windows), при этом учитывать, что спецсимволы и цифры всегда читаются первыми. 

В виду специфичности MacOS, который читает в обратном алфавитном порядке, эти правила для него должны выполняться в другом порядке. Желательно впереди названия перевода ставить цифру «1», а мода «2». При таком раскладе перевод будет читаться гарантировано.

— переводы всегда имеют конфликт с оригиналами, это нормально. Исключение, перевод WW (для него делается шаблон).


— при проблемах с WW, примените команду ww.fix, сохранитесь и выйдете. Возможно, при следующем заходе их уже не будет. Если продолжатся, то примените более глубокую очистку этого мода. Описана в «Методике…» на первой странице.

— проблема в интерпретации результатов работы программы нахождения конфликтовModConflictDetector (MCD). Прежде чем, писать, о якобы, большом количестве конфликтов, почитайте о проблеме нулевых конфликтов тут. 

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

Чистка сейвов от Турбо

ОЧИСТКА ИГРЫ

Есть вероятность, что после обновления или из-за ошибок у вас будут проблемы с застрявшими переменными. Лучший способ справиться с ними — очистить свою сохраненку.

Прежде чем пытаться это сделать, попробуйте использовать команду ww.fix в игре. Это будет иметь аналогичный эффект для мелкой очистки без сброса настроек.

Вы можете очистить свою сохраненку в два этапа, но выполнение мелкой очистки должно быть достаточно в большинстве ситуаций.

МЕЛКАЯ ОЧИСТКА

WickedWhims сохраняет большинство дополнительных данных во внешних файлах, которые не встроены в игру. Все дополнительные файлы данных можно найти в папке «saves» ( Documents Electronic Arts The Sims 4 saves). Вы можете удалить папку под названием «WickedWhimsMod». Имейте в виду, что это приведет к удалению всех ваших настроек, связанных с WickedWhims и дополнительной информацией. Все настроения, черты, навыки и объекты будут сохранены.

ГЛУБОКАЯ ОЧИСТКА

НЕ ВЫПОЛНЯЙТЕ  глубокую очистку, не выполняя сначала мелкую очистку.

Детали данных WickedWhims встроены в игру. Вы можете очистить эти данные, удалив все файлы WickedWhims из папки «Моды» ( Documents Electronic Arts The Sims 4 Mods), включив игру и сохраните ее. 
Сохранение игры без установленного мода позволит удалить лишние данные, которые больше не нужны. Вы потеряете все навыки WickedWhims, moodlets, черты и объекты.

————————————————————————————————————————————————————————

После выхода патча 1.52 поломались некоторые прически и черты характера. При этом возникают проблемы с самой игрой, вплоть до краха.

Также возникла проблема бликования персонажей при любом параметре отображения персонажей ниже «Самого высокого». Проблему решать удалением поиска и удаления допов, поскольку они кроме отображения, могут вызывать случайные оранжевые окна и образование LE.

Способ решения вопроса с бликованием персонажей см. подробней тут.

После выхода патча 1.58 поломались элементы декора мебели, объектов. При этом возникают проблемы с самой игрой, вплоть до краха.

Метод поиска сломанных допов Slot195

Для тех, у кого происходит краш игры, нужно сделать следующее:

Скачайте и установите Sims 4 Studio  

Запустите её и откройте чит-консоль комбинацией клавиш Ctrl+Shift+C

В появившемся окошке введите «Slot195» (без кавычек)

Далее выберите паку «Mods». Нажмите «Ok».

Дождитесь пока программа просканирует вашу папку «Mods»

Появится окно со списком сломанных модов, которые нужно будет удалить уже вручную из вашей папки «Mods»

Убедитесь, что у вас установлена самая последняя версия Sims 4 Studio, перед тем как сделать всё выше перечисленное.

Проблема с кастомными стульями, на которые симы отказываются садиться, только на игровые от ЕА.

В весеннем обновлении игры были сломаны все кастомные стулья. Симы избегают и выбирают только стулья по умолчанию. Чтобы симы снова на них садились, нужно скачать и установить последнюю версию Sims 4 Studio. Далее через неё пофиксить все стулья (Управление контентом — Batch Fixes — Objects — Fix Chairs). Игру запускать не надо. Дождитесь результата в виде отчета. Запустите программу еще раз нажмите комбинацию клавиш Ctrl + Shift + C и в появившейся консоли введите код «chairfix.savegames.update» без кавычек. Нажмите ОК. Эта команда исправит стулья в вашем сохранении. После этого можно запустить игру. 

Метод дихотомии (50/50) поиска мода/допа, вызывающего проблемы.

Другие названия метода, половинного деления, 50/50, возможны другие.

Суть, сократить число проверяемых папок, путем исключения из проверки папок, заведомо чистых от глючного мода.

Если имеется проблема, все свои папки делите на равные половины и проверяете в какой половине находится ваша проблема. Чистую папку убираете, например, в корзину или иное место и снова делите пополам. Снова чистую половину убираете и продолжаете процесс до одной папки. В последней папке точно также делите все файлы пополам и выясняете в какой половине находится ваша проблема. Процесс продолжаете пока не останется проблемный мод/доп.

Существует более сложный способ выявления и удаления плохих CC, (искажающих облика сима, отсутствие лица, крест вместо одежды и прочее), но он предполагает использование Sims 4 Tray Importer.

Создайте сима,

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

Наденьте на сима подозрительную, поломанную шмотку/аксессуар и более ничего.

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

Сохраните сим в вашу библиотеку (трей).

Откройте Sims 4 Tray Importer.

Прокрутите вниз, пока не увидите своего недавно созданного сима и выберите его.

Нажмите «Экспортировать с CC» и сохраните его.

Откройте сохраненный файл и посмотрите на файлы CC. Если вы сделали это правильно, то должны быть только один или два файла пакета (.package).

Вы можете просмотреть эти файлы в Sims 4 Studio, можно S4PE, если вы не уверены, какой файл является плохим CC: Sims 4 Studio — «My CC».

Удалите плохой файл из папки модов Sims 4.

________________________________________________________________________________________________________________________________________

Черный список (ЧС)

Список глючных допов и модов находится в скрытом тексте:

Примечание:

список составляется на основе сообщений участников и названия даются так, как есть в их сообщениях.

При появлении обновлений модов или допов, просьба сообщать для внесения их сюда. 

Список поломанных объектов, возникших в версии 1.58

(проблема с уменьшением числа костей до 195)

Список модов и допов, найденные участниками AML

[MiniGiles]Azmodan22_UpdatedRig_MPEdit

[dreamteamsims] Starbucks Fridge
[KKB]kitchen set-3-counter ver.3
[KKB]Korean Style Goods-Bench

 [YUMIA] BEAUTY TABLE 

[Severinka] TS4 Chemical laboratory — cabinet

[Severinka] TS4 Alwine kidsroom — shelf
[Severinka] TS4 Antique set — chest coffee table
[Severinka] TS4 Evelina nursery — balloons floor lamp
[Severinka] TS4 Evelina nursery — toddlers bed
[Severinka] TS4 Evelina nursery — wigwam (armchair)
[Severinka] TS4 WildWest — bar shelf

[Severinka] TS4 Era livingroom — wooden big coffee table

[Severinka] TS4 Evelina kidsroom — vanity table

[Severinka] TS4 — wood burning stove v1

[Severinka] TS4 — wood burning stove v1
[Severinka] TS4 — wood burning stove v2

[W-Patreon] Celtis Coffee Table

amoebae — OMSP Shelf

AmericanDinerTableWithSockets
BS_20170405_BathIndustryShower
BS_20170406_BathIndustryShowerCurtain

ATS4_object_maruslife_cardboardboxbed_PETS

ATS4_object_maruslife_tentbed_PETS

ATS4_object_maruslife_tentbed_PETS

ATS4_object_garagesale_salecardboard_CL.package
ATS4_object_garagesale_saletablex1_CL.package
ATS4_object_giftsforsims_trubridgecoffeetable.package
ATS4_object_maruslife_cardboardballbed_PETS.package
ATS4_object_maruslife_cardboardboxbed_PETS.package
ATS4_object_maruslife_tentbed_PETS.package
ATS4_object_maruslife_tinbed_PETS.packageShinoKCRS4 Shabby Sidetable

daer0n BIBLIOTHEQUE E.package
daer0n MDN NSD outdoor set Softtub Hot Tub structure.package
DOX atelier fireplace.package
DOX Lorenzo Comfort Set concrete fireplace.package
Dresser Minimalist perfection (short) by Zonbka.package
Jomsims the roulette the table.package
kardofe_Kitchen dining room_Sideboard.package
linzlu-antique-wicker-coffee-table.package
mango_s4_Elisa_Console_Mesh.package

ND_732 — Aura Nursery — Crib Canopy

ND_737 — Aura Nursery — Throw Blanket

ND_828 — Erin Living — Throw Blanket

ND_1050 — Lyne Build Set — Three Quarters Window — 1×1 Left
ND_1051 — Lyne Build Set — Three Quarters Window — 1×1 Right

NynaeveDesign_479 — Soho Kitchen — Counter Island

NynaeveDesign_069 — Altara — Shelves (Shiftable)
OnyxSims4NaomiBookcaseLeftSide01252018
OnyxSims4NaomiBookcaseRightSide01252018
Pilar Brazil DisplayCabinet
Pilar CerezoAparador S4

SIMc-TSR-Tropics4-Firepit

SIMc-Verat-Brazier

SrslySims_FaireDresser

SaudadeSims_CharlestonFM_Dining Merged Al

SanoysimsLykkeLRMetalBookcase
ShinoKCRS4 CliveC N Shower
ShinoKCRS4 Shabby Sidetable
SIMc-Clarity4-Bikedecor
SIMc-Clarity4-Bikedecor

SIMc-Clarity4-CTable1x1

SIMc-Clarity4-EndTable

SIMc-Hacienda4-Cabinet2Pts

SIMc-TSR-Incantatrix-Cauldron
SIMc-TSR-Tropics4-Firepit

SIMc-TSR-ComeCozy4-CabinetH

SIMc-TSR-ScandiFeverL-Fireplace

SIMc-TSR-ScandiFeverL-Fireplace2

SIMc-TSR-Regenerate-Fireplace-CL.

SIMc-TSR-Tropics4-Firepit

SIMc-Recreio4-Brazier

SloxCompactKitchenCupboard1x1Slotted
SloxCompactKitchenCupboard2x1Slotted
SloxHuleaKitchenItemsShelf
SloxPatronExclusive102018Cabinet1
SloxPatronExclusive102018Cabinet2
SloxPatronExclusive102018Cabinet3
SloxPatronExclusive102018Cabinet4
SloxPatronExclusive201906ShelfHigh
Sn4_Bibliophile_bookcase_withbooks
Vega Industrial Shelving
Viviansims4_42_bookshelf

А также другие проблемы, связанные с этой версией и новым дополнением «Университет»

Моды, вызывающие отсутствие меню «Университет» во всех компьютерах

RVSN_Another_One_Bytes_The_Dust_Computer_Neutrals

RVSN_Another_One_Bytes_The_Dust_Computer_Colors.

————————————————————————————————————————————————

Все, что ломает игру:

Прически, ломающие игру

Тяжелое свопирование 2 сек. с интервалом 7 сек. Возникает «дергалка». Вызываются прическами CURBS «Colores Urbanos»

— curbs_yfHair_BettiePage01

— Curbs_hairsS4_36

— Simpliciaty_PrivateHairOctober2019 

Скорее всего прически данных авторов следует удалять все. поскольку у авторов принято их делать по одному шаблону.

Черты характера, ломающие игру и/или вызывающие ошибки

— черта булимии (англ. эквивалент не сообщен автором сообщения)

— некоторые из этих черт

1.png.669ade1ed39f1291e0d5755b1cba4c79.png

Глючная одежда, вызывающая проблемы с загрузкой игры

2019-07-05_14-47-54.png.012f46e23cc34464905da64472888d38.png

— 142-blackrecolors одежда, черный пиджак. При загрузке игры вылет.

Объекты, ломающие игру

Сильные графические артефакты при активации объекта, затем краш игры.

— [Noir and Dark sims 4] Sex Doll — Maria — 01 

Скины, ломающие игру

S-Club WMLL ts4 HS3.0 F skin.package

____________________________________________________________________________________________________________________________________________

Проблемы отсутствия частей тела

Нет головы

NANDONG_ymHead Default Replacement without EA Eyelash.package
NANDONG_yfHead Default Replacement without EA Eyelash.package

Проблема отсутствия тел у мужских симов

— LLS_PectacularNewReplacement

— [fixed]LUUMIA_DR_BODEII_Lean.package

Проблема отсутствия верхней половины тела

— [THISISTHEM] Denny’s Skin Overlay

PK — Pastel Streak Crop Tank Top.package
PK — Floral Crop Top.package
PK — Fur Crop Tank Top.package

Проблема отсутствия нижней половины тела

142-blackrecolors

[fixed]LUUMIA_DR_BODEII_Lean.package

Проблема отсутствия верхней половины женского тела

LUUMIA DR’s tit

Проблема отсутствия нижней половины женского тела

Simtasia’s Female Body Bottom.

Проблема отсутствия лица связан с ресницами

epp-noEAeyelashhesUPDATE.package

— Cien-No EA Lashes  For-Females only TN YA AD EL AL Vamp   доп обновлен, проблема решена.

— ZombieApocalypse_Decapitated Head_NoHead

— NANDONG_yfHeadDefault

SympxlsWinterScarfRC.package

Пропадание руки из-за слайдера

— LUUMIA_mod_HandFingerSliders (пока не обновлен)

Проблема черного пениса

— скинтон S-Club WM ts4 skincolor 09 (22.09.2015)

— скинтон Simsperience_FreshSkins_1-63_Fixed (15.10.2018)

— MsBlue_LauraSkintones
— MsBlue_SkintoneSetV1
— MsBlue_SkintoneSetV2
— PauleanR_SkinTone_v1.0
— PYXIS_StuckOnYou_Skintones_NATURAL-IL
— SIMSINSPRING_Genetic-HumanSkin_BNatural-Fair
— SIMSINSPRING_Genetic-HumanSkin_BNatural-Pale

Проблема зеленого пениса

— скинтон xmiramiramelaninpack1 (27.10.2017)

Проблема отделения языка от лица и пениса у мужчин от тела

— merman hair physics mod

— NANDONG_yfHeadDefault

— NANDONG_ymHeadDefaultHQ

— NANDONG_OverideSliderHeadJawMouthForTongueCompability

— Non_EVE.package из пакета BodySelectorNonEve.zip

Другие проблемы, связанные с телом

Проблема застревания симок в розовом лифчике

Вина лежит на одном из этих модов

— REDHEADSIMS_S4Presets_ChubbyV2

— EVOL_EVOLVED-ExpandedPhysiqueRange_x3

— [fixed]LUUMIA_DR_BODEII_Lean

— [fixed]LUUMIA_DR_TIT-E_Medium

Точнее не сказать, проблема так обозначена по сообщениям участников на LL.

Пресет носа вызывает порчу лица персонажа (чернота лица), и черный силуэт вместо фигуры.

-obscurus_nose_presets_2m.package

— а также MidBobBangsConversion by KiaraZurk

Черный силуэт в режиме жизни (в CAS нормально)

— HallowSims_PoseidonsimsTulip

Причина невозможности выбрать цвет глаз в CAS (по умолчанию становятся карими)

— Alf-si_eyes_04_HQ_default

— [Ts4]Taty_JemEyes_Default

Причина нарушения элементов меню в CAS (отсутствие крестиков и др.)

CC wrench override

——————————————————————————————————————-

Разные проблемы

Исчезновение одежды

DarkCottageCore.package

Большая очередь из взаимодействий

BaddiesHangoutV3.package

BaddiesHangoutV3.ts4script

Объекты, вызывающие образование LE

PC-TS4-HG-Bathtub

iradium metal shower

MOTHERLODEshower

Невозможность увидеть профиль сима

Excitable Trait Snowiii95.package
Enchanter Trait 2.0 Snowiii95.package
Depressed Trait Snowiii95.package
FalseHope_SuicidalBehaviorDisorder_v2.package
FalseHope_SuicidalBehaviorDisorder_v2.ts4script
Serial Killer — BASE GAME + ALL AGES.package
Entomophobia — JUNGLE ADVENTURES REQUIRED — ALL AGES.package
JustAnotherSimsFanLongerInteractionQueue16054.package
Lover_Trait.package
Darkening_Demise_customtrait_nymphomaniac_icon.package
Darkening_Demise_customtrait_horny_icon.package
Darkening_Demise_customtrait_attention_whore_icon.package

Мод, который не дает создать сима с историей

— NoMoreVampireGrowling_DDF 

— или NoMoreVampireGrowling_СDF

— или NoMoreVampireGrowling_CAS Only

Моды, возможно, обновлены.

Невозможно создать любое мероприятие через календарь или по телефону, пустое окно без списка мероприятий 

Требует обновления мод

— Peculiar Desires Mod

MSQSIMS_New_Year’s_Eve_Party_Event.package

———————————————————————————————————————-

Допы, вызывающие бликование персонажей.

Бликование возникает при установке ниже самого высоко уровня качества отображения симов в настройках графики.

Мейкап (вызывал бликование симов)

— некоторые помады от FashionRoyaltySims, в частности (могут найтись другие от того же автора)

    FRS Kara Lip Liquid 

    FRS Lipstick N25 (HQ) по мотивам Библии Карли.

Прически

— некоторые прически  от Newsea, в частности J139 (могут найтись другие от того же автора)

— многие прически от WINGS, в частности, (могут найтись другие от того же автора)

  WINGS HAIR TS4 OE0316 F
  WINGS HAIR TS4 OE0510 F
  WINGS HAIR TS4 OS0514 F

  WINGS DAY TS4 OS0408 F

Одежда

Вызывает бликование одежды от Harmonia, Cleotopia, by bukovka, Devilicious, Laupipi, Leia, Sims2fanbg и др. Проверяйте этих авторов в первую очередь или просто удаляйте, не проверяя, поскольку, судя по сообщениям участников, приходилось удалять до 80 допов от Harmonia.

В частности бликование вызывают

по bukovka_ya female_skirt_ultra shor.package
Cleotopia-AshleyRippedHighWaistedShorts.package
Cleotopia-LaceSummerTopBralet.package
Cleotopia-LittleDenimShortsRipped40.package
Cleotopia-SkinnyJeansBasicAnkleBootcut.package
Cleotopia-ZipperLeggings.package
Devilicious-AF-EternallyWeddingDress.package
Laupipi_Camilaвытягивание нитей.package
Лея-SlaveOutfit.package
MidBobBangsConversion по KiaraZurk (черный цвет) .package
Pixel_RealisticBottom_Chuby.package
Sims2fanbg_Dress_with_leather_jacket_new mesh.package

____________________________________________________________________________________________________________________________________________

—————————————————————————————————————————————————

Методические материалы по Sims 4

(см. скрытый текст)

Текст будет дополняться.

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

alexlnkp opened this issue

Jul 26, 2021

· 2 comments

Comments

@alexlnkp

When i launch a program it gives me this:

Arc_path: arcface_model/arcface_checkpoint.tar
aspect_ratio: 1.0
batchSize: 8
checkpoints_dir: ./checkpoints
cluster_path: features_clustered_010.npy
data_type: 32
dataroot: ./datasets/cityscapes/
display_winsize: 512
engine: None
export_onnx: None
feat_num: 3
fineSize: 512
fp16: False
gpu_ids: [0]
how_many: 50
id_thres: 0.03
image_size: 224
input_nc: 3
instance_feat: False
isTrain: False
label_feat: False
label_nc: 0
latent_size: 512
loadSize: 1024
load_features: False
local_rank: 0
max_dataset_size: inf
model: pix2pixHD
multisepcific_dir: ./demo_file/multispecific
nThreads: 2
n_blocks_global: 6
n_blocks_local: 3
n_clusters: 10
n_downsample_E: 4
n_downsample_global: 3
n_local_enhancers: 1
name: people
nef: 16
netG: global
ngf: 64
niter_fix_global: 0
no_flip: False
no_instance: False
no_simswaplogo: False
norm: batch
norm_G: spectralspadesyncbatch3x3
ntest: inf
onnx: None
output_nc: 3
output_path: ./output/pexels-polina-tankilevitch_swapsingle.mp4
phase: test
pic_a_path: ./demo_file/pexels-andrea-piacquadio.jpg
pic_b_path: ./crop_224/zrf.jpg
pic_specific_path: ./crop_224/zrf.jpg
resize_or_crop: scale_width
results_dir: ./results/
semantic_nc: 3
serial_batches: False
temp_path: ./temp_results
tf_log: False
use_dropout: False
use_encoded_image: False
use_mask: False
verbose: False
video_path: ./demo_file/pexels-polina-tankilevitch.mp4
which_epoch: latest
————— End —————-
input mean and std: 127.5 127.5
find model: ./insightface_func/modelsantelopeglintr100.onnx recognition
find model: ./insightface_func/modelsantelopescrfd_10g_bnkps.onnx detection
set det-size: (640, 640)
Traceback (most recent call last):
File «test_video_swapsingle.py», line 51, in
img_a_align_crop, _ = app.get(img_a_whole,crop_size)
TypeError: ‘NoneType’ object is not iterable

Command i use:
D:SimSwap-main>python test_video_swapsingle.py --isTrain false --name people --Arc_path arcface_model/arcface_checkpoint.tar --pic_a_path ./demo_file/pexels-andrea-piacquadio.jpg --video_path ./demo_file/pexels-polina-tankilevitch.mp4 --output_path ./output/pexels-polina-tankilevitch_swapsingle.mp4 --temp_path ./temp_results

@alexlnkp

It turns out that this message means that it couldn’t find a face on an image, using other images works.

@woctezuma

2 participants

@woctezuma

@alexlnkp

<report><version>2</version><sessionid>d5f54df10e8f16755beb3aae</sessionid><type>desync</type><sku>ea.maxis.sims4_64.15.pc</sku><createtime>2018-11-13 22:34:25</createtime><buildsignature>Local.Unknown.Unknown.1.47.49.1020-1.200.000.373.Release</buildsignature><categoryid>posture_graph.py:4094</categoryid><desyncid>d5f54df10e8f16755beb3aae</desyncid><systemconfig/><screenshot/><desyncdata>TODO: Exception thrown during Sim reset, possibly we should be kicking the Sim out of the game. (TypeError: ‘NoneType’ object is not iterable) Traceback (most recent call last): File «T:InGameGameplayScriptsCoresims4commands.py», line 369, in invoke_command File «T:InGameGameplayScriptsServerserver_commandsinteraction_commands.py», line 788, in select_choice File «T:InGameGameplayScriptsServerserverclient.py», line 265, in select_interaction File «T:InGameGameplayScriptsServerobjectsbase_object.py», line 266, in reset File «T:InGameGameplayScriptsServerservicesreset_and_delete_service.py», line 301, in trigger_reset File «T:InGameGameplayScriptsServerservicesreset_and_delete_service.py», line 419, in start_processing File «T:InGameGameplayScriptsServerservicesreset_and_delete_service.py», line 443, in _process File «T:InGameGameplayScriptsServerservicesreset_and_delete_service.py», line 553, in _process_one_record File «T:InGameGameplayScriptsServerserverclient.py», line 257, in select_interaction File «T:InGameGameplayScriptsServerinteractionschoices.py», line 258, in select File «T:InGameGameplayScriptsServerinteractionsaop.py», line 236, in test_and_execute File «T:InGameGameplayScriptsServerinteractionsaop.py», line 224, in execute File «T:InGameGameplayScriptsServerinteractionsaop.py», line 212, in execute_interaction File «T:InGameGameplayScriptsServerinteractionsinteraction_queue.py», line 1331, in append File «T:InGameGameplayScriptsLibcontextlib.py», line 119, in __exit__ File «T:InGameGameplayScriptsServerinteractionsinteraction_queue.py», line 878, in _head_change_watcher File «T:InGameGameplayScriptsServerinteractionsinteraction_queue.py», line 962, in _get_head File «T:InGameGameplayScriptsServerinteractionsinteraction_queue.py», line 339, in get_next_unblocked_interaction File «T:InGameGameplayScriptsServerinteractionsbasesuper_interaction.py», line 2416, in get_sims_with_invalid_paths File «T:InGameGameplayScriptsServerinteractionsbasesuper_interaction.py», line 2380, in _generate_connectivity File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 1457, in compute_transition_connectivity File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 1504, in run_transitions File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 3361, in _build_transitions File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 3152, in _build_and_log_transitions_for_sim File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 3214, in _build_transitions_for_sim File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 2692, in get_transitions_for_sim File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 2870, in _get_transitions_for_sim File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 5718, in generate_connectivity_handles File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 5531, in _get_segmented_path_connectivity_handles File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 545, in generate_right_paths File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 4139, in _right_path_gen File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 679, in _shortest_path_gen File «T:InGameGameplayScriptsCorealgos.py», line 121, in shortest_path_gen File «T:InGameGameplayScriptsCorealgos.py», line 121, in &lt;listcomp&gt; File «T:InGameGameplayScriptsCorecaches.py», line 281, in __missing__ File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 4094, in heuristic_fn_right File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 3778, in _get_destination_locations_for_estimate File «T:InGameGameplayScriptsServerobjectspoolspool_seat.py», line 279, in _cache_and_return_position_and_routing_surface_for_posture ValueError: not enough values to unpack (expected 2, got 0) During handling of the above exception, another exception occurred: Traceback (most recent call last): File «T:InGameGameplayScriptsServersimssim.py», line 1563, in on_reset_internal_state File «T:InGameGameplayScriptsServerinteractionsinteraction_queue.py», line 1433, in on_reset File «T:InGameGameplayScriptsLibcontextlib.py», line 112, in __enter__ File «T:InGameGameplayScriptsServerinteractionsinteraction_queue.py», line 865, in _head_change_watcher File «T:InGameGameplayScriptsServerinteractionsinteraction_queue.py», line 947, in get_head File «T:InGameGameplayScriptsServerinteractionsinteraction_queue.py», line 962, in _get_head File «T:InGameGameplayScriptsServerinteractionsinteraction_queue.py», line 339, in get_next_unblocked_interaction File «T:InGameGameplayScriptsServerinteractionsbasesuper_interaction.py», line 2416, in get_sims_with_invalid_paths File «T:InGameGameplayScriptsServerinteractionsbasesuper_interaction.py», line 2380, in _generate_connectivity File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 1457, in compute_transition_connectivity File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 1504, in run_transitions File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 3361, in _build_transitions File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 3152, in _build_and_log_transitions_for_sim File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 3214, in _build_transitions_for_sim File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 2692, in get_transitions_for_sim File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 2870, in _get_transitions_for_sim File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 5718, in generate_connectivity_handles File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 5531, in _get_segmented_path_connectivity_handles File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 545, in generate_right_paths File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 4139, in _right_path_gen File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 679, in _shortest_path_gen File «T:InGameGameplayScriptsCorealgos.py», line 121, in shortest_path_gen File «T:InGameGameplayScriptsCorealgos.py», line 121, in &lt;listcomp&gt; File «T:InGameGameplayScriptsCorecaches.py», line 281, in __missing__ File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 4094, in heuristic_fn_right TypeError: ‘NoneType’ object is not iterable rtim=0</desyncdata></report>
<report><version>2</version><sessionid>d5f54df10e8f16755beb3aae</sessionid><type>desync</type><sku>ea.maxis.sims4_64.15.pc</sku><createtime>2018-11-13 22:34:25</createtime><buildsignature>Local.Unknown.Unknown.1.47.49.1020-1.200.000.373.Release</buildsignature><categoryid>posture_graph.py:4094</categoryid><desyncid>d5f54df10e8f16755beb3aae</desyncid><systemconfig/><screenshot/><desyncdata>[sscholl] Exception processing ResetRecord:&lt;, reason:ResetReason.RESET_ON_ERROR, stage:_Stage.INTERNAL_STATE_RESET, being_processed:True, source:None, cause:Exception while selecting interaction from the pie menu.. This will result in a partially reset object (TypeError: ‘NoneType’ object is not iterable) Traceback (most recent call last): File «T:InGameGameplayScriptsCoresims4commands.py», line 369, in invoke_command File «T:InGameGameplayScriptsServerserver_commandsinteraction_commands.py», line 788, in select_choice File «T:InGameGameplayScriptsServerserverclient.py», line 265, in select_interaction File «T:InGameGameplayScriptsServerobjectsbase_object.py», line 266, in reset File «T:InGameGameplayScriptsServerservicesreset_and_delete_service.py», line 301, in trigger_reset File «T:InGameGameplayScriptsServerservicesreset_and_delete_service.py», line 419, in start_processing File «T:InGameGameplayScriptsServerservicesreset_and_delete_service.py», line 443, in _process File «T:InGameGameplayScriptsServerserverclient.py», line 257, in select_interaction File «T:InGameGameplayScriptsServerinteractionschoices.py», line 258, in select File «T:InGameGameplayScriptsServerinteractionsaop.py», line 236, in test_and_execute File «T:InGameGameplayScriptsServerinteractionsaop.py», line 224, in execute File «T:InGameGameplayScriptsServerinteractionsaop.py», line 212, in execute_interaction File «T:InGameGameplayScriptsServerinteractionsinteraction_queue.py», line 1331, in append File «T:InGameGameplayScriptsLibcontextlib.py», line 119, in __exit__ File «T:InGameGameplayScriptsServerinteractionsinteraction_queue.py», line 878, in _head_change_watcher File «T:InGameGameplayScriptsServerinteractionsinteraction_queue.py», line 962, in _get_head File «T:InGameGameplayScriptsServerinteractionsinteraction_queue.py», line 339, in get_next_unblocked_interaction File «T:InGameGameplayScriptsServerinteractionsbasesuper_interaction.py», line 2416, in get_sims_with_invalid_paths File «T:InGameGameplayScriptsServerinteractionsbasesuper_interaction.py», line 2380, in _generate_connectivity File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 1457, in compute_transition_connectivity File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 1504, in run_transitions File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 3361, in _build_transitions File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 3152, in _build_and_log_transitions_for_sim File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 3214, in _build_transitions_for_sim File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 2692, in get_transitions_for_sim File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 2870, in _get_transitions_for_sim File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 5718, in generate_connectivity_handles File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 5531, in _get_segmented_path_connectivity_handles File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 545, in generate_right_paths File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 4139, in _right_path_gen File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 679, in _shortest_path_gen File «T:InGameGameplayScriptsCorealgos.py», line 121, in shortest_path_gen File «T:InGameGameplayScriptsCorealgos.py», line 121, in &lt;listcomp&gt; File «T:InGameGameplayScriptsCorecaches.py», line 281, in __missing__ File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 4094, in heuristic_fn_right File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 3778, in _get_destination_locations_for_estimate File «T:InGameGameplayScriptsServerobjectspoolspool_seat.py», line 279, in _cache_and_return_position_and_routing_surface_for_posture ValueError: not enough values to unpack (expected 2, got 0) During handling of the above exception, another exception occurred: Traceback (most recent call last): File «T:InGameGameplayScriptsServerservicesreset_and_delete_service.py», line 553, in _process_one_record File «T:InGameGameplayScriptsServersimssim.py», line 1563, in on_reset_internal_state File «T:InGameGameplayScriptsServerinteractionsinteraction_queue.py», line 1433, in on_reset File «T:InGameGameplayScriptsLibcontextlib.py», line 112, in __enter__ File «T:InGameGameplayScriptsServerinteractionsinteraction_queue.py», line 865, in _head_change_watcher File «T:InGameGameplayScriptsServerinteractionsinteraction_queue.py», line 947, in get_head File «T:InGameGameplayScriptsServerinteractionsinteraction_queue.py», line 962, in _get_head File «T:InGameGameplayScriptsServerinteractionsinteraction_queue.py», line 339, in get_next_unblocked_interaction File «T:InGameGameplayScriptsServerinteractionsbasesuper_interaction.py», line 2416, in get_sims_with_invalid_paths File «T:InGameGameplayScriptsServerinteractionsbasesuper_interaction.py», line 2380, in _generate_connectivity File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 1457, in compute_transition_connectivity File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 1504, in run_transitions File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 3361, in _build_transitions File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 3152, in _build_and_log_transitions_for_sim File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 3214, in _build_transitions_for_sim File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 2692, in get_transitions_for_sim File «T:InGameGameplayScriptsServerposturestransition_sequence.py», line 2870, in _get_transitions_for_sim File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 5718, in generate_connectivity_handles File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 5531, in _get_segmented_path_connectivity_handles File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 545, in generate_right_paths File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 4139, in _right_path_gen File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 679, in _shortest_path_gen File «T:InGameGameplayScriptsCorealgos.py», line 121, in shortest_path_gen File «T:InGameGameplayScriptsCorealgos.py», line 121, in &lt;listcomp&gt; File «T:InGameGameplayScriptsCorecaches.py», line 281, in __missing__ File «T:InGameGameplayScriptsServerposturesposture_graph.py», line 4094, in heuristic_fn_right TypeError: ‘NoneType’ object is not iterable rtim=0</desyncdata></report>

Explanation of error: ‘NoneType’ object is not iterable

In python2, NoneType is the type of None. In Python3 NoneType is the class of None, for example:

>>> print(type(None))     #Python2
<type 'NoneType'>         #In Python2 the type of None is the 'NoneType' type.

>>> print(type(None))     #Python3
<class 'NoneType'>        #In Python3, the type of None is the 'NoneType' class.

Iterating over a variable that has value None fails:

for a in None:
    print("k")     #TypeError: 'NoneType' object is not iterable

Python methods return NoneType if they don’t return a value:

def foo():
    print("k")
a, b = foo()      #TypeError: 'NoneType' object is not iterable

You need to check your looping constructs for NoneType like this:

a = None 
print(a is None)              #prints True
print(a is not None)          #prints False
print(a == None)              #prints True
print(a != None)              #prints False
print(isinstance(a, object))  #prints True
print(isinstance(a, str))     #prints False

Guido says only use is to check for None because is is more robust to identity checking. Don’t use equality operations because those can spit bubble-up implementationitis of their own. Python’s Coding Style Guidelines — PEP-008

NoneTypes are Sneaky, and can sneak in from lambdas:

import sys
b = lambda x : sys.stdout.write("k") 
for a in b(10): 
    pass            #TypeError: 'NoneType' object is not iterable 

NoneType is not a valid keyword:

a = NoneType     #NameError: name 'NoneType' is not defined

Concatenation of None and a string:

bar = "something"
foo = None
print foo + bar    #TypeError: cannot concatenate 'str' and 'NoneType' objects

What’s going on here?

Python’s interpreter converted your code to pyc bytecode. The Python virtual machine processed the bytecode, it encountered a looping construct which said iterate over a variable containing None. The operation was performed by invoking the __iter__ method on the None.

None has no __iter__ method defined, so Python’s virtual machine tells you what it sees: that NoneType has no __iter__ method.

This is why Python’s duck-typing ideology is considered bad. The programmer does something completely reasonable with a variable and at runtime it gets contaminated by None, the python virtual machine attempts to soldier on, and pukes up a bunch of unrelated nonsense all over the carpet.

Java or C++ doesn’t have these problems because such a program wouldn’t be allowed to compile since you haven’t defined what to do when None occurs. Python gives the programmer lots of rope to hang himself by allowing you to do lots of things that should cannot be expected to work under exceptional circumstances. Python is a yes-man, saying yes-sir when it out to be stopping you from harming yourself, like Java and C++ does.

Explanation of error: ‘NoneType’ object is not iterable

In python2, NoneType is the type of None. In Python3 NoneType is the class of None, for example:

>>> print(type(None))     #Python2
<type 'NoneType'>         #In Python2 the type of None is the 'NoneType' type.

>>> print(type(None))     #Python3
<class 'NoneType'>        #In Python3, the type of None is the 'NoneType' class.

Iterating over a variable that has value None fails:

for a in None:
    print("k")     #TypeError: 'NoneType' object is not iterable

Python methods return NoneType if they don’t return a value:

def foo():
    print("k")
a, b = foo()      #TypeError: 'NoneType' object is not iterable

You need to check your looping constructs for NoneType like this:

a = None 
print(a is None)              #prints True
print(a is not None)          #prints False
print(a == None)              #prints True
print(a != None)              #prints False
print(isinstance(a, object))  #prints True
print(isinstance(a, str))     #prints False

Guido says only use is to check for None because is is more robust to identity checking. Don’t use equality operations because those can spit bubble-up implementationitis of their own. Python’s Coding Style Guidelines — PEP-008

NoneTypes are Sneaky, and can sneak in from lambdas:

import sys
b = lambda x : sys.stdout.write("k") 
for a in b(10): 
    pass            #TypeError: 'NoneType' object is not iterable 

NoneType is not a valid keyword:

a = NoneType     #NameError: name 'NoneType' is not defined

Concatenation of None and a string:

bar = "something"
foo = None
print foo + bar    #TypeError: cannot concatenate 'str' and 'NoneType' objects

What’s going on here?

Python’s interpreter converted your code to pyc bytecode. The Python virtual machine processed the bytecode, it encountered a looping construct which said iterate over a variable containing None. The operation was performed by invoking the __iter__ method on the None.

None has no __iter__ method defined, so Python’s virtual machine tells you what it sees: that NoneType has no __iter__ method.

This is why Python’s duck-typing ideology is considered bad. The programmer does something completely reasonable with a variable and at runtime it gets contaminated by None, the python virtual machine attempts to soldier on, and pukes up a bunch of unrelated nonsense all over the carpet.

Java or C++ doesn’t have these problems because such a program wouldn’t be allowed to compile since you haven’t defined what to do when None occurs. Python gives the programmer lots of rope to hang himself by allowing you to do lots of things that should cannot be expected to work under exceptional circumstances. Python is a yes-man, saying yes-sir when it out to be stopping you from harming yourself, like Java and C++ does.

None and iterables are distinct types of objects in Python. None is the return value of a function that does not return anything, and we can use None to represent the absence of a value. An iterable is an object capable of returning elements one at a time, for example, a list. If you try to iterate over a None, you will raise the error “TypeError: ‘NoneType’ object is not iterable”.

This tutorial will go through the error in detail. We will go through an example scenario and learn how to solve the error.

Table of contents

  • TypeError: ‘NoneType’ object is not iterable
  • Example: Function Does Not Return a Value
    • Solution
    • How to Avoid the NoneType Exception
  • Summary

TypeError: ‘NoneType’ object is not iterable

TypeError occurs in Python when you perform an illegal operation for a specific data type. The “‘NoneType’ object is not iterable” part of the error tells us that the TypeError is referring to the iteration operation. You cannot iterate over an object that is not iterable.

Another example of a non-iterable object is an integer.

An iterable is a Python object that you can use as a sequence. You can go to the next item in the sequence using the next() method.

d = {"two": 2, "four":4, "six": 6, "eight": 8, "ten": 10}

iterable = d.keys()

print(iterable)
dict_keys(['two', 'four', 'six', 'eight', 'ten'])

The output is the dictionary keys, which we can iterate over. We can loop over the items and get the values using a for loop:

for item in iterable:

    print(d[item])

Here we use item as the index for the key in the dictionary. The following result will print to the console:

2
4
6
8
10

We can also create an iterator to use the next() method

d = {"two": 2, "four":4, "six": 6, "eight": 8, "ten": 10} 

iterable = d.keys()

iterator = iter(iterable)

print(next(iterator))

print(next(iterator))
two

four

The code returns the first and second items in the dictionary.

For an object to be iterable, it must contain a value. A None value is not iterable because it represents a null value.

You will not raise this error when iterating over an empty list or an empty string. In Python, list and string are iterable data types.

Let’s look at examples of trying to iterate over a NoneType, which raises the error: “TypeError: ‘NoneType’ object is not iterable”.

Example: Function Does Not Return a Value

Let’s write a program that takes a list of sandwiches and filters out those that contain cheese in the name. The program will print the sandwiches to the console. First, we will define a function that filters out the sandwiches:

def select_sandwiches(sandwiches):
   
    selected_sandwiches = []
    
    for sandwich in sandwiches:
    
        if "cheese" in sandwich:
   
            selected_sandwiches.append(sandwich)

The function select_sandwiches() loops over the items in the sandwiches list. If the item contains the word cheese, we add it to the selected_sandwiches list.

Next, we will write a function that goes through the selected_sandwiches list and prints each value to the console.

def print_sandwiches(sandwich_names):

    for s in sandwich_names:
        
        print(s)

With the two functions in place, we can declare a list of sandwiches for our program to search through. We need to pass the list of sandwiches to our select_sandwiches() function:

sandwiches = ["cheese and ham", "chicken salad", "cheese and onion", "falafel", "cheese and pickle", "cucumber"]

sandwiches_with_cheese = select_sandwiches(sandwiches)

We can then print all of the sandwiches that contain the word cheese to the console using the print_sandwiches() function.

print_sandwiches(sandwiches_with_cheese)

Let’s run the code to see what happens:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
      1 print_sandwiches(sandwiches_with_cheese)

in print_sandwiches(sandwich_names)
      1 def print_sandwiches(sandwich_names):
      2     for s in sandwich_names:
      3         print(s)
      4 

TypeError: 'NoneType' object is not iterable

We get an error message because the function select_sandwiches() does not return a value to iterate over. Therefore when we call print_sandwiches(), the function tries to iterate over a None value.

Solution

To solve the error, we need to return a value in the select_sandwiches() function. Let’s look at the revised code:

def select_sandwiches(sandwiches):

    selected_sandwiches = []

    for sandwich in sandwiches:

        if "cheese" in sandwich:

            selected_sandwiches.append(sandwich)

    # Added a return statement

    return selected_sandwiches

def print_sandwiches(sandwich_names):

    for s in sandwich_names:

        print(s)

sandwiches = ["cheese and ham", "chicken salad", "cheese and onion", "falafel", "cheese and pickle", "cucumber"]

sandwiches_with_cheese = select_sandwiches(sandwiches)

print_sandwiches(sandwiches_with_cheese)

The select_sandwiches() function returns the selected_sandwiches list. Let’s run the code to see what happens:

cheese and ham
cheese and onion
cheese and pickle

The program selects and prints out the sandwiches that contain the word cheese.

How to Avoid the NoneType Exception

You can avoid the NoneType exception by checking if a value is equal to None before you try to iterate over that value. Let’s modify the print_sandwiches() function:

def select_sandwiches(sandwiches):

    selected_sandwiches = []

    for sandwich in sandwiches:

        if "cheese" in sandwich:

            selected_sandwiches.append(sandwich)

    # Added a return statement

    return selected_sandwiches

def print_sandwiches(sandwich_names):

    if sandwich_names is not None:

        for s in sandwich_names:

            print(s)
    else:

        print('You are trying to iterate over a NoneType')

sandwiches = ["cheese and ham", "chicken salad", "cheese and onion", "falafel", "cheese and pickle", "cucumber"]

sandwiches_with_cheese = select_sandwiches(sandwiches)

print_sandwiches(sandwiches_with_cheese)

Let’s run the code to see what happens:

cheese and ham
cheese and onion
cheese and pickle

The code executes successfully. However, by putting is not None into the print_sandwiches() function, we will not know if a function is missing a return statement. Therefore, if you encounter this error, you should accept it and resolve the issue instead of using is not None.

Summary

Congratulations on reading to the end of this tutorial. The error “TypeError: ‘NoneType’ object is not iterable” occurs when you try to iterate over a NoneType object. Objects like list, tuple, and string are iterables, but not None. To solve this error, ensure you assign any values you want to iterate over to an iterable object. A common mistake is not adding a return statement to a function, which will make the function return None instead of a value. To solve this, ensure the function returns an iterable value.

For further reading on TypeErrors involving NoneType objects go to the article: How to Solve Python TypeError: can only join an iterable.

Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!

Explanation of error: ‘NoneType’ object is not iterable

In python2, NoneType is the type of None. In Python3 NoneType is the class of None, for example:

>>> print(type(None))     #Python2
<type 'NoneType'>         #In Python2 the type of None is the 'NoneType' type.

>>> print(type(None))     #Python3
<class 'NoneType'>        #In Python3, the type of None is the 'NoneType' class.

Iterating over a variable that has value None fails:

for a in None:
    print("k")     #TypeError: 'NoneType' object is not iterable

Python methods return NoneType if they don’t return a value:

def foo():
    print("k")
a, b = foo()      #TypeError: 'NoneType' object is not iterable

You need to check your looping constructs for NoneType like this:

a = None 
print(a is None)              #prints True
print(a is not None)          #prints False
print(a == None)              #prints True
print(a != None)              #prints False
print(isinstance(a, object))  #prints True
print(isinstance(a, str))     #prints False

Guido says only use is to check for None because is is more robust to identity checking. Don’t use equality operations because those can spit bubble-up implementationitis of their own. Python’s Coding Style Guidelines — PEP-008

NoneTypes are Sneaky, and can sneak in from lambdas:

import sys
b = lambda x : sys.stdout.write("k") 
for a in b(10): 
    pass            #TypeError: 'NoneType' object is not iterable 

NoneType is not a valid keyword:

a = NoneType     #NameError: name 'NoneType' is not defined

Concatenation of None and a string:

bar = "something"
foo = None
print foo + bar    #TypeError: cannot concatenate 'str' and 'NoneType' objects

What’s going on here?

Python’s interpreter converted your code to pyc bytecode. The Python virtual machine processed the bytecode, it encountered a looping construct which said iterate over a variable containing None. The operation was performed by invoking the __iter__ method on the None.

None has no __iter__ method defined, so Python’s virtual machine tells you what it sees: that NoneType has no __iter__ method.

This is why Python’s duck-typing ideology is considered bad. The programmer does something completely reasonable with a variable and at runtime it gets contaminated by None, the python virtual machine attempts to soldier on, and pukes up a bunch of unrelated nonsense all over the carpet.

Java or C++ doesn’t have these problems because such a program wouldn’t be allowed to compile since you haven’t defined what to do when None occurs. Python gives the programmer lots of rope to hang himself by allowing you to do lots of things that should cannot be expected to work under exceptional circumstances. Python is a yes-man, saying yes-sir when it out to be stopping you from harming yourself, like Java and C++ does.

The Python TypeError: NoneType Object Is Not Iterable is an exception that occurs when trying to iterate over a None value. Since in Python, only objects with a value can be iterated over, iterating over a None object raises the TypeError: NoneType Object Is Not Iterable exception.

What Causes TypeError: NoneType Object Is Not Iterable

For an object to be iterable in Python, it must contain a value. Therefore, trying to iterate over a None value raises the Python TypeError: NoneType Object Is Not Iterable exception. Some of the most common sources of None values are:

  • Calling a function that does not return anything.
  • Calling a function that sets the value of the data to None.
  • Setting a variable to None explicitly.

Python TypeError: NoneType Object Is Not Iterable Example

Here’s an example of a Python TypeError: NoneType Object Is Not Iterable thrown when trying iterate over a None value:

mylist = None

for x in mylist:
    print(x)

In the above example, mylist is attempted to be added to be iterated over. Since the value of mylist is None, iterating over it raises a TypeError: NoneType Object Is Not Iterable:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    for x in mylist:
TypeError: 'NoneType' object is not iterable

How to Fix TypeError in Python: NoneType Object Is Not Iterable

The Python TypeError: NoneType Object Is Not Iterable error can be avoided by checking if a value is None or not before iterating over it. This can help ensure that only objects that have a value are iterated over, which avoids the error.

Using the above approach, a check can be added to the earlier example:

mylist = None

if mylist is not None:
    for x in mylist:
        print(x)

Here, a check is performed to ensure that mylist is not None before it is iterated over, which helps avoid the error.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!

Понравилась статья? Поделить с друзьями:
  • Error object reference not set to an instance of an object veeam
  • Error object file git
  • Error object apache is not a member of package org
  • Error obj debug main o нет такого файла или каталога
  • Error nvidia installer must be run as root что делать