暴露 __main__

发布于 2024-09-08 02:42:59 字数 2099 浏览 4 评论 0原文

这在Python中合法吗?似乎有效...

感谢

# with these lines you not need global variables anymore

if __name__ == '__main__':
    import __main__ as main
else:
    main = __import__(os.path.basename(os.path.splitext(__file__)))

var_in_main = 0  # now any var is a global var, you can access any var from everywhere

def fun(*args, **kwargs):

    self = fun
    self.var_in_fun = 'I am a var into fun'

    if args:
        returnList = []
        for request in args:
            returnList.append( getattr(self, request , 'Sorry, no var named "%s" into fun.' % request ) )

        if len(returnList) == 1:
            return returnList[0]
        else:
            return returnList

    elif kwargs:
        for k,v in kwargs.iteritems():

            reset = kwargs.get('reset', None)
            if reset:
                main.var_in_main = 0

            if k == 'times':
                for i in range(v):
                    fun()

            setattr(self, k, v)

    else: # when no args or kwars, execute.
        main.var_in_main += 1
        print ' -', main.var_in_main
        return self


# testing 

print '\nSETTING AND GETTING VARS'

print '     ', fun('var_in_fun')
print '     ', fun('var_in_fun','erroneus_var_name')
print '     ', fun('var_in_fun','erroneus_var_name')[0]

fun( new_var_in_fun = fun )

print '     ', fun( 'new_var_in_fun' ) 
print '     ', fun

print '\nMULTIFUNCTION'

fun()()()()    
fun()
fun()()()

print '\nRESET AND THEN LOOP'

fun( reset = 1)
fun( times = 3 )

print '\nRESET AND LOOP, IN ONE SHOT'

fun( reset= 1, times = 100  )

输出

SETTING AND GETTING VARS
      I am a var into fun
      ['I am a var into fun', 'Sorry, no var named "erroneus_var_name" into fun.']
      I am a var into fun
      <function fun at 0x44f930>
      <function fun at 0x44f930>

MULTIFUNCTION
 - 1
 - 2
 - 3
 - 4
 - 5
 - 6
 - 7
 - 8

RESET AND THEN LOOP
 - 1
 - 2
 - 3

RESET AND LOOP, IN ONE SHOT
 - 1
 - 2
 - 3
 - 4
 - 5
 - 6
 - 7

  --- goes on and on -----

 - 95
 - 96
 - 97
 - 98
 - 99
 - 100

is this legal in python?. Seems to work ...

Thanks

# with these lines you not need global variables anymore

if __name__ == '__main__':
    import __main__ as main
else:
    main = __import__(os.path.basename(os.path.splitext(__file__)))

var_in_main = 0  # now any var is a global var, you can access any var from everywhere

def fun(*args, **kwargs):

    self = fun
    self.var_in_fun = 'I am a var into fun'

    if args:
        returnList = []
        for request in args:
            returnList.append( getattr(self, request , 'Sorry, no var named "%s" into fun.' % request ) )

        if len(returnList) == 1:
            return returnList[0]
        else:
            return returnList

    elif kwargs:
        for k,v in kwargs.iteritems():

            reset = kwargs.get('reset', None)
            if reset:
                main.var_in_main = 0

            if k == 'times':
                for i in range(v):
                    fun()

            setattr(self, k, v)

    else: # when no args or kwars, execute.
        main.var_in_main += 1
        print ' -', main.var_in_main
        return self


# testing 

print '\nSETTING AND GETTING VARS'

print '     ', fun('var_in_fun')
print '     ', fun('var_in_fun','erroneus_var_name')
print '     ', fun('var_in_fun','erroneus_var_name')[0]

fun( new_var_in_fun = fun )

print '     ', fun( 'new_var_in_fun' ) 
print '     ', fun

print '\nMULTIFUNCTION'

fun()()()()    
fun()
fun()()()

print '\nRESET AND THEN LOOP'

fun( reset = 1)
fun( times = 3 )

print '\nRESET AND LOOP, IN ONE SHOT'

fun( reset= 1, times = 100  )

output

SETTING AND GETTING VARS
      I am a var into fun
      ['I am a var into fun', 'Sorry, no var named "erroneus_var_name" into fun.']
      I am a var into fun
      <function fun at 0x44f930>
      <function fun at 0x44f930>

MULTIFUNCTION
 - 1
 - 2
 - 3
 - 4
 - 5
 - 6
 - 7
 - 8

RESET AND THEN LOOP
 - 1
 - 2
 - 3

RESET AND LOOP, IN ONE SHOT
 - 1
 - 2
 - 3
 - 4
 - 5
 - 6
 - 7

  --- goes on and on -----

 - 95
 - 96
 - 97
 - 98
 - 99
 - 100

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

江湖正好 2024-09-15 02:42:59
if __name__ == '__main__':
    import __main__ as main
else:
    main = __import__(os.path.basename(os.path.splitext(__file__)))

这是一种非常脆弱的方法,因为它依赖于包内所有模块的相对导入行为。有一个更好的解决方案——更快、更简洁、更可靠:

import sys
main = sys.modules[__name__]

名称的奇怪选择 main 仍然存在(我通常在使用时使用类似 thismodule 的东西)这种方法),但绑定该名称的方法现在是合理的。

if __name__ == '__main__':
    import __main__ as main
else:
    main = __import__(os.path.basename(os.path.splitext(__file__)))

This is quite a fragile approach, since it relies on relative import behavior for all modules from within a package. There is a much better solution -- faster, more concise, and more reliable:

import sys
main = sys.modules[__name__]

The weird choice of main for the name remains (I normally use something like thismodule when I use this approach) but the approach taken to bind that name is now sound.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文