简体   繁体   English

python:def的两个版本,具体取决于设置

[英]python: two versions of def depending on setting

I have a program that runs on two platforms. 我有一个在两个平台上运行的程序。 Each platform has a different set of imported modules. 每个平台都有一组不同的导入模块。 Many of the def statements on one platform need an additional parameter to run with its set of imports. 一个平台上的许多def语句都需要一个附加参数才能与其导入集合一起运行。 Not every def statement needs to be changed. 并非每个def语句都需要更改。

If something like this worked, it would be make things easier: 如果像这样的事情行得通,那将使事情变得更容易:

if platform_1:
   def func(this, that):
else:
   def func(self, this, that):

   func_body

Is there any way do do this? 有什么办法吗?

I wonder why a function should have an argument that it never uses. 我想知道为什么一个函数应该有一个它从不使用的参数。 Wouldn't it be better to fix the surrounding code that forces you into this situation? 修复周围的迫使您进入这种情况的代码会更好吗?

Nevertheless, it is possible... 尽管如此,还是有可能...

def narcissist(func):
    def wrapper(self,*args,**kwargs):
        return func(*args,**kwargs)
    return wrapper

def identity(func):
    return func

if platform_1:
    modify_args=identity
else:
    modify_args=narcissist

@modify_args
def func(this,that):
    func_body

If the imports aren't actually calling your func , you're making things harder for yourself, and you want to do: 如果导入实际上没有调用func ,那么您会使自己变得更难了,并且您想这样做:

def func( self, this, that ):
    if platform_1:
        # do something with just this and that, ignoring self
        import_1.doSomething( this, that )
    else:
        # do something with self, this, that
        import_2.doSomething( self, this, that )

If the platform-specific code is calling into your func, I'd consider defining one version of func as a wrapper for the other, with two separate names. 如果特定于平台的代码正在调用您的func,则可以考虑将一个版本的func定义为另一个版本的包装,并使用两个单独的名称。

i think you could do this with a decorator, if the change was always of the same form. 我认为如果更改始终是相同的形式,则可以使用装饰器执行此操作。 for example, the following would add a first argument of None if the system is X : 例如,如果systemX ,则以下将添加第一个参数None

def multiplatform(function):
    if system is X:
        def wrapper(*args, **kargs):
            return function(None, *args, **kargs)
    else:
        def wrapper(*args, **kargs):
            return function(*args, **kargs)
    return wrapper

@multiplatform
def foo(first, second, third):
    '''first should not be given on platform X'''
    print(first, second, third)

and then on system X : 然后在系统X

>>> foo(2, 3)
None 2 3

while on other systems 在其他系统上

>>> foo(1, 2, 3)
1 2 3

disclaimer: untested code, but should give the general idea. 免责声明:未经测试的代码,但应给出总体思路。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM