I have a problem where I’m trying to use a function from another module but that function calls a debug function which checks if a global variable has a certain attribute. This global variable is not set (otherwise set using parser.parse_args) when I import the function so the function complains that the attribute doesn’t exist. For clarification:
File findfile.py:
_args = {}
def _debug(msg):
if _TEST and _args.debug:
print msg
def findfile(filename):
...
_debug("found file")
...
if __name__ == "__main__":
...
_args = parser.parse_args()
...
File copyafile.py
import findfile
findfile.findfile("file1")
This gives me
AttributeError: 'dict' object has no attribute 'debug'
Now I understand that parser.parse_args() returns a namespace (??) and that _args.debug isn’t really looking in the dict. But my question is: How can I in this situation properly assign something to _args to set the _args.debug to False?
I can not change findfile.py but I can change copyafile.py.
How are these things usually handled otherwise? What is the pythonic way of enabling debug flags in a script?
The
findfile.pyis wrong as it’s written, but can you try to make it work anyway setting yourArgumentparserwith something like:and then with:
have your
_args.debugset toFalseby default.About your error:
You get
AttributeError: 'dict' object has no attribute 'debug', beacuse you’re trying to access adictlike if it was aNamespace.Maybe an example will clarify what a
Namespaceis: