1

I would like to create a package of my python code. My folder structure is like below:

sing*(this is a folder)*
--ml*(this is a folder)*
----regression*(this is a folder)*
------linear.py*(this is a class file with functions in it)* 
----classification*(this is a folder)*
------logistic.py*(this is a class file with functions in it)* 

i want to access class within linear.py by something like:

from sing.ml.regression import linear

Please advice how to create a package like this

thanks in advance

5
  • you already should be able to access to linear from where you are using absolute imports, I believe Commented Feb 28, 2018 at 9:11
  • my consumer application is hosted on azure. Commented Feb 28, 2018 at 9:17
  • @Shinratensei, are you saying that if i were to have a test.py file in "sing" folder then inside the test.py i can call linear.py class by saying "sing.ml.regression import linear" ? Commented Feb 28, 2018 at 9:18
  • from what I've read in other questions, yes, you should be able to Commented Feb 28, 2018 at 9:33
  • No i get the following error "ValueError: Attempted relative import in non-package" Commented Feb 28, 2018 at 9:38

2 Answers 2

4
sing
    __init__.py
    -ml
        __init__.py
        -regression
           __init__.py
           linear.py

        -classification
           __init__.py
           logistic.py

And if the working directory of application is not parent folder of sing then you need to register folder 'sing' into PYTHONPATH environment variable.

For importing linear from sing folder you can use relative path:

from ml.regression import linear

and for calling function of linear file you can use:

linear.<*functionname*>(...)
Sign up to request clarification or add additional context in comments.

2 Comments

error is "TypeError: 'module' object is not callable" and the code is import os os.chdir("/Users/Documents/sing"); from ml.regression import Linear obj=Linear()
even if i try "linear.<*functionname*>(...)" and get the same error
3

You need to add a __init__.py files in every folder, so that python interpret the other *.py files (and folder) as packages. A empty file is enough.

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.