Making a copy of an entire namespace?

后端 未结 3 1093
Happy的楠姐
Happy的楠姐 2021-02-01 10:44

I\'d like to make a copy of an entire namespace while replacing some functions with dynamically constructed versions.

In other words, starting with namespace (impo

3条回答
  •  盖世英雄少女心
    2021-02-01 10:57

    To my mind, you can do this easily:

    import imp, string
    
    st = imp.load_module('st', *imp.find_module('string')) # copy the module
    
    def my_upper(a):
        return "a" + a
    
    def my_lower(a):
        return a + "a"
    
    st.upper = my_upper
    st.lower = my_lower
    
    
    print string.upper("hello") # HELLO
    print string.lower("hello") # hello
    
    print st.upper("hello") # ahello
    print st.lower("hello") # helloa
    

    And when you call st.upper("hello"), it will result in "hello".

    So, you don't really need to mess with globals.

提交回复
热议问题