How can I import a module with tilde in Python?


I know it's bad practice but I'm curious.

This works for me to create a default folder path:


But this:

import Módulo

It does not work. What should I do?


I understand that you are talking about python2, since in python 3 there is no problem, as you can see here:

# coding: utf-8
# Contenido del fichero Mó
def funcion():
    print("Función del módulo")
if __name__ != "__main__":
    print("¡Módulo importado!")

And in an interpreter:

>>> import Módulo
¡Módulo importado!
>>> Módulo.funcion()
Función del módulo

Instead in python2, the same attempt is a syntax error:

>>> import Módulo
  File "<stdin>", line 1
    import Módulo
SyntaxError: invalid syntax

The error is because in Python 2 identifiers cannot have accents (and importing a module creates an identifier with the same name, in order to access that module's namespace, as I did earlier with Módulo.funcion() ).

It is still possible to import it using the imp library (renamed import as of python 3.4), which allows you to interact at a low level with the functions that python uses to import.

The easiest way is to use imp.find_module() to find the module in the path chain, and return a tuple (three elements) that you need to pass to imp.load_module() , which actually loads the module. . To load_module() you also have to pass a parameter with the name that the module will receive "internally".

The value returned by imp.load_module() is the module itself, which you will assign to a variable in order to access its namespace . Logically the name of that variable cannot have accent marks in Python2.

So we would do something like this:

>>> import imp
>>> datos_modulo = imp.find_module("Módulo")
>>> mi_modulo = imp.load_module("Módulo", *datos_modulo)
¡Módulo importado!
>>> mi_modulo.funcion()
Función del módulo

The first parameter we pass when loading the module (the string "Módulo" ) is what the module will receive in the __name__ variable, and we can also access that name via mi_modulo.__name__ .

Scroll to Top