命名python模块有哪些要求? [英] What are the requirements for naming python modules?

查看:107
本文介绍了命名python模块有哪些要求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在通过学习Python的艰难之路作为一种复习课程.但是,我没有命名每个示例ex#.py(其中#是练习的编号),而是将它们命名为#.py.在我进入练习25 之前,该方法一直有效,这需要您导入刚通过创建的模块口译员.当我尝试此操作时,会发生以下情况:

I've been going through Learn Python The Hard Way as a sort of refresher. 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

我尝试将文件重命名为ex25.py,然后按预期方式工作(>>> import ex25).我想知道python模块的命名要求是什么?我在此处中查看了官方文档,但没有看到任何提及限制.

I tried renaming the file to ex25.py and it then worked as expected (>>> import ex25). What I'm wondering is 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.

iCodez,Pavel和BrenBarn的所有三个答案都提供了很好的资源,并有助于回答该问题的不同方面.我最终选择iCodez的答案作为正确答案,仅仅是因为这是第一个答案.

All three answers by iCodez, Pavel and BrenBarn give good resources and help answer different aspects of this question. I ended up picking iCodez's answer as the correct one simply because it was the first answer.

推荐答案

使用 import语句必须遵循为变量名(标识符)设置的相同命名规则.具体来说,它们必须以字母 1 或下划线开头,然后完全由字母,数字 2 和/或下划线组成.

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.

您可能还对 PEP 8感兴趣是Python代码的官方样式指南,必须提及模块名称:

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

模块应使用简短的全小写名称.下划线可以是 如果可以提高可读性,请在模块名称中使用. Python包 也应该使用短的全小写名称,尽管使用 不鼓励使用下划线.

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 字母是ASCII字符A-Za-z.
2 数字是ASCII字符0-9.


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

这篇关于命名python模块有哪些要求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆