3
$\begingroup$

I use Python for data munging, R for data analysis, and I combine both by running the munging/analysis sequentially in a Makefile. My Python and R scripts depend on various constants. I typically store my Python constants in a settings.py file, and I import this file across several Python scripts which depend on those constants. My R constants are typically not used in more than one script, so I store those constants in the script which uses them.

Some constants are shared by both the Python scripts and R scripts. Right now, I am defining them separately in R/Python files. However, it would be better if there was some way of defining constants in common across Python and R files, since this redundancy can lead to mistakes.

What would be the best way for me to define constant in common across files? Obviously, there is the problem that these are two different languages; so, for example, a list in Python is not quite the same as a list in R. However, there might be some solution which is more elegant than simply repeating constants across files.

I believe this would be the best place for this question, but if it belongs in the Python or R StackExchanges, please let me know.

$\endgroup$
  • $\begingroup$ Can you show a small sample of your constants? $\endgroup$ – E_net4 says Reinstate Jul 21 '17 at 18:47
  • $\begingroup$ Sure. Two examples of constants used in my Python munging are: FIRST_YEAR = 1952 IV_TYPES = [('p', 6), ('n', 6), ('w', 4)] $\endgroup$ – Yusuf Jul 21 '17 at 19:21
  • $\begingroup$ It might not be appropriate to call the second a "constant", but it is a fixed unit of information I would like to convey to both all my R scripts and all my Python scripts. However, I define both in a settings.py file, and I have a hard time thinking about how to instead define these variables in a way which allows me to import them both to R and Python scripts. $\endgroup$ – Yusuf Jul 21 '17 at 19:27
6
$\begingroup$

You should consider storing this sort of data into a format that is more universally accessible. I would suggest either JSON or YAML. JSON can be readily parsed by both R and Python

Your data would look something like:

{
    "FIRST_YEAR": 1952, 
    "IV_TYPES": [
        ["p", 6], 
        ["n", 6], 
        ["w", 4]
    ]
}
$\endgroup$
  • 1
    $\begingroup$ I think this is exactly what I want to do - thanks Stephen! $\endgroup$ – Yusuf Jul 23 '17 at 0:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.