Why are underscores better than hyphens for file n

2019-02-05 10:41发布

问题:

From Building Skills in Python:

"A file name like exercise_1.py is better than the name execise-1.py. We can run both programs equally well from the command line, but the name with the hyphen limits our ability to write larger and more sophisticated programs."

Why?

回答1:

The issue here is that importing files with dashes in their name doesn't work since dashes are minus signs in python. So, if you had your own module you wanted to import, it couldn't have a dash in its name:

>>> import test-1
  File "<stdin>", line 1
    import test-1
               ^
SyntaxError: invalid syntax
>>> import test_1
>>>

Larger programs tend to be logically separated into many different modules, hence the quote

the name with the hyphen limits our ability to write larger and more sophisticated programs.



回答2:

From that very document (p.368, Section 30.2 'Module Definition'):

Note that a module name must be a valid Python name... A module's name is limited to letters, digits and "_"s.



标签: python naming