I'm currently using this repository https://github.com/careercup/CtCI-6th-Edition-Python for studying. I want to run the script, but I got an error, for example, Unable to import 'chapter_04.binary_search_tree' when I try to run python3 chapter_04/p09_bst_sequences.py.
Here is the code of chapter_04/p09_bst_sequences.py.
from chapter_04.binary_search_tree import BinarySearchTree
# code continues...
I guess this error is pretty normal because p09_bst_sequences.py file is already at chapter_04 directory. As I guessed, if I rewrite the file like below, I actually can run normally.
from binary_search_tree import BinarySearchTree #changed
# code continues...
However, this repository is pretty big and used by a decent amount of people, so I assume these codes are not mistakes or anything. I think I'm just misunderstanding something. Please tell me about that.
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.
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.
I am working on documenting a piece of code using ReadTheDocs (RTD). Here is the GitHub repo that it builds off, and below it is the current state of the website:
Repo: https://github.com/GluonicPenguin/AutoDQM
RTD: https://autodqm.readthedocs.io/en/latest/index.html
I have run a Sphinx-build locally and checked the build on RTD, and I get no warnings or errors, but the autodqm/dqm.py module does not display the list of functions properly on RTD, i.e. the lists of functions aren't appearing. I had an issue with autodqm/compare_hists.py as well, and I found the issue was I had an import ROOT line at the top (with the other import lines), which when the import is called through a ROOT() function, for some reason this cures the issue and the autodqm/compare_hists.py module displays properly on the website.
I thought a similar fix would work with autodqm/dqm.py but in this case, I have to define near the top the functions
def lxml():
import lxml.html
return lxml.html
def FuturesSession():
from requests_futures.sessions import FuturesSession
return FuturesSession
and I have to remove the class DQMSession. At most I can think that RTD doesn't like handling import functions of the form import <package>.<subpackage>.
I also apologise in advance for all the commits and vague/poor commit messages - I was doing this exhaustively, and developing this locally rather than on GitHub, so I had to keep pushing to test this.
Is there a reason why the setup I currently have doesn't work? Are there other issues that I'm missing? I've never used Sphinx/RTD before, so I'm a novice when it comes to fixing things like this. The reason why I'm not wanting to support the quick fix above with "segregated" import functions is this code needs to be efficient given it is designed to scan through a lot of histograms to perform stats comparisons on, which on that scale efficiency is essential.
Based on Steve's response above, I fixed the issue in AutoDQM RE failing to import modules, so now all the functions display properly on the website. The fixes were:
dqm.py - requests-futures and lxml now requirements specified in setup.py, which are pip installed via
install_requires=['lxml==4.5.2','requests-futures==1.0.0']
compare_hists.py - import ROOT fixed using extension autodoc_mock_imports from autodoc, so there is a line in docs/conf.py autodoc_mock_imports = ["ROOT"]. We need the requirement like this because it is a package with C dependencies, so can't be pip installed like the others.
Thanks for your help!
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.
I have defined a simple SOAP-service in Spyne.
When I run my server like using the run module functionality of python like this:
python -m my_module.service
then everything's fine.
But when I run it from a wrapper script like this:
#!/usr/bin/env python
import my_module.service
sys.exit(my_module.service.main())
then suddenly in the generated WSDL, there will exist a namespace import xmlns:s0="my_module.service" on the<wsdl:definitions …>-tag.
Why is that? Where is that coming from? How can I set this myself in the main() method or prevent it from getting inserted in the first place? I looked throught he code of spyne but couldnt find the relevant lines.
This thread at GitHub explains how and why:
https://github.com/arskom/spyne/issues/233