I am making a package in python3, using PyDev. One of my .py files has a simple relative import, from . import filename. When I use another file outside of the package to import from the package and test out that file it works fine, but running that file directly in PyDev fails with this error:
ImportError: attempted relative import with no known parent package
After a lot of searching, I found some code that works when I add it before any imports are made:
__path__ = [""] # indicates local directory
__package__ = ["package_name"]
Then everything runs fine. However, just a test, in that file I put this line: print(__name__)
The output is two strings!
package_name
__main__
I suspect this is just because it's in a package and being run directly, but then how do I do something like if __name__ == "__main__": ?
Here are some more outputs when I messed around with the __name__ var more:
print(repr(__name__))
# output
'package_name'
'__main__'
print(__name__.endswith("__main__"))
# output
False
True
print(type(__name__))
# output
<class 'str'>
<class 'str'>
I don't even understand how a variable could have two separate strings assigned to it. What is going on?
if __name__ == '__main__'guard, and that this file is also getting imported as a module in the course of running it as a script. In that case, the file will be executed twice, once as__main__and once as whatever module.if __name__ == '__main__'is supposed to guard against most of the negative effects of that, but it doesn't entirely work - for example, even with anif __name__ == '__main__'guard, classes defined in such a file will be defined twice. - user2357112 supports Monica