0

Sought: A Python 3 library (hopefully also supporting Python 2) that takes a Python file containing assignments of literal values (specifically, anything parseable by ast.literal_eval) to variables and returns a dict of the resulting namespace. If the file contains any non-literal assignments, the library either raises an error or ignores them.

For example, the library should be able to turn a file like this:

foo = 42
bar = [{"quux": None, "glarch": True}]
foo = 'reassigned'

into the value:

{
    "bar": [{"quux": None, "glarch": True}],
    "foo": "reassigned"
}

and a file like this:

foo = range(42)
bar = 2 + 2
quux = input()
glarch = 'Hi!'

would either produce an error or end up as just {"glarch": "Hi!"} without actually running the range() or input() (Bonus points if it can parse the bar = 2 + 2, though).

(I could've sworn I'd seen a library like this before, possibly as part of Django, but I can't find it anymore.)

1 Answer 1

4

I don't know of a library for this specific task, but it's easy to do it with ast.parse. Here's an example in Python 3:

import ast

with open("myfile.py", "r") as o:
    src = o.read()
top_level = ast.parse(src)

result = {}
for statement in top_level.body:
    assert isinstance(statement, ast.Assign)
    assert len(statement.targets) == 1
    name = statement.targets[0].id
    result[name] = ast.literal_eval(statement.value)

print(result)

If the input is:

 foo = 42
 bar = [{"quux": None, "glarch": True}]
 foo = 'reassigned'
 bing = 1 + 1

Then you get:

{'bing': 2, 'foo': 'reassigned', 'bar': [{'glarch': True, 'quux': None}]}
1
  • I did not expect the code to be that simple.
    – jwodder
    Jan 25, 2017 at 2:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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