Unknown encoding: idna in socket.py

Encountered a problem (possible bug?) in socket.py related to idna encoding:

However this only happens in runtime mode, it works fine in debug mode!

Error:

  File "C:\Program Files\Python315\Lib\socket.py", line 826, in getfqdn
    hostname, aliases, ipaddrs = gethostbyaddr(name)
                                ~~~~~~~~~~~~~^^^^^^
LookupError: unknown encoding: idna

Main.py:

from wsgiref import simple_server
import Import1

def dummy():
    pass
httpd = simple_server.make_server("", 8000, dummy)

Import1.py:

import ImportHook

ImportHook.py:

import sys
from importlib.machinery import SourceFileLoader, FileFinder

class PreProcessLoader(SourceFileLoader): # SourceLoader
    def source_to_code(self, data, path, fullname, *, _optimize: int = -1):
        return super().source_to_code(data, path, fullname, _optimize=_optimize)

sys.path_hooks.insert(0, FileFinder.path_hook( (PreProcessLoader, [".py"]) ))
sys.path_importer_cache.clear()

I think it has something to do with you clearing the import cache. Try import encodings.idna before from wsgiref import simple_server.

@jonathandung That works, thanks.

However it also works if I put the same import encodings.idna between sys.path_hooks.insert(0... and sys.path_importer_cache.clear(). That suggests it may not be so much to do with the cache.clear() line as the sys.path_hooks.insert(0....

I have tried print(sys.modules) both before and after the cache.clear but can’t see any obvious differences.

Although this is a good quick fix for now, it would be preferable to get to the root cause so that it doesn’t come back to bite us in the future sometime.

I’m unfamiliar with the details of the Python import machinery, but this looks like an interesting problem.

Can you import any other .py file after installing your hook into sys.path_hooks?

Shouldn’t the source_to_code() of your SourceFileLoader subclass allow the fullname argument to be omitted (with a default value of None)?

@mgedmin Yes other files can be imported, the error does not show up until it hits the httpd = simple_server.make_server("", 8000, dummy) line.

You are quite right the fullname argument can, and perhaps should, be omitted, to the upstream call thanks for spotting that. I seem to recall this argument was new in 3.15 and I had to add it in to get the import hook working; and then to stop the type annotation warnings.

A bit more info: if I move import encodings.idna to before the httpd = simple_server.make_server line I then get error:
ModuleNotFoundError: Standard library module 'unicodedata' was not found

So something in your import hook is breaking standard library imports. The exact failing module is likely just coincidence.

See if you can figure out exactly what your loader is getting asked for when you import a stdlib module. My guess is you need to add something that says “oh this one’s not for me, use the default handling”.

@Rosuav I have now added this print into my source _to_code:

class PreProcessLoader(SourceFileLoader): # SourceLoader
    def source_to_code(self,
                       data: Buffer | str | ast.Module | ast.Expression | ast.Interactive,
                       path: bytes | str | os.PathLike[str],
                       fullname: str | None = None, *, _optimize: int = -1) -> CodeType:
        print("In source_to_code:", path)
        return super().source_to_code(pre_process(data, os.fsdecode(path)), path, _optimize=_optimize)

Of course that did nothing because the standard library imports didn’t need recompiling, so I then deleted (renamed) C:\Program Files\Python315\Lib\__pycache__ which caused permission problems so I created a new C:\Program Files\Python315\Lib\__pycache__ with full permissions for all users.

This now runs and I can see it importing various standard library modules but unfortunately still get the same LookupError: unknown encoding: idna.

You’re subclassing SourceFileLoader, so you get all of its existing methods. I’d start by overriding each of the methods of SourceLoader with one that prints out status and then returns super, as it’s entirely possible your PreProcessLoader is doing something it doesn’t need to.

As a side point: In digging through the docs to find where source_to_code is called, I find that it’s meant to be a static method. Is that possibly relevant?

Have now removed pre_process() from the equation completely. source_to_code is now:

class PreProcessLoader(SourceFileLoader): # SourceLoader
    def source_to_code(self,
                       data: Buffer | str | ast.Module | ast.Expression | ast.Interactive,
                       path: bytes | str | os.PathLike[str],
                       fullname: str | None = None, *, _optimize: int = -1) -> CodeType:
        print("In source_to_code:", path)
        return super().source_to_code(data, path, _optimize=_optimize)

Same idna error.

By the way also made it a @staticmethodbut still no change.

One thing I have now found is that:

import unicodedata
import encodings.idna
httpd = simple_server.make_server("", 8000, dummy)

causes:

import unicodedata
ModuleNotFoundError: Standard library module 'unicodedata' was not found

I can’t seem to find unicodedata anywhere in my Python 3.15 installation?

It’s a builtin module, like sys.

>>> import unicodedata
>>> unicodedata.__loader__
<class '_frozen_importlib.BuiltinImporter'>

How did you install Python?

@mgedmin
so it seems my system can’t find unicodedata for some reason.

If I revert to just:

import encodings.idna
httpd = simple_server.make_server("", 8000, dummy)

I get error:

  File "C:\Program Files\Python315\Lib\encodings\idna.py", line 3, in <module>
    import stringprep, re, codecs
  File "C:\Program Files\Python315\Lib\stringprep.py", line 10, in <module>
    import unicodedata
ModuleNotFoundError: Standard library module 'unicodedata' was not found

Although that still doesn’t ex[plain why I need to import encodings.idna in the first place.

@jonathandung
Python was installed from python-3.15.2-amd64.exe.

Have you tried to use the REPL to import unicodedata? Something like this:

Python 3.15.2 (tags/v3.15.2:5e58eaa, Oct 25 2026, 17:27:03) [MSC v.1951 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import unicodedata

It does not raise any error on my computer. If this works for you, then clearly it is something that is incorrect with the rest of your code. I suspect that it is your use of sys.path_importer_cache.clear() which likely removes the frozen module importer finder.

from REPL

>>> import sys
>>> sys.path_importer_cache.clear()
>>> import unicodedata

runs fine. Also running same from test prog runs fine.

The problem is definately the import hook for some unexplained reason:

from importlib.machinery import SourceFileLoader, FileFinder

class PreProcessLoader(SourceFileLoader): # SourceLoader
    def source_to_code(self,
                       data,path,fullname = None, *, _optimize: int = -1):
        print("In source_to_code:", path)
        return super().source_to_code(data, path, _optimize=_optimize)

import sys
sys.path_hooks.insert(0, FileFinder.path_hook( (PreProcessLoader, []) ))
sys.path_importer_cache.clear()

import socket # <- fails: ModuleNotFoundError: No module named 'socket'

You’re inserting a path hook that handles all filesystem directories. Such a path hook should AFAIK handle all kind of modules and in particular extension modules (which unicodedata is). The hook you’re inserting only handles “.py” source files.

See _install in _bootstrap_external.py for how the standard library creates the default path hooks for path-based path entries.

@ronaldoussoren I may be misunderstanding how to use an import hook but, reverting to the example below

from importlib.machinery import SourceFileLoader, FileFinder

@staticmethod
class PreProcessLoader(SourceFileLoader): # SourceLoader
    def source_to_code(data, path, fullname = None, * ,_optimize = -1):
        print("In source_to_code:", path)
        # return None
        return super().source_to_code(data, path, fullname, _optimize=_optimize)

import sys
sys.path_hooks.insert(0, FileFinder.path_hook( (PreProcessLoader, [".py"]) ))
sys.path_importer_cache.clear()
import unicodedata # <- fails: ModuleNotFoundError: Standard library module 'unicodedata' was not found

Isn’t the call to super().source_to_code(data, path, _optimize=_optimize) supposed to handle external modules? Either that or my PreProcessLoader tells Python that we have not handled this import and to move on to the next (FileFinder) loader in the sys.path_hooks list; I have tried returning None but that doesn’t help.

Why do you think you need this? By inserting your import hook at the beginning of sys.path_hooks, it will be used whenever possible. If you remove it, the exception will go away.

Without the sys.path_importer_cache.clear() the custom SourceFileLoader never runs.