Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Python package name start with a number?

Tags:

python

I know that naming a Python module starting with a number is a bad idea, as stated in this other question, but I'm wondering if is it legal to do so in a Python package, not module (aka file).

For example. I want to integrate a Django website with some external APIs and I wanted to create a "third party" package, containing a file for each provider, and I don't know if calling it 3rd_party will become a headache or I should name it third_party instead, to avoid problems.

Note: I don't know if it matters, but I'm using Python 2.7

like image 309
Caumons Avatar asked Jul 05 '13 10:07

Caumons


2 Answers

No, it cannot. Python package and module names need to be valid identifiers:

identifier ::=  (letter|"_") (letter | digit | "_")*

Identifiers must start with a letter or an underscore.

The import statement defines the grammar for modules as:

module          ::=  (identifier ".")* identifier

Packages are a special kind of module (implemented as a directory with __init__.py file) and are not exempt from these rules.

Technically you can work around this by not using the import statement, as the importlib module and __import__ hook do not enforce the restriction. It is however not a good idea to name your package or module such that you need to use non-standard import mechanisms to make it work.

like image 54
Martijn Pieters Avatar answered Oct 09 '22 19:10

Martijn Pieters


Yes.

# 1/x.py dont forget 1/__init__.py
x = 42

Import it from another file

# test.py
p1 = __import__('1.x')
print p1.x.x
like image 20
neuront Avatar answered Oct 09 '22 18:10

neuront