How do I define a global function in Python?

Is there a way to define a function that is global from within the class (or from within another function, in fact)? Something similar to defining a global variable.

+3


source to share


2 answers


Functions are added to the current namespace like any other name. This means that you can use a keyword global

inside a function or method:

def create_global_function():
    global foo
    def foo(): return 'bar'

      

The same goes for the body or method of a class:

class ClassWithGlobalFunction:
    global spam
    def spam(): return 'eggs'

    def method(self):
        global monty
        def monty(): return 'python'

      



with the difference that it spam

will be determined immediately when the bodies of the top-level instance are executed on import.

As with all uses global

, you probably want to rethink the problem and find another way to solve it. For example, you could return the generated function, eg.

Demo:

>>> def create_global_function():
...     global foo
...     def foo(): return 'bar'
... 
>>> foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
>>> create_global_function()
>>> foo
<function foo at 0x102a0c7d0>
>>> foo()
'bar'
>>> class ClassWithGlobalFunction:
...     global spam
...     def spam(): return 'eggs'
...     def method(self):
...         global monty
...         def monty(): return 'python'
... 
>>> spam
<function spam at 0x102a0cb18>
>>> spam()
'eggs'
>>> monty
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'monty' is not defined
>>> ClassWithGlobalFunction().method()
>>> monty()
'python'

      

+14


source


You can use global to declare a global function inside a class. The problem with this is that you cannot use it with class scope so that it can also declare it outside of the class.



class X:
  global d
  def d():
    print 'I might be defined in a class, but I\'m global'

>> X.d

   Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   AttributeError: 'X' object has no attribute 'd'

>> d()

I might be defined in a class, but I'm global

      

+7


source







All Articles