Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can a python function call a global function with the same name?

Can I call a global function from a function that has the same name?

For example:

def sorted(services):
    return {sorted}(services, key=lambda s: s.sortkey())

By {sorted} I mean the global sorted function. Is there a way to do this? I then want to call my function with the module name: service.sorted(services)

I want to use the same name, because it does the same thing as the global function, except that it adds a default argument.

like image 869
user13097 Avatar asked Dec 26 '14 13:12

user13097


2 Answers

Python's name-resolution scheme which sometimes is referred to as LEGB rule, implies that when you use an unqualified name inside a function, Python searches up to four scopes— First the local (L) scope, then the local scopes of any enclosing (E) defs and lambdas, then the global (G) scope, and finally the built-in (B) scope. (Note that it will stops the search as soon as it finds a match)

So when you use sorted inside the functions interpreter considers it as a Global name (your function name) so you will have a recursion function. if you want to access to built-in sorted you need to specify that for Python . by __builtin__ module (in Python-2.x ) and builtins in Python-3.x (This module provides direct access to all ‘built-in’ identifiers of Python)


python 2 :

import __builtin__
def sorted(services):
    return __builtin__.sorted(services, key=lambda s: s.sortkey())

python 3 :

import builtins
def sorted(services):
    return builtins.sorted(services, key=lambda s: s.sortkey())
like image 196
Mazdak Avatar answered Nov 11 '22 13:11

Mazdak


Store the original function reference before define a new function with the same name.

original_sorted = sorted

def sorted(services):
    return original_sorted(services, key=lambda s: s.sortkey())

For, builtin functions like sorted, you can access the function using __builtin__ module (In Python 3.x, builtins module):

import __builtin__

def sorted(services):
    return __builtin__.sorted(services, key=lambda s: s.sortkey())

But, both which shadow builtin function is not recommended. Choose other name if possible.

like image 27
falsetru Avatar answered Nov 11 '22 12:11

falsetru