views:

98

answers:

3

Am I allowed to have a directory named 'import' containing Python code? Or will the import command fail to parse it as a result? Is there any way around that?

+6  A: 

You can use the built-in __import__ function which accepts any string. Thus you may write:

__import__('keyword.submodule')
Olivier
This is awful practice.
Mike Graham
It's not. There are plenty of situations where the use of `__import__` may come in very handy. Bottomline is: there is no restriction on the module names in python. Whether or not it should be abused is another question.
Olivier
A: 

Or will the import command fail to parse it as a result?

It will indeed fail.

Joshua Fox
A: 

You can have a directory with a name that is a Python keyword storing your Python code. This directory should not be used as a package, since package names should be valid Python identifiers.

Mike Graham
Wrong. See my answer.
Olivier
@Olivier, I said "should". Python doesn't stop me from doing all sorts of awful things. I can use invalid identifiers as variables my modifying `globals()` or for attributes using `setattr` or plenty of other places, but fortunately I know better.
Mike Graham
Your answer is misleading: you are saying that it's ok for a directory but not for a package to be a python keyword? I would say it's bad practice either way.
Olivier
I don't see any reason to impose a naming convention on directories that don't end up having anything to do with the Python code they contain.
Mike Graham