0

Let's assume that one has one list: lst = [name, surname, phone, email] and one dictionary data={"name": "Mary", surname: "Smith", "phone": "123", "email": "mail@domain.com"}.

I want to preapre code like this:

sample_object.add('user').prop('name': data['name']).prop('surname': data['surname']).prop('phone': data['phone']).prop('email': data['email']).do()

The problem is that I want to make id dynamically, the static parts are: sample_object.add('user') and .do(). The middle part is dynamic that means that my list can contain e.g. 7 elements and the values could be various.

Theoretically, I can concatenate strings in for loop and then use exec on the string but I found it as an ugly solution. How can I do it in a pythonic way?

Tomasz
  • 21
  • 4
  • Why not give your object an update method that takes the dictionary, or the dictionary unpacked into keyword arguments? The fluent interface doesn't seem like it's giving you any benefits. – jonrsharpe Oct 12 '17 at 14:22
  • The object is created from the third part class. – Tomasz Oct 12 '17 at 14:24
  • .prop is a method that set's the property simillar to `setattr`? – Vince W. Oct 12 '17 at 14:24
  • 1
    That is not how you code in Python. Functions in Python are dynamic enough to do what you like to do in one shot. `.prop(name=data['name'], surname=data['surname'], ...)` and the function would be something like `def prop(**kwargs)`. – Klaus D. Oct 12 '17 at 14:26
  • @KlausD. as I mentioned the prop function is a third part function. It was primarily written in Java. More precisely in Groovy, and even more precisely it is Gremlin. – Tomasz Oct 12 '17 at 14:30
  • @Vince W, I'm not sure if I understand you correct. Could you expand your question? – Tomasz Oct 12 '17 at 14:31
  • Are you on Jython, or how do you use the Java function? – Klaus D. Oct 12 '17 at 14:32
  • I use Python, I use it as you can read here: http://tinkerpop.apache.org/docs/current/reference/#gremlin-python – Tomasz Oct 12 '17 at 14:37
  • I see that what you're trying to do is similar to the Builder pattern, maybe you should check this answer on Builder pattern in python - https://stackoverflow.com/questions/11977279/builder-pattern-equivalent-in-python#11977454 – TheSPD Oct 12 '17 at 14:38
  • Show us definition of that `prop` method. – pacholik Oct 12 '17 at 15:02
  • `prop` is short from `property` method which is here: https://github.com/apache/tinkerpop/blob/3.2.6/gremlin-python/src/main/jython/gremlin_python/structure/graph.py – Tomasz Oct 12 '17 at 15:06

0 Answers0