I am making a React app.
I am using some Python code to automate a few things.
But currently I am duplicating some Python code across separate components. I would like to avoid this, and place all my common python functions in a helper class, accessible from any component.
Currently the project structure (relevant to this question) looks like this:
/src
/reducers
/localData
Helpers.py
txt_to_jsx_converter.py
This is what my Helpers.py
file looks like.
import argparse
import os
from openai import OpenAI
from dotenv import load_dotenv
from pathlib import Path
class Helpers:
def read_file(filepath):
"""Read a file...
Args:
filepath (string): path to file that I want to read contents of
"""
with open(filepath, "r", encoding="utf-8") as f:
file_content = f.read()
return file_content
def get_api_key(name, root_project):
"""Get api key
Args:
name (string): name that I assigned it in the .env file
root_project (string): root project directory
"""
# name of file where my API keys are stored...
env = '.env.local'
# load the file...
load_dotenv(Path(f"{root_project}/{env}"))
# now we retrieve the API key we want...
API_KEY = os.getenv(name)
return API_KEY
And I can use this in my txt_to_jsx_converter.py
file fine, because they are in the same directory. For example:
from Helpers import Helpers
API_KEY = Helpers.get_api_key(name="OPENAI_API_KEY")
client = OpenAI(api_key=API_KEY)
Attempt to optimise v1:
I literally just dragged the
Helpers.py
file, into a new directory I calledpythonhelpers
I created at root level. The project structure looks like this now:/pythonhelpers Helpers.py /src ...
In doing this, the import statement in my
txt_to_jsx_converter.py
script updated automatically, it changed it to this:from pythonhelpers.Helpers import Helpers
Somehow, when I hover over
pythonhelpers
VS Code recognises it as a module:Despite that, I get the following error:
from pythonhelpers.Helpers import Helpers ModuleNotFoundError: No module named 'pythonhelpers'
Contradictory to what VS Code had me believing.
Attempt to optimise v2:
I tried changing the import statement to this:
from .....pythonhelpers.Helpers import Helpers
However, when I run my Python script, I get the following error:
from .....pythonhelpers.Helpers import Helpers ImportError: attempted relative import with no known parent package
What am I doing wrong?