0

I have a program that I would like to automate, removing the pre-processing steps as much ass possible. Reading through a dataset, the program generates series of function calls that get used in a subsequent step. Currently I just copy the generated calls stored in the variable into the file, but I would like to skip this step if possible

##preprocessing steps here...
bindings = ["g.bind('rdf', URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#'))",
 "g.bind('bf', URIRef('http://id.loc.gov/ontologies/bibframe/'))",
 "g.bind('bflc', URIRef('http://id.loc.gov/ontologies/bflc/'))"]

### then the bind calls are added to the function below.
g = rdflib.Graph()

g.bind('rdf', URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#'))
g.bind('bf', URIRef('http://id.loc.gov/ontologies/bibframe/'))
g.bind('bflc', URIRef('http://id.loc.gov/ontologies/bflc/'))```

g.parse(data= graph, format='nt')
g.serialize(format='turtle')

How can I remove the copying and pasting from the process?

2
  • Essentially, you want to execute the strings like "g.bind('rdf', URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#'))" as if they contained valid Python code, right? This is exactly what you can do with eval and exec functions. Commented Nov 1, 2019 at 18:30
  • 1
    I would avoid using eval or exec where they're not absolutely necessary. If you want to defer a function call until later, you can wrap it in a lambda, like lambda: g.bind(...). However, there is probably no need for that here either. Commented Nov 1, 2019 at 18:32

1 Answer 1

2

Are these calls all going to be for the same function? If so, there is no need to store a string representing a function call; just store the data it should be called with.

bindings = [
    ('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'),
    ('bf', 'http://id.loc.gov/ontologies/bibframe/'),
    ('bflc', 'http://id.loc.gov/ontologies/bflc/'),
]

# ...

for key, uri in bindings:
    g.bind(key, URIRef(uri))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.