What is the best way to access a Python file from both within the same folder and from outside of it

I am facing an issue with the file hierarchy in my project. Here is how the files are structured:
folder
|
classes
|
class1.py
class2.py
test_class2.py
main.py
Apologies, I am unable to format text properly. The main.py and classes folder exist in the same directory.
In main.py, there is an import statement that reads

from classes.class2 import someclass
.
The class2.py file imports from class1.py using
from classes.class1 import someanotherclass
.
This setup works seamlessly when running main.py. However, a challenge arises when trying to test class2.py within the 'classes' folder as it requires changing the import statement to
from class1.py import someanotherclass
. Is there a more universal way to handle these imports in order for both main.py and class2.py to function correctly?

Answer №1

If you are searching for a way to utilize relative imports in Python, then relative imports may be what you need. You can find more information about them at the following link: https://docs.python.org/3/reference/import.html#package-relative-imports

Consider the example below:

main.py:
from classes.class2 import someclass

classes/class2.py:

from .class1 import someanotherclass

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Python selenium element search yields no results

I am having trouble retrieving titles that include '募集说明书' using the provided code. Despite no errors being returned, the search results are coming back empty. driver.get('http://www.szse.cn/disclosure/bond/notice/index.html') ...

Save the Python version for future rebuilding of the virtual environment

In order to remember the package requirements for future installation in a Python virtual environment, many people use the following convention: first run pip freeze > requirements.txt, and then install the packages using pip install -r requirements.txt ...

Issue with graphviz software, encountering ExecutableNotFound error

Having trouble installing graphviz in PyCharm on my Windows system. I've already added the graphviz library to my PyCharm project, but I keep getting an error when trying to execute dot.render: graphviz.backend.execute.ExecutableNotFound: failed to e ...

Converting strings in rows of a Pandas Dataframe into characters separated by commas

I am dealing with a dataframe that has sequence data in each row, formatted like this. MKEYGEDLK My goal is to process the sequence strings in each row to have them presented in this format: [M, K, E, Y, G, E, D, L, K] I attempted the following code: get ...

Encoding a list of categories as strings for creating Pandas dummies

I am working with a dataframe structured like this: id amenities ... 1 "TV,Internet,Shower,..." ... 2 "TV,Hot tub,Internet,..." ... 3 "Internet,Heating,Shower..." ... ... My goal is to split the string by comm ...

What is the process for executing tasks from a different server with Celery?

Two of my Python applications are utilizing Celery and connected to the same broker. Instance A contains all of my @tasks, but I need to run these tasks from Instance B. Unfortunately, I cannot perform standard imports as the tasks do not exist on Instanc ...

Tips for improving the appearance of a seaborn heatmap:

Currently, I am generating a correlation heatmap using the code below: plt.figure(figsize = (20,8)) sns.heatmap(df.corr(),annot=True, cmap = 'coolwarm') Upon running the code, the generated plot looks like this: https://i.stack.imgur.com/XfKpQ ...

Has Flask already sanitized the request data?

Is it necessary to ensure proper handling of user-generated data (such as cookie values, variable segments in URLs, and query arguments), or can Flask sanitize and escape input automatically before passing it to a function like test(input_data)? ...

Python Code for Finding the Minimum Depth of a Binary Tree is Ineffective

I am currently working on a challenging problem that involves finding the minimum depth of a binary tree. Despite my efforts, I am struggling to identify the mistake in my code. Any suggestions or guidance would be greatly appreciated. # Definition for a ...

Python3 selenium can be utilized to extract the profile image link from a Facebook account

How can I fetch the Facebook profile image link using Python3 and Selenium? Upon inspecting the profile photo element, the following information is obtained: <image style="height: 168px; width: 168px;" x="0" y="0" height="100%" preserveAspectRatio="xM ...

Using Selenium with Python, ensure that after clicking a button, the program waits for all newly loaded elements, regardless of their attributes, to fully load

Is there a way to wait for all newly appearing elements on the screen to fully load after clicking a particular button? While I understand that the presence_of_elements_located function can be used to wait for specific elements, how can I ensure that all ...

Tips for generating a three-dimensional visualization of a deep learning model

Is it possible to generate a 3D representation of a deep learning network in .png or .jpeg format? Currently, Keras only provides a two-dimensional model plotting utility, showing the number of layers and basic properties of each layer (see image link b ...

What is the best way to transfer form data stored locally to a Django view and then store it in the database?

Is there a way to transfer form data from an offline website to a Django view for database storage? I want to fill out a form, save it in local storage, and then upload the data to the database when I reconnect to the internet. Is there a tutorial or can ...

Unable to interact with an input field in Selenium due to it not being concealed within a shadow DOM or iframe

Currently, I am in the process of scraping data from the website . My journey with automation using Selenium has hit a roadblock as I struggle to click on the input field for entering the city name (referred to as "city" in the code). I've already i ...

Tips on modifying the maxlength attributes for all "field answer" class elements

Looking for some help with adjusting the "maxlength" attribute in a class called "field answer." The current maxlength is set to 250, but I need it changed to 9999. Can someone guide me through this process? <div class="field answer"> &l ...

Filtering Django ORM for the sum of multiple different related objects

I am in a situation where I have the following models: class Developer(models.Model): name = models.CharField(max_length=100) class Skill(models.Model): code = models.CharField(max_length=30) class Experience(models.Model): date_from = models ...

Acquire the content of an interactive website with Python without using the onclick event

I am looking to extract the content of a dynamically generated website after clicking on a specific link. The link is structured as follows: <a onclick="function(); return false" href="#">Link</a> This setup prevents me from directly accessin ...

Exporting table data to a CSV file using Selenium and Python

My goal is to automate the process of extracting my transcript data and saving it to a CSV file using Python with Selenium. I've managed to automate reaching the table page, however, I am facing an issue where only the first row of the table is displa ...

What is causing the error when attempting to install xlwings via the terminal?

Recently, I've started learning Python and embarked on a personal project. I wanted to install xlwings to execute Python code from Excel but I encountered issues with the installation process. Here's what I attempted: C:\Users\Rafi> ...

Time Frame for querying Facebook Graph API for post-level data

I'm currently developing a tool for my company that is designed to extract data from our Facebook posts. Unfortunately, the tool hasn't been functioning properly recently, so I need to retrieve all the historical data from June to November 2018. ...