Is it ok to use dashes in Python files when trying to import them? Is it ok to use dashes in Python files when trying to import them? python python

Is it ok to use dashes in Python files when trying to import them?


You should check out PEP 8, the Style Guide for Python Code:

Package and 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.

Since module names are mapped to file names, and some file systems are case insensitive and truncate long names, it is important that module names be chosen to be fairly short -- this won't be a problem on Unix, but it may be a problem when the code is transported to older Mac or Windows versions, or DOS.

In other words: rename your file :)


One other thing to note in your code is that import is not a function. So import(python-code) should be import python-code which, as some have already mentioned, is interpreted as "import python minus code", not what you intended. If you really need to import a file with a dash in its name, you can do the following::

python_code = __import__('python-code')

But, as also mentioned above, this is not really recommended. You should change the filename if it's something you control.


TLDR

Dashes are not illegal but you should not use them for 3 reasons:

  1. You need special syntax to import files with dashes
  2. Nobody expects a module name with a dash
  3. It's against the recommendations of the Python Style Guide

If you definitely need to import a file name with a dash the special syntax is this:

module_name = __import__('module-name')

Curious about why we need special syntax?

The reason for the special syntax is that when you write import somename you're creating a module object with identifier somename (so you can later use it with e.g. somename.funcname). Of course module-name is not a valid identifier and hence the special syntax that gives a valid one.

You don't get why module-name is not valid identifier?

Don't worry -- I didn't either. Here's a tip to help you: Look at this python line: x=var1-var2. Do you see a subtraction on the right side of the assignment or a variable name with a dash?

PS

Nothing original in my answer except including what I considered to be the most relevant bits of information from all other answers in one place