I recently created and published a python package called ADCT.
Link to package as zip download so you can see what I mean: https://pypi.org/project/ADCT/#modal-close
I went ahead and published it and I was able to pip install it on my local machine. In the package, there is an object itself called ADCT. What code snippet, other than "import ADCT" do I run to call the object ADCT? Do I have to rename the object to something else since it could be a collision error? I know this is embarrassing since its my package but any help would be appreciated.
The package and the object will likely to end up in different namespaces. Example:
from ADCT import DataObj
adct_instance = DataObj.ADCT()
Another way to deal with duplicated names (not very helpful in this case, just for the reference) is to use import .. as, e.g.:
import ADCT as ADCT_package
adct_instance = ADCT_package.DataObj.ADCT()
Related
I have quite a number of different file which I want to use to create an API. The files are :
app.py -- main file
utils.py -- utilities file
recorder.py
consts.py
submitter.py
All of these files have a dependency on one another. However, when I try to import them in a particular file ( for ex - importing consts in recorder.py, I am getting error saying The module consts is not found.
I am importing it using :
from .consts import consts
Can someone tell me what am I doing wrong here, and how to solve this issue.
If i import it in the main app.py, it doesn't give any error. but it does when I want to access any consts in other files.
Thank you in advance
EDIT : Here is the folder structure :
When you say they are interdependent, that may be your issue. You cannot have two files that depend directly on one another with out some hacky solutions as youll run into the problem of importing one that tries to import the importer which tries to import the importee and so on forever.
Edit: i misunderstood how imports work, the problem comes from:
"If you import X from your main program, Python will load the code for
X and execute it. When Python reaches the import Y statement, it loads
the code for Y, and starts executing it instead.
At this time, Python has installed module objects for both X and Y in
sys.modules. But X doesn’t contain anything yet; the def spam
statement hasn’t been executed."
As stated in the link i included at the bottom of this response. The link also gives some possible solutions like changing when you import the different modules.
What we really need is to see the code for the files to understand how you are importing everything
this link should help you in your desire for circular dependency.
So I am pretty new with Python. I've been working on running with a code similar to one I hope to build myself (so a reference code). Aside from some bugs I need to work out with invalid syntax, all seems to work except for one issue with one particular .py file I have.
My structure is this:
MoodForecasting -> eval -> nsga_two.py
I do have _init_.py in eval folder though, so I'm not sure why this block of code isn't working.
I am trying to load one particular fucntion from it, so the structure should look like this
from nsga_two import PatientProblem
Unfortunately, I keep getting the error ModuleNotFoundError: No module named 'nsga_two'.
I checked nsga_two.py itself and found that it couldn't load inspyred. I went in and was able to fix this. So, nsga_two.py runs fine on its own. However, I cannot import it into the main script I will be working with.
Some extra details: I am working with the IDE Spyder with Python Custom Version 3.7.9.
I'm not sure if it is an issue with Spyder or just how I am loading in my working directory. (Most of my coding experience is in MatLab and R so having an IDE similar to RStudio and MatLab is the reason I chose to work in Spyder)
Edit:
I got a syntax error when using from eval import nsga_two.PatientProblem. Python didn't like the period. So, I instead tried it with no period. I got the error cannot import name 'nsga_twoPatientProblem' from 'eval' (C:\Users\name\Desktop\MoodForecasting-master\MoodForecasting-master\eval\__init__.py). I don't know why. But doing from eval import nsga_two works. nsga_two.py only consists of PatientProblem. This solve should be ok for this purpose. I'm just not sure why this could be happening.
Suppose your structure is like:
MoodForecasting-master/
main.py
eval/
__init__.py
nsga_two.py
When you run the main script to import something, the directory of that script is added to the module search path sys.path, .../MoodForecasting-master/ in this case. from nsga_two import PatientProblem raised ModuleNotFoundError because nsga_two.py is not in that directory.
As Iguananaut said, from eval import nsga_two.PatientProblem in the first comment has never been a valid statement. The valid ways of doing so are:
import by from eval import nsga_two and use as nsga_two.PatientProblem().
import by from eval.nsga_two import PatientProblem and use as PatientProblem() directly.
Module search starts from .../MoodForecasting-master/, first option go to .../MoodForecasting-master/eval/ to find nsga_two.py, second option go to .../MoodForecasting-master/eval/nsga.py to find attribute named PatientProblem.
The correct syntax would be:
from package.module import function
so:
from eval.nsga_two import PatientProblem
I have the following project structure:
MainScript.py
ExampleFolder
├ MainImport.py
└ SecondaryImport.py
MainScript.py: import ExampleFolder.MainImport
MainImport.py: Import SecondaryImport
When I try to run MainImport.py it gets no errors, but when I try to run MainScript.py, I get an import error that says No module named 'SecondaryImport'.
My question is simple - is there any way that I can import only MainImport.py from MainScript.py without getting this error, and importing SecondaryImport.py? Thanks in advance!
I have also tried adding a blank file named __init__.py to the ExampleFolder, but the error still appears. I also read Python's official documentation, but I could not find the problem. Am I missing something? (:
I think using the statement import ExampleFolder.SecondaryImport would work.
If it does, the error might be happening because as mentioned in docs, import statements will usually start searching your main project directory where the python interpreter was called if your module is not in python itself.
Another way would be to use relative import statement like this:
import .secondaryimport in order to tell the python interpreter to look in the current directory. Hope this helps!
Taking a look at these links will help, I think (It helped me when I was stuck in a similar problem):
https://docs.python.org/3/library/sys.html#sys.path
https://realpython.com/absolute-vs-relative-python-imports/
I have also tried adding a blank file named __init__.py to the ExampleFolder
That's the way - you're creating a Python package from a directory that way. And with packages you have got namespace directory.file where file is a Python file also known as module in Python world.
Then you can do from mainscript.py:
from examplefolder import mainimport
For importing inside package you may use the following syntax inside mainscript.py:
import secondaryimport
and use it in that mainscript.py as:
sevondaryimport.SomeClass()
or you may just do:
from secondaryimport import SomeClass
and use it like:
SomeClass()
Btw, use lowercase in all the cases except classes names - only they should have CamelCase names.
i'm stucked at a point and i can't progress, sorry for this silly question. I searched a lot for that but i couldn't know what i am missing. Please help me.
I studied modules and classes in python. Now i want to make some operations using python and apt. I'm studying from : http://apt.alioth.debian.org/python-apt-doc/library/apt.cache.html
However, i couldn't understand, the module is apt.cache, as shown in the top of the page. I expected that object should be created by writing apt.cache.Cache(), but object is created by writing apt.Cache(), as shown below. Why?
import apt
import apt.progress
# First of all, open the cache
cache = apt.Cache()
# Now, lets update the package list
cache.update()
# We need to re-open the cache because it needs to read the package list
cache.open(None)
# Now we can do the same as 'apt-get upgrade' does
cache.upgrade()
# or we can play 'apt-get dist-upgrade'
cache.upgrade(True)
# Q: Why does nothing happen?
# A: You forgot to call commit()!
cache.commit(apt.progress.TextFetchProgress(),
apt.progress.InstallProgress())
Second similar question is about below code, Cache class is imported from module apt.cache. I expected that object would be created by writing apt.cache.Cache(), but it is created by writing apt.Cache(). Why?
>>> from apt.cache import FilteredCache, Cache, MarkedChangesFilter
>>> cache = apt.Cache()
>>> changed = apt.FilteredCache(cache)
>>> changed.set_filter(MarkedChangesFilter())
>>> print len(changed) == len(cache.get_changes()) # Both need to have same length
True
Thanks in advance
If you look at the __init__.py file of the apt package, you see the line:
__all__ = ['Cache', 'Cdrom', 'Package']
The python documentation says:
The import statement uses the following convention: if a package’s
__ init__.py code defines a list named all, it is taken to be the list of module names that should be imported when from package import
* is encountered.
That's the reason why you can use apt.Cache()
For the second part of your question you can import directly the Cache class with
from apt.cache import Cache
cache = Cache()
You can also import the Cache class with
import apt
cache = apt.Cache() //because of the __all__ variable in __init__.py
cache = apt.cache.Cache() //because it's a fully qualified name
I am new to python and trying to get a feel for python fuse with this tutorial. I installed pythonfuse with pip. I installed os x fuse by downloading a dmg and installing on os x. When I run this line of code from fuse import FUSE, FuseOSError, Operations from the tutorial I see this:
akh2103$ python myfuse.py
Traceback (most recent call last):
File "myfuse.py", line 10, in <module>
from fuse import FUSE, FuseOSError, Operations
ImportError: cannot import name FUSE
It seems like it can't find the fuse package, can't find the python fuse package or can't find the FUSE, FuseOSError and Operations methods within the package. Which one is it? When I type import fuse where does Python go to look for the fuse package? I'm used to class paths in java: is there a python equivalent? I'm very new to python. How do I begin to debug this.
It looks in /Library/Python/<version>/site-packages.
You may be having multiple versions which may be the cause of the problem.
Find out where pip installed fuse.
You can use the PYTHONPATH environment variable to add additional folders.
The fuse module was found (otherwise you would see "No module named fuse"). The error you got means that "FUSE" symbol is not found in the module fuse.
My guess is there are several python bindings for FUSE and you are probably looking at a tutorial for a different module than the one you are loading. The other alternative is some drastic changes in the library between different versions.
If you want to see all the symbols exported by a module, use dir():
import fuse
dir(fuse)
Say this was your directory structure:
myapp/
firstpackage/
__init__.py
firstmodule.py
secondpackage/
__init__.py
secondmodule.py
__init__.py
myfirstapp.py
firstmodule.py
def first_function(data):
return data
def second_function(data):
return data
Now let's say we're working from :mod:`myfirstapp`.
If we wanted to access :func:`first_function`, we'd import like:
from myapp.firstpackage.firstmodule import first_function
print first_function('foo')
:mod:`__init__` in 'firstpackage' directory allows :mod:`firstmodule` to be accessed from outside of it's directory. The inclusion of :file:`__init__.py` within a directory makes that directory a Python package.
However, it's better practice to import the whole module like:
import myapp.firstpackage.firstmodule as firstmodule
print firstmodule.first_function('foo')
print firstmodule.second_function('bar')
Another method would be:
from myapp.firstpackage import firstmodule
print firstmodule.second_function('foo')
That way everything is accessible from within your module, and better for readability.
That being said, the :exc:`ImportError` you're receiving is because 'FUSE' does not exist in :mod:`fuse`, whether it's data, class or a function.
Open fuse.py and do a search for 'FUSE' and see if anything comes up. Look for:
def FUSE(): ...
class FUSE(..): ...
FUSE = ...
I know the whole package/module lesson was off topic from your question, but you said you were new, so I thought I'd elaborate :P