python模块层次结构命名约定 [英] python modules hierarchy naming convention

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

问题描述

我想要模块/包结构如下:

I'd like to have modules/packages structure like following:

/__init__.py
/mymodule.py
/mymodule/
/mymodule/__init__.py
/mymodule/submodule.py

然后使用如下模块:

import mymodule
import mymodule.submodule

但似乎文件mymodule.py"与mymodule"目录冲突.

But it seems like file "mymodule.py" conflicts with "mymodule" directory.

这里正确的命名约定是什么?

What's the correct naming convention here?

推荐答案

如果你想做一个包,你必须了解 Python 如何将文件名转换为模块名.

If you want to make a package, you have to understand how Python translates filenames to module names.

文件 mymodule.py 将作为 mymodule 使用,假设解释器在 Python 搜索路径的目录中找到它.如果您使用的是不区分大小写的文件系统,它也可以使用不同的大小写导入(但您应该避免使用这种依赖于系统的行为).

The file mymodule.py will be available as the mymodule, assuming the interpreter finds it in a directory in the Python search path. If you're on a case-insensitive filesystem, it might also be importable with different capitalization (but you should avoid using such system-dependent behavior).

包是一个包含 __init__.py 文件的目录.最近有一些动作允许没有这些文件的包,但我将忽略这个答案的不太常见的情况.包成为 Python 中的一个模块,其代码来自 __init__.py 文件.所以文件 mypackage/__init__.py 可以作为 mypackage 导入.

A package is a directory with an __init__.py file in it. There's been some movement recently to allow packages without those files, but I'm going to ignore that less-common case for this answer. A package becomes a module inside Python, with its code coming from the __init__.py file. So the file mypackage/__init__.py can be imported as mypackage.

直接在 Python 搜索路径中的 __init__.py 文件没有意义(好吧,我想你可以将它导入一个 __init__ 模块,但这可能是一个坏主意).

There's no meaning to an __init__.py file directly in the Python search path (well, I suppose you could import it an an __init__ module, but this is probably a bad idea).

因此,对于您的情况,以下是适当的文件系统布局:

So, for your situation, here's the appropriate filesystem layout:

toplevel/
    mymodule/
        __init__.py     # put code here for mymodule
        submodule.py    # put code here for mymodule.submodule

只有 toplevel 文件夹应该在 Python 搜索路径中.

Only the toplevel folder should be in the Python search path.

这篇关于python模块层次结构命名约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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