0

I'm new to python and now learning how to to import a module or a function, but I got these posted errors. The python code is saved under the name: hello_module.py

python code:

def hello_func():
    print ("Hello, World!")
hello_func()
import hello_module
hello_module.hello_func()

error message:

Traceback (most recent call last):
  File "C:/Python33/hello_module.py", line 9, in <module>
    import hello_module
  File "C:/Python33\hello_module.py", line 10, in <module>
    hello_module.hello_func()
AttributeError: 'module' object has no attribute 'hello_func'
1
  • 1
    import hello_module should not be in hello_module.py. it doesn't make sense. Commented May 3, 2013 at 17:27

1 Answer 1

4

You cannot and should not import your own module. You defined hello_func in the current namespace, just use that directly.

You can put the function in a separate file, then import that:

  • File foo.py:

    def def hello_func():
        print ("Hello, World!")
    
  • File bar.py:

    import foo
    
    foo.hello_func()
    

and run bar.py as a script.

If you try to import your own module, it'll import itself again, and when you do that you import an incomplete module. It won't have it's attributes set yet, so hello_module.hello_func doesn't yet exist, and that breaks.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.