OK, prerequisites:
It's my first ever Python project. I used to do some scripting but never anything bigger
So I'm at the very beginning of a learning curve. It's like when you can't kill an ant in Fallout 2 Temple level. On later levels, I was really good in Fall 2:)
Problem:
I can't figure out how to import a module written by me and placed in a different folder
Context:
The project I'm intended to create is meant to do a lot of measures conversions. So I decided to store in DB all data in the same unit system & keep all conversions upon user preferences on a codebase level
In a different folder I decided to store tests. To write the very first one (testing the abovementioned module) I need to import the module, but here is the story begins. I know it's classic, but I'm completely messed with import
Toolkit:
PyCharm Pro (PyCharm 2021.3.1)
Python 3.7 interpreter
macOS 10.15, Intell
Set up:
Settings screenshot provided
Project structure. Folders are marked as Source & Test
I need to import from conversions.py to test_conversions.py
PYTHONPATH settings like this
What do I, for the sake of God, need:
with all the abovementioned, how do I import conversions.py to test_conversions.py or any other place of my project? I read a number of articles and it's getting me anywhere (contradictory, 2.x related, etc). I feel like I need a piece of more foundational info but as well I need a clear walkthrough, a code snippet to import bloody file, I really appreciate any kind of advice
imports are a bit tricky. The issue you have is where your python is looking for packages. I would discourage you to add to your PYTHONPATH a specific project but you could do that locally in your file.
A much easier way is just to launch your test file from the top directory.
In this case your import will just be import conversion.conversion
And then you can launch your test from the root folder with python -m tests.conversion.
In Pycharm you can use the interface to deal with that, see this link. But I like the python -m because it works from anywhere, not only inside Pycharm.
make a class inside a conversion.py, then you can import it from test_conversion.py.
conversion.py
class convert():
def km_to_mm(input):
output = input * 1000000
return output
then import it in test_conversion.py
input = 0.001 # specify your input value
from conversion import convert
converted = convert().a_to_b(input)
converted will have value 1000
make sure you use the same folder. otherwise should use folder name to import. like
import foldername.conversion
from foldername.conversion import convert
I really appreciate all of you who tried to help. I got the problem solved in a very ridiculous manner, below is to someone who might face the same issue in the future.
So, in case you see the next:
You use PyCharm (no idea how other IDEs behave)
You created a module & want to import it into other files of your project
You type import module_name
While you type it, the string looks active and autocomplete even proposes you your module name but as only you finished typing, the import string turns grey, PyCharm throws you a warning saying Unused import statement, yellow bulb next to the import string suggests you delete the import string
--> This does not mean you are not able to import your module, it means you've done it and now can call anything from your module in the code below.
This taught me to pay some more time to read docs before jumping to using anything new and think better about UX in anything I do.
Related
I just started learning Python two weeks ago. I know this question is probably so basic. But please explain to me like I'm 5. I googled "vscode python import not working" etc but all the other cases seem way more complicated than mine.
I'm trying to follow a tutorial where they're introducing me to IDEs and showing that, if the a .py file is in the same directory as your current file, you can import it by typing "import file_name". Except it's not working for me:
It doesn't say there's an error or anything when I just run "import file_name" but says the function in the imported file doesn't exist in the current file if I try to run that.
I did not click on "add blah to PATH" thing when I installed. Could that be the problem?
Some google results say to make sure the debugger uses the correct working directory. Does it pertain to my situation and if it does, how do I do that? Some other results said to add the directory to PYTHONPATH but I didn't understand what that does, also it sounded like that sets up a path for the current file but doesn't establish that that's where I want to pull a file from in general when I type "import file_name" in any file I make from now on.
Please help, both in understanding the problem and fixing it. Thanks.
What I've done so far:
I thought maybe the file name was a keyword so I changed it from area to my_area but it still didn't work. I don't have any other ideas as to how to fix this.
In simple terms, the triangle function is imported as part of the my_area module, and so you'll need to get it from there as my_area.triangle:
import my_area
print(my_area.triangle(4, 5))
Alternatively, you can directly import triangle:
from my_area import triangle
print(triangle(4, 5))
Here's the python module tutorial for more info.
I'm building a large application, a game-engine if you so will. I've tried both relative and absolute imports but nothing seems to be working.
As seen, I'm inside of Sacra/Screen/main.py and want to import something located in Sacra/Audio/PlayAudio.py; The part of which is a "simple" class.
To relate to the "problem", how can one do to import that class? I've looked through the bulk of python docs, real python and many more websites and all I get is the same, that it should be working as of right now.
Note: I've also tried ..Audio.PlayAudio import PlaySound, where PlaySound is the class in PlayAudio.
Another note: It's possbile to import in the Sacra, being a test.py file, with the code, import Audio. Because the init file is configuered.
I am trying to do a bit of math not covered under the numpy or scipy packages. Since I have to do these calculations many times, I thought I'd create my own function in my own mathystuff.py module and import it into my workspace. Easy enough, except python doesn't like importing the function! Here's what I did:
First, I created my file mathystuff.py which is located in my venv/lib/python3.7/site-packages/ folder like the rest of my modules.
import numpy as np
def mathfunction(input1, input2):
#do some math calculations here - lots of np.stuff()
#and some more math calculations here, you get it
return answer
Simple as that. In my main project, I simply call:
from mathystuff import mathfunction
where I'm met with the error cannot import name 'mathfunction' from 'mathystuff' pointing me to the correct location of the .py file. I've done this a million times before and even done this with other modules I've made in the same project, so why would this happen?
There can be many reasons, but according to limited information provided I will go with the ones I think are most possible. (PS I would've commented to ask questions but unfortunately I don't have enough rep).
Check if:
Your virtual env is activated. (I know it sounds silly but it is possible to forget activating venv)
If it's active, then check the location of python by typing which python into terminal (or which python3 if you are running your code with python3). This will return the directory python (eg: path/to/folder/venv/bin/python3). While working on multiple venvs, it's easy to get confused and work on venvA while venvB is active.
If all above checks, go into venv/lib/ directory and confirm that you have only one python directory there. Like venv/lib/python3.8 or venv/lib/python3.7. If, for some reason, there are two (or more) python versions in venv/lib/ then make sure the one you use is the one your module is located in.
These are the most common errors I came across so far.
Is there any conceivable point to reloading these modules immediately after importing them? This is the code that I was reviewing which made me wonder:
import time
import sys
import os
import string
import pp
import numpy
import nrrd
reload(nrrd)
import smooth as sm
reload(sm)
import TensorEval2C as tensPP
reload(tensPP)
import TrackFiber4C as trackPP
reload(trackPP)
import cmpV
reload(cmpV)
import vectors as vects
reload(vects)
Edit: I suggested that this might make the creation of .pyc files more likely, but several people pointed out that this happens this first time, every time.
I note that the standard modules are just imported: it's the other modules that are reloaded. I expect whoever wrote this code wanted to be able to easily reload the whole package (so as to get their latest edits). After putting in all these redundant reload calls, the programmer only had to write
>>> reload(package)
to bring things up to date in the interpreter, instead of having to type
>>> reload(package.nrrd)
>>> reload(package.sm)
>>> reload(package.tensPP)
etc. So please ignore the suggestion that you commit violence against the programmer who wrote this: they are far from the only programmer who's had trouble with reloading of dependencies. Just encourage them to move the reloads to a convenience function.
It is possible that this does cause something to happen; the obvious example is side-effects that happen on import. For instance, a module could log to a file the time and date of every time it is imported.
There is probably no good reason for this, however.
The .pyc files would be created on the first import, so even that's not a very good reason for this.
What's the execution environment for this code? There exists at least one Python web framework that makes different reload decisions than standard python does, which leads to frustration and confusion when you make a change that doesn't 'take'.
So I just met a strange so-called bug. Because this work on my other .py files, but just on this file it suddenly stopped working.
from tuttobelo.management.models import *
The above used to work, but it stopped working all of a sudden, and I had to replace it with the bottom.
from tuttobelo.management.models import Preferences, ProductVariant, UserSeller, ProductOwner, ProductModel, ProductVariant
from tuttobelo.management.models import ProductMeta, ShippingMethods
I know the following is the better way of coding, however ALL of the models mentioned in models are used, so my question is, what possible reasons can wildcard stop working?
The error I got was that the model I was trying to import does not exist, only if I remove the wildcard and import the name of the model could I get it imported properly.
Thanks!
Maybe the models module has an __all__ which does not include what you're looking for. Anyway, from ... import * is never a good idea in production code -- we always meant the import * feature for interactive exploratory use, not production use. Specifically import the module you need -- use that name to qualify names that belong there -- and you'll be vastly happier in the long run!-)
There are some cases in Python where importing with * will not yield anything. In your example, if tuttobelo.management.models is a package (i.e. a directory with an __init__.py) with the files Preferences.py, ProductVariant.py, etc in it, importing with star will not work, unless you already have imported it explicitly somewhere else.
This can be solved by putting in the __init__.py:
__all__ = ['Preferences', 'ProductVariant', 'UserSeller', <etc...> ]
This will make it possible to do import * again, but as noted, that's a horrible coding style for several reasons. One, tools like pyflakes and pylint, and code introspection in your editor, stops working. Secondly, you end up putting a lot of names in the local namespace, which in your code you don't know where they come from, and secondly you can get clashes in names like this.
A better way is to do
from tuttobelo.management import models
And then refer to the other things by models.Preferences, models.ProductVariant etc. This however will not work with the __all__ variable. Instead you need to import the modules from the __init__.py:
import Preferences, ProductVariant, UserSeller, ProductOwner, <etc...>
The drawback of this is that all modules get imported even if you don't use them, which means it will take more memory.