Search code examples
pythonwindowspython-importwinreg

Python 'import X as Y' results in 'NameError global name 'Y' is not defined


I'm new to python and trying to wrap my head around this error from the code below:

try:
    import _winreg as winreg
except ImportError:
    pass

...

path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
        try:
                 key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
        except WindowsError, e:
                if e.errno == 2:
                        return []
                else:
                        raise e

Outputs: NameError global name 'winreg' is not defined.

What am I missing to get this working? My guess is that they included 'import as' because _winreg is simply winreg in python 3+. I have tried simply importing as _winreg and replacing the winreg -> _winreg but that also returns a NameError with '_winreg' not defined. Thanks in advance!


Solution

  • You're silencing the ImportError.

    try:
        import _winreg as winreg
    except ImportError:
        pass
    

    winreg is most likely not getting imported here, hence the NameError: the winreg name was never assigned because import failed.

    You could remove the try / except block to confirm what's happening.


    Since you want to support Python 3, what you're most likely looking for is:

    try:
        import _winreg as winreg  # Try importing on Python 2
    except ImportError:
        import winreg  # Fallback to Python 3 (if this raises an Exception, it'll escalate)
    

    (_winreg was renamed in Python 3)