簡體   English   中英

從另一個模塊訪問全局變量

[英]Accessing globals from another module

我想制作一個通用模塊,可以將對象轉換為 JSON 格式,將其保存到文本文件中,然后將它們重新加載。

下面是偽代碼的解釋

保存時,它需要一個對象(復制它以不損壞原始對象,由自定義類方法創建)並遍歷所有屬性。

如果該屬性是提供的要跳過的鍵列表中的值,則刪除該屬性

如果屬性是可迭代的,它會對其進行迭代以查看它是否還有其他可迭代對象或類對象

如果來自可迭代對象或屬性的值是類對象,它會在該對象上運行此保存函數

最后它返回一個帶有兩個鍵的字典,“id”:“類對象類型的名稱”和“data”:“作為對應數據鍵的所有屬性的字典”

這將轉換為字符串並保存到文件中

加載問題來自##的##時

它接受字符串並轉換回字典。 它需要“id”並嘗試使用globals()[dict["id"]]()創建該類的實例

這就是問題的來源。 因為我將此模塊導入到其他地方的主代碼中,所以在調用 globals 時,它正在獲取模塊的全局變量,而不是主程序,據我所知,無法與此導入的模塊共享全局變量。 我還有其他方法可以做到這一點嗎? 或者一些不需要我將所有代碼重新定位到我的主代碼中的修復程序? 我已經在模塊本身內對其進行了測試,它可以 100% 工作,但在導入時卻不能。

電話:博士

制作了一個模塊,可以將對象保存為 JSON 並可以將它們轉換回來,但需要訪問正在運行的程序的全局變量。

這是底部帶有功能示例的代碼。 它在不以這種方式導入和使用時有效。

import json

def testiter(object): ## tests if an object is iterable
    if isinstance(object, list) or isinstance(object, tuple):
        return True
    else:
        return False
def testclass(object): ## tests if an object is a class object 
    try:
        object.__dict__
        return True
    except:
        return False
class object_clone(): ## creates a clone of a object
    def __init__(self, object, skip):
        self.__class__.__name__ = object.__class__.__name__
        for attr, value in dict(vars(object)).items():
            if not(attr in skip):
                if testiter(value):
                    setattr(self, attr, self.iterable_search(value, skip))
                elif testclass(value):
                    setattr(self, attr, object_clone(value, skip))
                else:
                    setattr(self, attr, value)
    def iterable_search(self, lst, skip):
        ret = []
        for value in lst:
            if testiter(value):
                ret.append(self.iterable_search(value, skip))
            elif testclass(value):
                ret.append(object_clone(value, skip))
            else:
                ret.append(value)
        return ret
class object_save(): ## saves an object
    def save(self, object, skip, path):
        self.skip=skip ## for skipping data that is unsaveable
        open(path, 'w').write(json.dumps(self.semisave(object_clone(object, skip)))) ## clones the given object, writes it in a dict format, saves as json string, then writes to path
    def semisave(self, object):
        for attr, value in dict(vars(object)).items(): ## iterate over class object attributes
            if attr in self.skip: 
                delattr(object, attr) ##remove unsavable
            elif testiter(value):
                setattr(object, attr, self.iterable_search(value)) ## Searches through iterables
            elif testclass(value): ## runs this function on any class objects found
                setattr(object, attr, self.semisave(value))
        return {
            'class_instance':object.__class__.__name__,
            'data':json.loads(json.dumps(vars(object)))} ## json dict of object
    def iterable_search(self, lst):
        ret=[]
        for value in lst:
            if testiter(value):
                ret.append(self.iterable_search(value)) ## Searches through nested iterables
            elif testclass(value):
                ret.append(self.semisave(value)) ## converts found class objects to dict
            else:
                ret.append(value) ## skips other data
        return ret
class object_load():
    def load(self, path):
        json.loads(open(path, 'r').read()) ## loads saved string and converts to dict
        return self.semiload(json.loads(open(path, 'r').read()))
    def semiload(self, json):
        try:
            [print(key, name) for key, name in globals().items()] ##issue here##
            ret = globals()[json['class_instance']]()
        except:
            return
        for attr, value in json['data'].items():
            if isinstance(value, dict) and 'class_instance' in value:
                setattr(ret, attr, self.semiload(value))
            elif testiter(value):
                setattr(ret, attr, self.iterable_scan(value))
            else:
                setattr(ret, attr, value)
        return ret
    def iterable_scan(self, lst):
        ret=[]
        for value in lst:
            if isinstance(value, dict) and 'class_instance' in value:
                ret.append(self.semiload(value))
            elif testiter(value):
                ret.append(self.iterable_scan(value))
            else:
                ret.append(value)
        return ret

##example
class foo():
    def __init__(self):
        self.a='test'
        self.b=5
        self.c=['test', 5, [bar()]]
    def print_attr(self):
        [print([attr, value]) for attr, value in vars(self).items()]
class bar():
    def __init__(self):
        self.c=5
        self.e=[[6], 2]
object_save().save(foo(), ['b'], 'a')
object_load().load('a').print_attr()

下面的示例代碼用簡單的術語說明了如何做你想做的事情的原則。 盡管我同意@Tim Roberts 的觀點,但我還是提供了它,因為這樣做通常是不明智的——因為我也相信每個“規則”都有例外,我們都是成年人。

事實上,我很久以前就想出如何做到這一點的原因恰恰是在我認為這樣做是合理的情況下。

也就是說,這里的“足夠的繩子可以用腳射擊你自己”是我最喜歡的一本關於 C/C++ 編程的書的作者,他的一本書的書名中使用了這一點。

sample_vars.json

{
    "a": "foobar",
    "b": 42
}

main.py

from make_vars import create_vars

create_vars('sample_vars.json')
print(f'{a=}, {b=}')  # -> a='foobar', b=42

make_vars.py

import json
import sys

def create_vars(json_filename):
    namespace = sys._getframe(1).f_globals  # Caller's globals

    with open(json_filename) as json_file:
        saved_vars = json.load(json_file)

    namespace.update(saved_vars)  # Create/update caller's globals.

暫無
暫無

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

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