Retrieve module object from stack frame

Given a frame object, I need to get the corresponding module object. In other words, implement callers_module so this works:

import sys
from some_other_module import callers_module
assert sys.modules[__name__] is callers_module()

(That would be equivalent because I can generate a stack trace in the function for this test case. The imports are there simply to make that example complete and testable, and prevent callers_module from taking the shortcut of using __name__, since it's in a different module.)

I've attempted this:

import inspect
def callers_module():
  return inspect.currentframe().f_back

Which gets a frame object, on which f_code will give me a code object, but I can't find out how to get the corresponding module or its name (to use with sys.modules). If I could get function objects, those have a __module__ attribute (and also have code objects), but that's not present in the frame. Indeed, not all code objects belong to function objects, such as the code for my test case (with assert, above). The same can be said of frame/code objects not having a module—but many of them do, and in my case they will, so that doesn't need to be handled; however, a simple None or exception is fine in that case, too.

It feels like I'm missing something simple. What needs to be done for this to work?


Asked by: Owen128 | Posted: 30-11-2021






Answer 1

While inspect.getmodule works great, and I was indeed looking in the wrong place to find it, I found a slightly better solution for me:

def callers_module():
  module_name = inspect.currentframe().f_back.f_globals["__name__"]
  return sys.modules[module_name]

It still uses inspect.currentframe (which I prefer over the exactly identical sys._getframe), but doesn't invoke inspect's module-filename mapping (in inspect.getmodule).

Additionally, this question inspired an interesting way to manage __all__:

from export import export

@export
class Example: pass

@export
def example: pass

answer = 42
export.name("answer")

assert __all__ == ["Example", "example", "answer"]

Answered by: Rafael524 | Posted: 01-01-2022



Answer 2

import inspect
def callers_module():
   module = inspect.getmodule(inspect.currentframe().f_back)
   return module

Answered by: Darcy330 | Posted: 01-01-2022



Similar questions

Python module for HTTP: fill in forms, retrieve result

I'd like to use Python to access an HTTP website, fill out a form, submit the form, and retrieve the result. What modules are suitable for the task?


python - Odoo retrieve field from other module

Odoo 10 I am trying to copy a field from the products to the Sales order. The field in the products is called default_code. I've tried copying code from the Sales order module as its already getting unit price and tax etc. but cannot get it working. from odoo import api, models, fields class myfieldsinsaleorder(models.Model): _inherit = 'sale.order.line' squaremtr = fields.Float("SQ Meter...


python - Module to retrieve the inode of a file path?

I'm attempting to write a program that retrieves the file name, absolute path, etc., from a file path. Is there a module I can use in order to do that? Here's a snippet of my code import os filepath = "home/Documents/example.py" print("File Name: " + os.path.basename(filepath)) print("File Path: " + os.path.abspath(filepath)) print("inode: " + os.DirEntry.inode(filep...


python - Using RE to retrieve an ID

I am trying to use RE to match a changing ID and extract it. I am having some bother getting it working. The String is: m = 'Some Text That exists version 1.0.41.476 Fri Jun 4 16:50:56 EDT 2010' The code I have tried so far is: r = re.compile(r'(s*\s*)(\S+)') m = m.match(r) Can anyone help extract this string. Thanks


python - Retrieve User Entry IDs from MAPI

I extended the win32comext MAPI with the Interface IExchangeModifyTable to edit ACLs via the MAPI. I can modify existing ACL entries, but I stuck in adding new entries. I need the users entry ID to add it, according this C example (Example Source from MSDN) STDMETHODIMP AddUserPermission...


python regex retrieve only one group

I have juste a little experience with the regex, and now I have a little problem. I must retrieve the strings between the . So here is a sample : Categories: <a href="/car/2/page1.html">2</a>, <a href="/car/nissan/">nissan</a>,<a href="/car/all/page1.html">all</a> And this is my little regex: re.findall("""<a href=".*"&...


python - Retrieve header information from exe

I was wondering whether it would be possible to write a python script that retrieves header information from an .exe file. I tried googling but didn't really find any results that were usable. Thanks. Sept


python - Retrieve text inside #{ }

I have the following text: #{king} for a ##{day}, ##{fool} for a #{lifetime} And the following (broken) regex: [^#]#{[a-z]+} I want to match all #{words} but not the ##{words} (Doubling '#' acts like escaping) . Today I've noticed that the regex I have is ignoring the first word (refuses to match #{king}, but correctly ignores ##{day} and ##{fool}...


Python list of list retrieve data

Having a such list of list: data = [['a','x'], ['b','q'], ['c','z']] search = 'c' any(e[0] == search for e in data) This returns boolean value but what if I want to retrieve the first appearing other pair of seach variable (in other words I want to retrieve 'x' when I search 'a' )?


cgi - Python Pass List into Form and Retrieve as List

What is the best way to pass List via form in python (cgi). ListStr = ['State1', 'State2', 'State3'] TrVListStr = '##'.join(ListStr) print """ <form method="post"> <input type=hidden name="state_carry" value="""+TrVListStr+"""><br /> <input type="submit" value="Submit" /> </form> """ After submission I should have list as it was before submissi...


python - retrieve data from a column in mysql

As I know, the SELECT syntax is used for getting data from a row instead of column, here I have a column called time in a table, and I just want to select all the data in this time column, put them in an array, and use this array later. So how can I select a column of data and put them into an array?


python - apply a regex to retrieve a string

this might be a rookie question, but how would you efficiently apply regex expressions on strings to retrieve parts of the string ? I have a concrete parsing to solve as an example. If I have the string : STRING[(val1)-{val2}-!val3!] or STRING[{val2}-!val3!-(val1)] or STRING[!val3!-(val1)-{val2}] etc... (All 8 per...


Retrieve data from XML python


html - How can I retrieve the page title of a webpage using Python?

How can I retrieve the page title of a webpage (title html tag) using Python?


python - How to retrieve an element from a set without removing it?

Suppose the following: >>> s = set([1, 2, 3]) How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host. Quick and dirty: >>> elem = s.pop() >>> s.add(elem)


sql server - Python: Retrieve Image from MSSQL

I'm working on a Python project that retrieves an image from MSSQL. My code is able to retrieve the images successfully but with a fixed size of 63KB. if the image is greater than that size, it just brings the first 63KB from the image! The following is my code: #!/usr/bin/python import _mssql mssql=_mssql.connect('<ServerIP>','<UserID>','<Password>') mssql.select_db('<Database...


python - Best way to retrieve variable values from a text file?

Referring on this question, I have a similar -but not the same- problem.. On my way, I'll have some text file, structured like: var_a: 'home' var_b: 'car' var_c: 15.5 And I need that python read the file and then create a variable named var_a with value 'home', and so on. Example...


python - How to retrieve the selected text from the active window

I am trying to create a simple open source utility for windows using Python that can perform user-defined actions on the selected text of the currently active window. The utility should be activated using a pre-defined keyboard shortcut. Usage is partially outlined in the following example: The user selects some text using the mouse or the keyboard (in any application window)


python - How can I retrieve last x elements in Django

I am trying to retrieve the latest 5 posts (by post time) In the views.py, if I try blog_post_list = blogPosts.objects.all()[:5] It retreives the first 5 elements of the blogPosts objects, how can I reverse this to retreive the latest ones? Cheers


How do I retrieve Hotmail contacts with python

How can I retrieve contacts from hotmail with python? Is there any example?


linux - How to retrieve the process start time (or uptime) in python

How to retrieve the process start time (or uptime) in python in Linux? I only know, I can call "ps -p my_process_id -f" and then parse the output. But it is not cool.


python - Retrieve the two highest item from a list containing 100,000 integers

How can retrieve the two highest item from a list containing 100,000 integers without having to sort the entire list first?


c++ - How do I retrieve program output in Python?

I'm not a Perl user, but from this question deduced that it's exceedingly easy to retrieve the standard output of a program executed through a Perl script using something akin to: $version = `java -version`; How would I go about getting the same end result in Python? Does t...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top