簡體   English   中英

Python將變量定義為“首次使用時加載文件”

[英]Python define variable as “load file at first use”

Python初學者在這里。 我目前有一些看起來像的代碼

a=some_file_reading_function('filea')
b=some_file_reading_function('fileb')
# ...
if some_condition(a):
    do_complicated_stuff(b)
else:
    # nothing that involves b

讓我感到困擾的是,可能不需要加載“ fileb”,並且會降低性能。 理想情況下,僅當稍后實際需要b時,我才加載它。 OTOH,b可能被多次使用,因此,如果使用一次,則應該一次加載該文件。 我不知道該如何實現。

在上面的偽代碼中,可以簡單地將“ fileb”的加載帶入條件循環中,但實際上有兩個以上的文件,條件分支非常復雜。 此外,代碼仍在大量開發中,條件分支可能會更改。

我稍微看了一下迭代器或定義了一個類,但是(可能由於我的經驗不足)無法使它們起作用。 我遇到的關鍵問題是,如果不需要,將文件加載0次,如果需要,則僅加載一次。 我沒有在搜索中找到任何內容,因為“如何按塊加載文件”會污染“文件延遲加載”和類似查詢的結果。

如果需要:Win7上的Python 3.5和some_file_reading_function返回1D-numpy.ndarray。

class LazyFile():
  def __init__(self, file):
    self.file = file
    self._data = None

  @property # so you can use .data instead of .data()
  def data(self):
    if self._data is None: # if not loaded
      self._data = some_file_reading_function(self.file) #load it

    return self._data

a = LazyFile('filea')
b = LazyFile('fileb')

if some_condition(a.data):
  do_complicated_stuff(b.data)
else:
  # other stuff

實際上,剛剛找到了解決類的方法。 嘗試/除非受如何知道對象在Python中是否具有屬性的啟發。 有點丑陋,但是可以做到:

class Filecontents:
    def __init__(self,filepath):
        self.fp = filepath
    def eval(self):
        try:
            self.val
        except AttributeError:
            self.val = some_file_reading_function(self.fp)
            print(self.txt)
        finally:
            return self.val
def some_file_reading_function(fp):
    # For demonstration purposes: say that you are loading something
    print('Loading '+fp)

    # Return value
    return 0


a=Filecontents('somefile')
print('Not used yet')
print('Use #1: value={}'.format(a.eval()))
print('Use #2: value={}'.format(a.eval()))

雖然不確定這是“最佳”(最漂亮,最Pythonic)的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM