是否可以创建一个“ with”块来运行它只包含一次的代码?

问题描述 投票:0回答:2

无论调用多少次方法/函数,执行一次代码的最短和最佳方法是什么。

代码位于方法内部。仅举例来说:

once = 0
def fun():

  if once == 0 : 
    print 234
    once += 1

当然,这是过多的簿记..而且不是很可扩展..

我希望它更像是'with'

 def fun():
   ......
   once : ... code ..
   ......

功能/方法代码必须在每次调用时执行。.仅一次执行“一次”。

我正在使用2.7 ..

可能会涉及'一次'实施,但是用法必须简单,并且没有更多的逻辑和簿记。

我在调试某一种方法的时候经常需要这个方法,但是我想一次或两次打印调试信息...

'warnings'并不完全相同,但某种程度上具有相似的功能...不知道他们是如何做到的?

python contextmanager
2个回答
0
投票

一种策略可以是一个函数调用一个“一次性”执行函数,该函数可以在运行时或运行时开始时用另一种实现方式替换(调试与部署),或者在执行完之后不做任何事情而返回的函数第一次执行。

第一种情况的示例:

>>> def debug_logging(message):
...     print("doing a lot of logging..." + message)
...     
>>> def _disable_debug_logging(message):
...     pass
...     
>>> foo()
doing a lot of logging...just entered foo()
doing stuff...
doing a lot of logging...leaving foo()
>>> 
>>> debug_logging = _disable_debug_logging 
>>> 
>>> foo()
doing stuff...
>>> 

重新定义一次性函数可以在一次性函数本身内部完成,如下所示:

>>> def slow_initialization():
...     global slow_initialization
...     print("taking forever to update database - once...")
...     slow_initialization = _disable_slow_initialization
...     
>>> def _disable_slow_initialization():
...     pass
...     
>>> def foo():
...     slow_initialization()
...     print("now doing other stuff...")
...     
>>> foo()
taking forever to update database - once...
now doing other stuff...
>>> 
>>> foo()
now doing other stuff...
>>> 

0
投票

您是否考虑过decorator?有点像

Python 2.7.17 (default, Oct 20 2019, 14:46:50) 
[GCC 4.2.1 Compatible Apple LLVM 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import functools
>>> class once:
...     def __init__(self, wrapped):
...         self.wrapped = wrapped
...         functools.update_wrapper(self, wrapped)
...     def __call__(self, *args, **kwargs):
...         if not hasattr(self, "retval"):
...             self.retval = self.wrapped(*args, **kwargs)
...         return self.retval
... 
>>> @once
... def fun():
...     print 234
... 
>>> fun()
234
>>> fun()
>>> 

我认为这是一种管理上述全局状态的更好方法。

© www.soinside.com 2019 - 2024. All rights reserved.