pythonmodulenaming-conventions

What are the requirements for naming Python modules?


I've been going through Learn Python The Hard Way. Instead of naming each example ex#.py (where # is the number of the exercise), however, I've just been calling them #.py. This worked fine until I got to Exercise 25, which requires you to import a module you just created through the interpreter. When I try this the following happens:

>>> import 25
  File "<stdin>", line 1
    import 25
            ^

SyntaxError: invalid syntax

I tried renaming the file to ex25.py and it then worked as expected (>>> import ex25). What are the naming requirements for Python modules? I had a look at the official documentation here but didn't see it mention any restrictions.


Solution

  • Modules that you import with the import statement must follow the same naming rules set for variable names (identifiers). Specifically, they must start with either a letter1 or an underscore and then be composed entirely of letters, digits2, and/or underscores.

    You may also be interested in what PEP 8, the official style-guide for Python code, has to say about module names:

    Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.


    1 Letters are the ASCII characters A-Z and a-z.
    2 Digits are the ASCII characters 0-9.