2

Assume we have an object a and we want modify data which is structures like this

a.substructure1.subsubstructure1.name_of_the_data1

and this

a.substructure2.subsubstructure2.name_of_the_data2

To access this structure we call an external method get_the_data_shortcut(a) which is heavily parameterized (for example the parameter subsstructure specifies which substructure to return). This seems very redundant but there is a very good default setting for all these parameter which makes sense. Also, this function will return another branch of data if the default branch is not available.

How do I modify get_the_data_shortcut(a) ?

b = get_the_data_shortcut(a)
b = b + 1

Then, get_the_data_shortcut(a) is unchanged because well Python is not Java.

Do I need a setter? Mostly, this is not my code and written by people who write pythonic code, and I am trying to keep up with those standards.

1
  • 4
    The usual Python way would be to do something like b = a.substructure1.subsubstructure1; b.name_of_the_data1 += 1. But maybe you should write a minimal reproducible example so we have something more tangible to discuss. Commented Aug 28, 2015 at 16:01

2 Answers 2

1

As you discovered changing the object b refers to won't modify the a object (or its substructures). If you want to do this you will need a method similar to your get_the_data_shortcut(a). Namely a

set_the_data_shortcut(a, newvalue)

Alternatively you could have a method which would return the substructure the value was stored in and manipulate that..

# returns a.substructure2.subsubstructure2 
#          or a.substructure1.subsubstructure1 based on the value of kind
substruct = get_the_substructure(a, kind)
substruct.name_of_data1 += 1
Sign up to request clarification or add additional context in comments.

Comments

1

Python uses reference types, just like java. However, when you do

b = b + 1

you are not updating the object you have. Instead, you are creating a new object and assigning it to the variable b.

If you want to update the value of b in the data structure, you should follow your suggestion and write a setter for the data structure.

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.