开发者

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. Not every def statement needs to be changed.

If something like this worked, it would be make things easier:

开发者_JAVA技巧
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:

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.


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:

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:

>>> 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜