Python changing modifying via imported function
-
14-11-2019 - |
Question
I am trying to create a function, that when imported and then called, it will check and modify a tuple. I would like to be able to call this multiple times. However, I just have the function return the new variable, because I can not figure out a way to change the variable in place.
Here is my examples with two files, how I would like it to work:
**modifier.py**
import variable
def function(new_string):
if new_string not in variable.tuple:
variable.tuple = new_string, + variable.tuple
**variable.py**
import modifier
tuple = ('one','two',)
modifier.function('add this')
modifier.function('now this')
#--> tuple should now equal ('now this', 'add this', 'one', 'two',)
However right now I have to do this:
**modifier.py**
def function(tuple_old, new_string):
if new_string not in tuple_old:
return new_string, + tuple_old
**variable.py**
import modifier
tuple = ('one','two',)
tuple = modifier.function(tuple, 'add this')
tuple = modifier.function(tuple, 'now this')
#--> tuple now equals ('now this', 'add this', 'one', 'two',)
This is a lot messier. First off, I have to pass in the old tuple value and get a returned value, instead of replacing the tuple directly. It works, but its not DRY and I know there must be a way to make this cleaner.
I can't use lists, because this is actually a function to update my middleware on my django settings file. Also I don't have to have the function on a different file, but I also think it should be possible.
Solution
I don't see anything wrong about what you're doing right now (last code block), it's clear. If I see something like:
tuple = # something ...
I know that tuple is changed (probably it's just a name you used for the example, but don't call your variable "tuple").
But if I see this (what you'd like to do):
tuple = 'one', two'
function('add this')
I'd never imagine that function
changed tha value of tuple
. Anyway, it could be done with:
tuple = 'one', 'two'
def function(string):
global tuple
if new_string not in tuple:
tuple = (new_string,) + tuple
function('add this')
Also something like this could be done:
tuple = 'one', two'
function(tuple, 'add this')
I'd say it's a little better because if I were to use your code having probelms I might guess that function
does something to tuple.
And the code would be:
tuple = 'one', 'two'
def function(old_tuple, string):
global tuple
if new_string not in old_tuple:
tuple = (new_string,) + old_tuple
function(tuple, 'add this')
At the end I'd say that what you're doing right now is clear and more simple, I wouldn't change it.
OTHER TIPS
This seems to work:
def function(new_string):
if new_string not in variable.tuple:
variable.tuple = (new_string,) + variable.tuple