Python Forum
TypeError: 'NoneType' object is not subscriptable
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
TypeError: 'NoneType' object is not subscriptable
#1
I'm trying to check whether the user entered the correct path or not.
when the output appears it doesn't give any error but when i close the output it gets an error :

Traceback (most recent call last):
  File "voice_translate.py", line 115, in <module>
    main()
  File "voice_translate.py", line 88, in main
    if check_file(values["Path"]):
TypeError: 'NoneType' object is not subscriptable
I think it's wrong the
os.path.isfile()
method
but when I try to catch the error it still returns the same error

Here's the code to try to catch the error :
def check_file(path):
    try:
        os.path.isfile(path)
        return True
    except TypeError:
        return False
and this is the main code :
import os
import pyttsx3
import requests
import googletrans
import PySimpleGUI as sg
import speech_recognition as sr


def audio_layout():
    """ return audio layout """
    layout = [
        [sg.In(key="Path", size=(39, 0))],
        [
            sg.FileBrowse("Browse", size=(10, 0), target="Path"),
            sg.Button("Text", size=(10, 0)),
            sg.Button("Voice", size=(10, 0)),
        ],
    ]

    return sg.Window("Voice Translate", layout, finalize=True)


def result_layout():
    """ return result layout """
    layout = [[sg.Output(size=(60, 20))]]

    return sg.Window("Voice Translate", layout, finalize=True)


def language_translate(text, lang="id"):
    """ returns the text after it is translated """
    translator = googletrans.Translator()
    lang_convert = translator.translate(text, dest=lang)

    return lang_convert.text


def audio_to_text(audio):
    """ convert audio to text """
    recognizer = sr.Recognizer()
    sound = sr.AudioFile(audio)
    with sound as source:
        audio = recognizer.record(source)

    return recognizer.recognize_google(audio)


def text_to_audio(text):
    """ convert text into voice """
    engine = pyttsx3.init()
    engine.say(text)
    engine.runAndWait()
    engine.stop()


def check_internet():
    """ return true if internet is connect  """
    # google url only to test whether the user is connected to the internet
    url = "https://www.google.com/"
    timeout = 3
    try:
        requests.head(url, timeout=timeout)
        return True
    except requests.ConnectionError:
        sg.popup("Lost Connection!")
        return False


def check_file(path):
    try:
        os.path.isfile(path)
        return True
    except TypeError:
        return False


# main program
def main():
    audio_window, result_window, allowed = audio_layout(), None, False
    while check_internet():
        # read/get all event in all window
        window, event, values = sg.read_all_windows()
        # audio layout/window event handling
        if window == audio_window and event in (sg.WIN_CLOSED, "Exit"):
            break

        # bug! "TypeError: 'NoneType' object is not subscriptable"
        if check_file(values["Path"]):
            convert_to_text = audio_to_text(values["Path"])
            text_translate = language_translate(convert_to_text)
            allowed = True

        # user get the translate result of their voice
        if event == "Text" and allowed:
            result_window = result_layout()
            # show the output on output widget
            print(text_translate)

        if event == "Voice" and allowed:
            text_to_audio(text_translate)

        # result layout/window event handling
        if window == result_window and event in (sg.WIN_CLOSED, "Exit"):
            result_window.close()
            result_window = None
            allowed = False


    audio_window.close()
    if result_window is not None:
        result_window.close()


if __name__ == "__main__":
    main()
I know I can put the try and except statements above if or even replace them but I think it becomes unclean code and might make my code dirty
Reply
#2
Please show the complete error message. It surely tells on what line the error occurs.
Reply
#3
(Sep-26-2020, 07:44 AM)syafiq14 Wrote: TypeError: 'NoneType' object is not subscriptable

The error is self-explanatory. You are trying to subscript an object which you think is a list or dict, but actually is None (i.e: the object has no value). This means that you tried to do:

None[something]

Here you attempted to index an object that doesn’t have that functionality. You might have noticed that the method sort() that only modify the list have no return value printed – they return the default None. This is a design principle for all mutable data structures in Python.

This ‘NoneType’ object is not subscriptable is the one thrown by python when you use the square bracket notation object[key] where an object doesn’t define the getitem method.
buran write Sep-19-2022, 07:06 AM:
Necroposting with sole purpose to advertise your site is not acceptable. Link removed.
Reply
#4
cristydavidd Wrote:The error is self-explanatory.
The error traceback contains valuable information (including line numbers) that not only show where the error occurred, but also show what was processed just prior to the fail. This is why we ask for it.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  TypeError: cannot pickle ‘_asyncio.Future’ object Abdul_Rafey 1 268 Mar-07-2024, 03:40 PM
Last Post: deanhystad
  error in class: TypeError: 'str' object is not callable akbarza 2 444 Dec-30-2023, 04:35 PM
Last Post: deanhystad
Bug TypeError: 'NoneType' object is not subscriptable TheLummen 4 678 Nov-27-2023, 11:34 AM
Last Post: TheLummen
  TypeError: 'NoneType' object is not callable akbarza 4 917 Aug-24-2023, 05:14 PM
Last Post: snippsat
  [NEW CODER] TypeError: Object is not callable iwantyoursec 5 1,260 Aug-23-2023, 06:21 PM
Last Post: deanhystad
  Python: Regex is not good for re.search (AttributeError: 'NoneType' object has no att Melcu54 9 1,383 Jun-28-2023, 11:13 AM
Last Post: Melcu54
  TypeError: 'float' object is not callable #1 isdito2001 1 1,044 Jan-21-2023, 12:43 AM
Last Post: Yoriz
  TypeError: a bytes-like object is required ZeroX 13 3,834 Jan-07-2023, 07:02 PM
Last Post: deanhystad
  Help with python 'not subscriptable' error Extra 3 1,976 Dec-16-2022, 05:55 PM
Last Post: woooee
  TypeError: 'float' object is not callable TimofeyKolpakov 3 1,367 Dec-04-2022, 04:58 PM
Last Post: TimofeyKolpakov

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020