Beginner Python Import Module - python

Beginner question. I am trying to import a python script "feedparser.py" into another python script "ps5.py". Both scripts reside in the same folder "MIT_OCW" on my desktop. When I try to import "feedparser.py" into "ps5.py" I get an import error ("ImportError: No module named feedparser"). What steps should I take to diagnose the error (I am new to programming)? Thanks.

This is code from ps5.py
import feedparser
import string
import time
These are the paths of feedparser.py and ps5.py
~/Desktop/MIT_OCW/problem set 5/ps5.py
~/Desktop/MIT_OCW/problem set 5/feedparser.py
Originally when I ran the code I got back the "ImportError: No module named feedparser". However, I just tried running it again (without having changed anything) and it worked. I am happy it works but frustrated that I don't know why it didn't work in the first place. Anyway, thanks for your help.

The name of the module is the filename without the extension. So to import feedparser.py, you would use:
import feedparser
To use something from feedparser, say a function f, you would call it from your module like:
feedparser.f()

Actually, I agree with munk and Rushy Panchalon this. You should do the following:
import feedparser as feed
(or any other name)
You wouldn't need to import string or time unless needed for your code.

I agree with #munk, the file extension is not needed when you import a module.
import feedparser
or
import feedparser as f
from feedparser import * #not recommended at all
from feedparser import func1, func2 #where func1 and func2 are functions in your module
Anything will work for Python3 at least.

No need to add the file extension.
import feedparser
Or if you are going to refer the functions/classes in the file very frequently and you arenkt going to redefine the functions/classes in the file:
from feedparser import *
Using the second method will allow you to acces the objects defined in the feedparser file without having to add ‘feedparser.’ before the object name. If that doesn’t work try this(replace text in the curly brackets with the appropriate words):
from {name of the directory in which the feedparser file is located}.feedparser import *
Thank You! Hope that works!

Related

how do i correctly import a package in python?

Hello everyone im currently learning python and i im having some problems importing modules and packages. Actually i think is more of a problem with vscode.
i have this package called "paquete" with a module (funciones) that i want to import to my "main" with some fuctions in it to test if it all works correctly but i still getting "emphasized items and unresolved-import" warnings.
but for some reason it works just fine.
is more of a annoying thing.
EDIT:
module with the function "funcion"
the warning that appears in the main folder "prueba" is "emphasized items"
i tried what u guys told me to do but it stills shows the warnings
As you are trying to import a specific function from module in python
You should use in this manner:
from paquete import funciones
If you want to import full module then use:
import paquete
I can't tell whats in the funciones file. But normally this yellow import lines are telling you that you import functions, which you dont use.
Try this instead if you only want
funcion
to be imported.
from paquete.funcions import funcion
This is also better because you import only the functions you need, not all of the functions you declared in the other file. Also all imports of the other file will be loaded into your file if you import with an asterix.
The issue is you are doing all of this from within a directory named prueba. If you changed the import to from prueba.paquete.funciones import * it should work after you add a __init__.py file to your prueba directory. The other option is to use a relative import: from .paquete.funciones import *.
But do note that using import * is strongly discouraged when you are not working within the REPL. It's much better to import to the module and then reference things off the module, e.g. from prueba.paquete import funciones, from .paquete import funciones, or import prueba.paquete.funciones. That way you know exactly where things in your code came from without having to read the top of your file.
pip3 intall "name"
Use Pycharm, rather than Vscode

Name re is not defined although re is imported in module and in main code

I'm working on a Jupyter Notebook for my master's thesis and I'd like to keep it clean. I use a lot of functions to assign categories to groups of data.
Therefore, I've decided to put all those functions in a functions.py module which I import at the start of my notebook. My notebook has the following imports:
import sys
sys.path.append('../src/') # ugly hack to be able to import the functions module
import re
import numpy as np
import pandas as pd
import seaborn as sns
import functions as fn
One of my functions uses the "re" module for matching strings with regex. When I called the said function I get NameError: ("name 're' is not defined", 'occurred at index 0') so I figured I had to import re at the beginning of my functions.py file. This didn't change anything. So I even tried to put import re in the function body, but it wouldn't work either.
I have absolutely no idea why re doesn't work despite trying to import it everywhere.
Note: my functions worked correctly when I was defining and using them from the notebook so I know for certain it's not a bug in my function.
Solved my own issue, the answer is stupidly simple: Jupyter doesn't take into account any edits to an imported module even if you reimport it. If you make any changes to a module you have to shut down the kernel and restart it, import again and the edits will work.
In my particular case I had added import re to my functions.py but Jupyter didn't take it into account until I restarted the kernel.
In a notebook, you can use the importlib library and call importlib.reload(module) instead of restarting the kernel

Python: NameError when trying to use "re" inside a function

I have a script called main_plotter.py that looks like this:
import re
import numbs
numbs.getSquares("file.csv")
numbs.py is the file that I'm importing from. It looks like this:
def getSquares(sqfile):
infile=sqfile
base_name = re.split(".csv", infile)[0]
print (base_name)
When I run main_plotter.py, I get NameError: name 're' is not defined.
Why is this happening? I tried adding global re before the import re statement, but that doesn't help either. Aren't the import statements supposed to be global anyway? Any help appreciated!
PS. the code runs as expected if I import re inside the numbs.py file.
"Global" in Python means "module namespace". Any import re happens exactly there -- module-by-module; there intentionally does not exist any wider scope, which ensures that the content of any Python module can be understood by reading only that module (unlike Ruby, where to know the context in which code is run you need to read every module that was ever loaded by the same interpreter).
If you want to use the re module in numbs.py, you should have a separate import re inside that file. This doesn't reload the module from disk, but just adds a namespace entry pointing to the already-cached instance that was loaded on first reference.

Linking Python Files Assistance

I understand how to actually link python files, however, i don't understand how to get variable's from these linked files. I've tried to grab them and I keep getting NameError.
How do I go about doing this? The reason i want to link files is to simply neaten up my script and not make it 10000000000 lines long. Also, in the imported python script, do i have to import everything again? Another question, do i use the self function when using another scripts functions?
ie;
Main Script:
import sys, os
import importedpyfile
Imported Py File
import sys, os
I understand how to actually link python files, however, i don't
understand how to get variable's from these linked files. I've tried
to grab them and I keep getting NameError.
How are you doing that? Post more code. For instance, the following works:
file1.py
#!/usr/bin/env python
from file2 import file2_func, file2_variable
file2_func()
print file2_variable
file2.py:
#!/usr/bin/env python
file2_variable = "I'm a variable!"
def file2_func():
print "Hello World!"
Also, in the imported python script, do i have to import everything
again?
Nope, modules should be imported when the python interpreter reads that file.
Another question, do i use the self function when using another
scripts functions?
Nope, that's usually to access class members. See python self explained.
There is also more than one way to import files. See the other answer for some explanations.
I think what you are trying to ask is how to get access to global vars from on .py file without having to deal with namespaces.
In your main script, replace the call to import importedpyfile to say this instead
from importedpyfile import *
Ideally, you keep the code the way you have it. But instead, just reference those global vars with the importedpyfile namespace.
e.g.
import importedpyfile
importedpyfile.MyFunction() # calls "MyFunction" that is defined in importedpyfile.py
Python modules are not "linked" in the sense of C/C++ linking libraries into an executable. A Python import operation creates a name that refers to the imported module; without this name there is no (direct) way to access another module.

Import a module into a module, can't explain what i'm trying to do

So, the following is an example. Here's a module (called feedy.py) in let's say, the core directory:
import feedparser
feed = feedparser.parse("http://site.com/feed")
[...]
A bad example, but anyway: my problem is in the main script (parent dir), I have to do
import feedparser
as well as
from core import feedy
However, is there a way to eliminate the need to import feedparser, since it's already imported in feedy.py?
Hope you understand,
Fike.
In principle, yes. However, it's not usually a good idea.
When you import a module, you effectively declare a local variable which is a reference to that module. So in feedy you have an object called feedparser, which happens to be the module feedparser, although you could at any time reassign it to be any other Python object.
When you import feedy, you can refer to any of feedy's exported variables as feedy.name. So in this case, feedy.feedparser is the module feedparser.
However, if you change the way feedy is implemented, so that it doesn't import (or export) feedparser, this will break your main script. In general you don't want to export everything you have defined, although it's fine for a quick hack.

Categories