Noel Yap
Noel Yap

Reputation: 19768

How to access module-level names in Python?

I have the following code:

import m

def f(m=None):
    if m is None:
        k = m.M() # I want this m to refer to the imported module, not the parameter

I would really prefer to keep both the parameter name and the module name the same. Is there a way explicitly to refer to the module m?

Upvotes: 1

Views: 190

Answers (5)

Ben
Ben

Reputation: 71440

If it's just within this one function where the name clash occurs, you can always re-import the module within the function's scope and rename it to avoid the ambiguity.

import m

def f(m=None):
    import m as the_real_m
    if m is None:
        k = the_real_m.M()

The m in import m as the_real_m can be a little confusing, but here it's not a variable reference so there's no problem with it resolving to the wrong thing.

Personally I'd rather rename the function argument, but I realise with keyword arguments the name of the argument can be part of the interface exposed to other parts of the system, and keeping that with the clearest name possible can be more important.

Upvotes: 0

mata
mata

Reputation: 69032

a module in python is just another object, so the globals()-builtin will work fine:

import m

def f(m=None):
    if m is None:
        k = globals()['m'].M()

Upvotes: 1

Colin Valliant
Colin Valliant

Reputation: 1929

You can set the default value of the parameter m to be the attribute of the module, like this:

import m

def f(m=m.M):
    m()

However, shadowing a global (the module name) with a parameter is not the most Pythonic way to do it. More Pythonically, you'd name the parameter M, which matches the method M that it's going to be acting as.

import m

def f(M=m.M):
    M()

This way, you can still refer to other attributes of the module if you need to.

Upvotes: -2

Platinum Azure
Platinum Azure

Reputation: 46183

If you need the parameter the same as the usual module name, for code readability, but can tolerate the module being temporarily renamed for this scope, you can do something like this:

import m as _m

def f(m=None):
    if m is None:
        k = _m.M()

Not ideal, but probably the closest you can get.

Upvotes: 1

Noel Yap
Noel Yap

Reputation: 19768

If you don't mind changing the module's name only within the importing module, you could do:

import m as m_

def f(m=None):
    if m is None:
        k = m_.M()

Upvotes: 2

Related Questions