Python import : AttributeError: 'module' object has no attribute 'test'

24k views Asked by At

I think that's stupid problem, but I can't figure out why I get the following

AttributeError: 'module' object has no attribute 'test'

when running my test3.py.

Here is my project tree :

.
├── __init__.py
├── test3.py
└── testdir
    ├── __init__.py
    └── test.py

My test3.py :

#!/usr/bin/python                                                          

import testdir

if __name__ == "__main__":
    print(testdir.test.VAR)

My test.py :

#!/usr/bin/python

import os

VAR=os.path.abspath(__file__)

I also tried to import my VAR this way :

from testdir.test import VAR

EDIT: Now this one works -thanks to @user2357112- but I would still like to know how to import the whole test.py file without a from ... import ... if it is possible. :)

And I tried a import ..testdir to do a relative import but I got a SyntaxError.

And if I try import testdir.test I get a NameError: name'test' is not defined.

How could I import this file? I'm a bit confused.

EDIT bis :

I apologize, when I tried import testdir.test, I also modified print(testdir.test.VAR) to print(test.VAR).

That was the problem, my bad.

with :

#!/usr/bin/python                                                          

import testdir.test

if __name__ == "__main__":
    print(testdir.test.VAR)

It works perfectly, I though that importing testdir.test made test exist alone (and not testdir.test) in the scope.

Sorry for the inconvenience. :S

4

There are 4 answers

0
vmonteco On BEST ANSWER

I finally succeed to make it work this way :

#!/usr/bin/python                                                          

import testdir.test

if __name__ == "__main__":
    print(testdir.test.VAR)

I erroneously modified print(testdir.test.VAR) to print(test.VAR) when I tried with import testdir.test. So I had this NameError.

My bad.

2
hspandher On

Try adding from .test import VAR to testdir/init.py. Then import testdir print testdir.VAR in test3.py might work. I agree it is more of a workaround than solution.

1
dmr On

For adding the whole file with out using import statement, you can use execfile

1
Halkscout On

I know this one is old, but I had the same error relating to argparse. I had an instance where you'd run the script and pass test if you want to run tests (might be a weird way to do it, but I am new to this!). It would pass test to unittest.main() as well. I fixed it with this:

unittest.main(argv=['_'])

Below is what I had when it was working:

from tests import *

parser = argparse.ArgumentParser()
subparser = parser.add_subparsers(dest='command', title='Commands')
subcommand_parser = subparser.add_parser('test')
args.parse_args()

if args.command == 'test':
  unittest.main(argv=['_'])

This also helped me: https://stackoverflow.com/a/52369043/13752446