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
2010-04-13 18:47:04
This is awful practice.
Mike Graham
2010-04-13 19:34:50
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
2010-04-13 19:44:21
A:
Or will the import command fail to parse it as a result?
It will indeed fail.
Joshua Fox
2010-04-13 18:52:02
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
2010-04-13 19:18:01
@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
2010-04-13 19:36:07
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
2010-04-13 19:48:29
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
2010-04-14 01:51:35