ValueError: Attempted relative import beyond toplevel package - python

I have the following two files:
/quiz/quiz/views.py
and
/quiz/static/questions.html
I would like to import questions.html into views.py.
So I'm trying to do this:
from ..static import *
However, I'm getting:
ValueError: Attempted relative import beyond toplevel package

As Sebastian Wozny answered, you can not import such files in python.
Try to write module that parse useful data from html file then import that module.

Related

Python master import file

I have several scripts in a project folder, most of which use the same handful of standard libraries and modules. Instead of having to reiterate in every single script
import pandas as pd
import numpy as np
import datetime
import re
etc
etc
is it possible for me to place all import statements in a masterImports.py file and simply import masterImports at the top of each script ?
Yes you can.
So the basic idea is to import all the libraries in one file. Then import that file.
An example:
masterImports.py
import pandas as pd
import numpy as np
import datetime
import re
etc
etc
otherFile.py
import masterImports as mi
print(mi.datetime.datetime(2021,7,20))
Or you could use wildcard imports -
from masterImports import * # OR from masterImports import important_package
print(datetime.datetime(2021,7,20))
Do not use wildcard asterix imports because there can be name clashes
Try this, and you will see that there is no error
It's possible, although not really the done thing
To use it, you'd need to do, at the top of each script:
from master_imports import *

Calling a function in a different python file using Google Colab?

I'm working on a project for which I need to call functions from several python files to use in one main program. All of the programs in question are notebooks in the same directory in Google Colab. I am having trouble being able to call the functions I need and I haven't been able to find a solution that works. I've tried simply from InterpolateData import LoadandInterp where InterpolateData is the file name where the function LoadandInterp is stored. This is what I currently have:
from google.colab import files
import sys
sys.path.append( "/content/drive/My Drive/Colab Notebooks")
import InterpolateData
import numpy as np
import pandas as pd
from scipy.interpolate import griddata
#get, normalize and interpolate data
#SpectralHighData
temperatureList=np.arange(25.0,46.0,1.0)
interpList=np.arange(25.0,45.0,0.1)
pathBefore="/content/drive/My Drive/Colab Notebooks/Original Data/High Temperatures/Spectral_high/CdTe Spectra Interpolated "
pathAfter="C.csv"
interpolated=InterpolateData.LoadandInterp(temperatureList, interpList, pathBefore, pathAfter)
Everything that I've tried returns an error along the lines of ModuleNotFoundError: No module named 'InterpolateData'
Does anyone know a way I can get this to work? Surely, there is a way?
Edit: Before the previous code, I have code to mount my google drive and change the directory to where the files are stored. It looks like this:
from google.colab import drive
drive.mount('/content/drive', force_remount=True)
!ls "/content/drive/My Drive/Colab Notebooks"
%cd "/content/drive/My Drive/Colab Notebooks"
For anyone who stumbles across this in the future: I was able to find a solution, eventually.
In order to access another program, the program file must be a .py file and it must be in a folder that also contains a file called _init_.py. The _init_.py can be completely empty.
Once you have the files set up, change your directory to the folder with your 'module' program(s) using %cd 'filepath'. You can then import your module using import filename. The functions in your other program are now accessible through filename.function.

Is this the correct way to open a .csv file in Python?

I've so many different ways and it is still saying file not found
I'm running the code in a Jupyter Notebook.
I'd rather run the file from wherever it is. Here is the infomation for its location
Have I generated the correct code (below is the code).
import numpy
numpy.loadtxt(fname='C:\Desktop\swc-python\data\inflammation-01.csv', delimiter=',')
Also tried this but it did not work:
import numpy
numpy.fname = ('C:\Desktop\swc-python\data\small-01.csv')
openfname = open(fname,'r')
Also, an you save a Jupyter notebook in the same directory as the infomation.
these are some examples with pandas, and os, maybe they could help
they use slash, not backward slash (this option, or the option below)
# import pandas as pd
pd.read_csv("C:/Users/<Insert your user>/Desktop/code/Exercise Files/us_baby_names.csv")
or
(option below), change the current directory,
# import os and pandas library
import os
import pandas as pd
# show current working directory, change it, show it again
os.getcwd()
os.chdir('C:/Users/<Insert your user>/Desktop/code/Exercise Files/')
os.getcwd()
pd.read_csv("us_baby_names.csv")

Is it possible to reuse import code in Python?

There are several imports that are common between some files in my project. I would like to reuse this code, concentrating it in a unique file and have just one import in the other files. Is it possible?
Or is there another way not to replicate the desired import list in multiple files?
Yes its possible. You can create a Python file with imports and then import that Python file in your code.
For Eg:
ImportFile.py
import pandas as pd
import numpy as np
import os
MainCode.py:
from ImportFile import *
#Here you can use pd,np,os and complete your code
OR
from ImportFile import pd,np
#And then use pd and np

Python and importing sub-modules - Pandas example

I was trying to use the pandas.tseries.holiday module within pandas, but for some reason it was not showing up. I tried the following:
import pandas as pd
pd.tseries.<TAB>
This does give me a list of options, but holiday was among them. According to the documentation of holiday, it should be as simple as what I tried above.
This was on my system's Python. I tried it in Jupyter using Anaconda, then in Terminal and even in Emacs, but it was never found. So it must be a general design choice that I am unaware of. I have looked for clues, but all information I find tells me that importing a whole module or parts of it is a subjective choice - example: readability versus name-space pollution etc.
Eventually I just tried importing it manually (the next step would have been downloading the actual holiday file from the pandas git repository.
So I did:
from pandas.tseries import holiday # no error
holiday.<TAB>
... and I am shown all the stuff I need - great!
But what is going on here??
Looking at the actual code of holidays.py does not give me any hint as to why the file/module is not imported when I simply import pandas using the statements above.
Edit
Here is some additional information, showing how holiday is not found within pandas.tseries itself, but can be imported and used explicitly:
>>> import pandas as pd
>>> pd.tseries.holiday.USFederalHolidayCalendar()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'pandas.tseries' has no attribute 'holiday'
>>> from pandas.tseries import holiday
>>> holiday.USFederalHolidayCalendar()
<pandas.tseries.holiday.USFederalHolidayCalendar object at 0x7f3b18dc7fd0>
Using simply import pandas as pd does not automatically import all sub-modules of the pandas library (as pointed out by TomAugspurger in the comments above).
This is because the __init.py__ of the pandas library does not import the everything including the holiday sub-module module.
Either adapt the __init__.py file to do so, or be aware that one must explicitly import certain sub-modules of the pandas library!

Categories