如何成为可选参数? [英] How can an optional parameter become required?

查看:84
本文介绍了如何成为可选参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于在Python中禁用全局变量查找(以及我自己的回答),在使用带有可选参数的函数,例如在此最小示例中:

Based on Disable global variable lookup in Python (and my own answer there), I have had problems when using a function with optional parameters such as in this minimal example:

import types

def noglobal(f):
    return types.FunctionType(f.__code__, {})

@noglobal
def myFunction(x=0):
    pass

myFunction()

基本上,它会像这样失败:

Essentially, it fails like this:

Traceback (most recent call last):
  File "SetTagValue.py", line 10, in <module>
    myFunction()
TypeError: myFunction() missing 1 required positional argument: 'x'

为什么x突然被视为必需参数?

Why is x suddenly treated as a required parameter?

推荐答案

如果要保留默认参数值,还需要传递它们:

If you want to preserve the default argument values you need to pass them as well:

import types

def noglobal(f):
    return types.FunctionType(f.__code__, {}, f.__name__, f.__defaults__)

@noglobal
def myFunction(x=0):
    pass

myFunction()

您可以将最后一个closure参数传递给types.FunctionType,如果您想使函数保持闭合状态,您可能还希望从f.__closure__继承该参数.

You can pass one last closure parameter to types.FunctionType, which you may also want to inherit from f.__closure__ if you want to keep functions with a closure working.

这篇关于如何成为可选参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆