Trouble accessing function from imported module in the same directory - python

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.

Related

Unused import statement: classic problem while importing own module

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.

Python unable to import package in the package

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.

Is it possible to insert import statements with jedi-vim?

I've just started looking at the Vim jedi plugin, and it seems pretty impressive. One feature of some of the Java IDEs I've used is the ability to automatically add required imports. Can Jedi do that? For example, if I enter a line such as
arg1 = sys.argv[1]
and then invoke some Jedi command, is it possible for the plugin to automatically insert an import sys line at the top of the source file (if sys is not already being imported)?
I've looked through the Jedi help, and can't see anything like this - but it's possible I missed something. Alternatively, is there another Vim plugin that would do this? (It needs a certain level of understanding of Python syntax to get it right, which is why I looked to Jedi to be able to do it).
Currently Jedi doesn't do refactoringing. This includes import additions. There's an issue for the whole subject: https://github.com/davidhalter/jedi/issues/667.
It's not that easy to implement this command with good performance. However any help is appreciated. :)
FIY, I've defined a generic import feature that can be used on demand in lh-dev. I use it from my C&C++ suite, and from my snippet engine (mu-template).
So far I don't parse anything to add the missing import/include statements. This part would be complex as Dave said. Instead my snippets know which files need to be imported/included and import/include them if not already imported/included.
It's far from being perfect, but it's a start. mu-template provides a hook to do stuff at the start of the file after the snippet has been expanded, this is where I call lh-dev function. If other snippet engines provide similar hooks, you should be able to call lh#dev#import#add() from your snippets.
Here a proof of concept snippet for Python (I seldom program in Python, and don't have many snippets for it): https://github.com/LucHermitte/mu-template/blob/master/after/template/python/path-exists.template

Questions regarding wormy source code?

so I recently started looking into GUIs and I'm looking at a source code for the game wormy which can be found: here. I just have a few questions regarding this source code.
What does the sys module do in this code? I know that the sys module provides information about constants, functions and methods of the Python interpreter (taken from a website), but in this source code the only thing that the sys module is actually doing is being imported and then terminated when the game is closed? So I'm a bit confused about that.
In addition, I am wondering on how I can change the squares to look like circles instead? I tried changing the module functions (Rect and draw.rect) to draw.circle but an error keeps popping up. Any suggestions? Thanks!
When using pygame.draw.circle(), it will take different arguments than rect(). Look at the documentation here. Post your code and your error message for better help.

Spyder - UMD has deleted: module

I have been fooling around for about a month with python now and something is bothering me.
I use the python(x,y) toolkit, which comes with the neat Spyder IDE.
My question concerns the UMD (User module deleter) of Spyder.
I found this graphics module on the internet, which helps one to do some simple graphic stuff in a python script (as far as I understand).
It is not like i'm stuck, but when I execute the folowing code:
import pylab as p
import graphics as g
window = g.GraphWin("tryout", 600, 600)
window.close()
print p.sqrt(4)
The output is:
>>>runfile(r'C:\some\folders\tryout.py', wdir=r'C:\some\folders')
>>>UMD has deleted: graphics
>>>2.0
line 1 is obviously o.k. and so is line 3, but I don't get line 2.
Also, the provoked window flashes in and out of the screen, as it should.
Line 2 doesn't seem to do any harm, and i can perfectly rerun the file as many times as I wan't, but I want to know where it is comming from.
AFAIK UMD forces the interpreter to reload a module everytime a script is run.
Does the displayed message mean that 'it' has deleted the references to the module, because it isn't used anymore, or is it something else? Or does it mean something is wrong, and will it 'hurt' my code should I add more afterwards?
Note: first question, so please comment the crap out of it to help me improve my asking skills.
EDIT: i tried shifting around the test line print p.sqrt(4), and found out that it doesn't matter where I put it. If its the first line after importing the modules, it still raisses the message before showing sqrt(4)
Short Answer:
Perhaps deleted is not the best word in the message you mention. It should be reloaded, which is what UMD is really doing and because is way less confusing. I'll fill an issue for this in our issue tracker.
Long answer:
UMD reloads not only your script but also all the local modules it depends on. By local I mean modules outside your Python installation and over which you have writing permissions.
The idea is that next to your script, perhaps you have developed a library of auxiliary functions to go with it. So you most probably want to reload that library too, so that any changes to it are reflected at run time.
I know this is not your case, so if you want to remove that message, you can go to:
Tools > Preferences > Console > Advanced settings > User Module Deleter
and deactivate the option
Show reloaded modules list

Categories