Can one function have multiple names?

前端 未结 3 1182
离开以前
离开以前 2021-01-21 01:53

I\'m developing a bot on Python (2.7, 3.4). I defined a about 30+ dynamic functions which to be used based on bot commands. While development, since not all functions are done,

相关标签:
3条回答
  • 2021-01-21 02:29

    Yes, it's perfectly possible since defined functions are stored in variables like everything else.

    def foo():
        pass
    
    baz = bar = foo
    

    There is still some metadata relating to the original function (help(bar) will still mention foo), but it doesn't affect functionality.

    Another option is to use lambdas for one-liners:

    foo = bar = baz = lambda: None
    
    0 讨论(0)
  • 2021-01-21 02:35

    Functions do not intern in Python (i.e., automatically share multiple references to the same immutable object), but can share the same name:

    >>> def a(): pass
    ... 
    >>> a
    <function a at 0x101c892a8>
    >>> def b(): pass
    ... 
    >>> b
    <function b at 0x101c89320>
    >>> c=a
    >>> c
    <function a at 0x101c892a8>  # note the physical address is the same as 'a'
    

    So clearly you can do:

    >>> c=d=e=f=g=a
    >>> e
    <function a at 0x101c892a8>
    

    For the case of functions not yet defined, you can use a try/catch block by catching either a NameError:

    def default():
        print "default called"
    
    try:
        not_defined()
    except NameError:
        default()
    

    Or use a dict of funcs and catch the KeyError:

    funcs={"default": default}
    
    try:
        funcs['not_defined']()
    except KeyError:
        funcs['default']()      
    

    Or, you can do funcs.get(not_defined, default)() if you prefer that syntax with a dict of funcs.

    0 讨论(0)
  • 2021-01-21 02:46

    Yes, it is possible, and it is even possible to store them in lists using loops. For instance:

    l = []
    for i in range(10):
        l.append(lambda: None)
    

    And you can reference any of them through indices like l[index]()

    For example:

    c_events = 0
    c_about = 1
    l[c_events]()
    
    0 讨论(0)
提交回复
热议问题