0

I have two files in the same location namely 'hello-depend.py' and 'second-package.py'

hello-depend.py

 class HelloDepend():

    def depend():

         print "depend"

second-package.py

from hello-depend import HelloDepend

 class SecondPackage():

    def second():

       print "second"

       h = HelloDepend()

       h.depend()


 if \__name__ == '\__main__':

    s = SecondPackage()

    s.second()

I need to create object for hello-depend.py from second-package.py. i tied with above method. But i am getting 'syntax error' while importing 'hello-depend'.

Error:

File "second-package.py", line 1

import hello-depend

            ^

SyntaxError: invalid syntax

So i tried with below method.

import importlib

importlib.import_module('hello-depend')

but i am getting "global name 'HelloDepend' not defined'

Please help me in solving this.

Note: I need to do this without changing file name.

4
  • @MohitC I already tired that .. i am getting 'syntax error ' while importing Commented Jun 12, 2018 at 12:04
  • post the complete traceback Commented Jun 12, 2018 at 12:04
  • @MohitC . i have posted the error message Commented Jun 12, 2018 at 12:10
  • Remove - from module name and use _ then try. Commented Jun 12, 2018 at 12:22

1 Answer 1

2

Problem is - here. Python tries to treat it as minus symbol and hello-depend is not a valid identifier then.

Try to rename your file by replacing - with underscore (_)

Edit: If you just cant change the file names, whatever the reason may be, then you can do

execfile('hello-depend.py')

Note that this does not import the file, it would get all the file globals into your own scope, and his highly unrecommended to solve this problem.

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

2 Comments

i need this functionality without changing the file name. I already mentioned that too.
Please read the PEP8 conevntion here. Python doesnt really allow packages names to be like that python.org/dev/peps/pep-0008

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.