For the last 6 months I have been learning python and practicing with the logic of python. However, as I continue to become more advanced, I find that I just have more and more to learn. One question that I have encountered is how to work with multiple files in one project. An example of what I am trying to do is: If i have a solution that is running predictive analysis on stock data being scraped from the web, and I want to compare these results with SP500 data, I am currently using two different projects and comparing the data by hand. As you can imagine this is extremely inefficient and leads to more errors than benefits. When learning C# and VB.NET in visual studios, there was a way to create multiple forms for a GUI, and reference those forms from other forms. While I know this is not the same as what I am trying to ask, I am wondering if there is a way to work with multiple .py files in one solution, each having their own logic, and reference these different files from other files.
2 Answers
If you had a file like start.py and then things.py held functions, objects, or classes...
start.py
import things
from things import config
things.printline(config)
things.py
config = 'This is a variable assignment'
def printline(line):
print(line)
return line
It's really that easy. You can also store several files into a directory and just import the directory the same way, you just need to have an empty __init__.py file in it. Your import would be
import folder.nameofmodule
2 Comments
I focus only on your core problem:
If I have a solution that is running predictive analysis on stock data being scraped from the web, and I want to compare these results with SP500 data, I am currently using two different projects and comparing the data by hand.
My advice is not to combine different projects for the sake of comparing output. Don't let any interface or environment decide how you structure your code.
Code structure is dependent on what you are actually doing. If you need to compare outputs of 2 different classes from different projects, write a script to calculate and compare results from your 2 classes:
comparer.py:
import Class1
import Class2
Class1Instance = Class1.ClassOne()
Class2Instance = Class2.ClassTwo()
res1 = Class1Instance.get_results()
res2 = Class2Instance.get_results()
def compare_results(x, y):
return func(x, y)
compare_results(res1, res2)
If there are specific tests your scripts should satisfy, consider using unittest from the standard library.
2 Comments
unittest and perform other testing functions, comparing 2 other projects, then yes, that's absolutely a good reason for a 3rd project/script.
importsystem that you can use to logically separate code into different files and import into a single, master, script.