Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "import"-ing data pythonic?

Tags:

python

import

I have a python script that, in it's "initialize" runmode, accesses multiple files on my system and assembles what it thinks is the correct data. This data needs to be reviewed by a user before setting the script to run in "final" mode, when the data is actually used.

Right now I'm writing out the data to be reviewed into a data.py file, in the form of python data structures, e.g. the contents of data.py could be:

data1 = "script_generated_filename_1"

data2 = [ "script_generated_date1",
          "script_generated_date2" ]

After the user validates the data.py file, the "final" runmode then uses an "import data" call to gain access to the data, via data.data1, data.data2, etc...

I've been trying to clean up my python programming style, and come more in line with what is generally considered to be pythonic. After reading through the module docs, I have my doubts as to whether using the import function in this way is pythonic, or if there is a more mainstream way to accomplish this type of user-validation using python.

like image 225
jeremiahbuddha Avatar asked Jul 15 '26 08:07

jeremiahbuddha


2 Answers

This is a fine thing to do with a module. The thing you want to avoid is executing code that does too much, or has side-effects, at import time, and this doesn't do that.

like image 106
Ned Batchelder Avatar answered Jul 18 '26 14:07

Ned Batchelder


I think you should put your data in text files (JSON, CSV, whatever is appropriate) and then just have your script read it in. In general (not just in Python), it's best to keep code and data separate.

like image 34
dumbmatter Avatar answered Jul 18 '26 15:07

dumbmatter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!