Python通过导入函数改变修改

标签 python django-middleware django-settings

我正在尝试创建一个函数,当导入然后调用时,它将检查并修改元组。我希望能够多次调用它。但是,我只是让函数返回新变量,因为我无法找到适当更改变量的方法。

这是我的示例,包含两个文件,我希望它如何工作:

**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',)

但是现在我必须这样做:

**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',)

这要困惑得多。首先,我必须传入旧的元组值并获取返回值,而不是直接替换元组。它可以工作,但它不干燥,我知道必须有一种方法可以使它更干净。


我不能使用列表,因为这实际上是一个更新 django 设置文件上的中间件的函数。另外,我没有在不同的文件上拥有该函数,但我也认为这应该是可能的。

最佳答案

我认为你现在所做的事情(最后一个代码块)没有任何问题,很清楚。如果我看到类似的内容:

tuple = # something ...

我知道元组已更改(可能只是您在示例中使用的名称,但不要将变量称为“元组”)。

但是如果我看到这个(你想做的事情):

tuple = 'one', two'
function('add this')

我从来没有想过function会改变tuple的值。无论如何,可以通过以下方式完成:

tuple = 'one', 'two'

def function(string):
    global tuple
    if new_string not in tuple:
        tuple = (new_string,) + tuple

function('add this')

也可以这样做:

tuple = 'one', two'
function(tuple, 'add this')

我想说这更好一点,因为如果我使用有问题的代码,我可能会猜测 function 对元组做了一些事情。

代码是:

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')

最后我想说,你现在做的事情很清楚也更简单,我不会改变它。

关于Python通过导入函数改变修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8997975/

相关文章:

python - 在/admin/安装 jinja2 TemplateDoesNotExist 后

Django 模板系统独立

python - 按名称填写缺失值。 Pandas

python - "KeyError: 0"与 xgboost、scikit-learn 和 pandas

python - AttributeError: 'WSGIRequest' 对象没有属性 'user'

django - 使用多主机中间件测试 django 页面

python - 使用 pandas 建立索引的最佳实践

python - 如何创建具有可调参数的 numba 可调用对象?

python - 如何通过使用 urllib 从请求中读取 CSRF token 在 django 应用程序之间传递 CSRF token

django - 将 django 应用程序移动到子文件夹和 url.py 错误