Is there are a way to replace python import with actual sources?

2024/11/16 22:23:36

I am having python files with the import statements which I would like to replace into the actual code placed in the foo.py.

For instance, with the in file:

from foo import Barbar = Bar()
print bar

I would like to out file below:

# source of Bar class.bar = Bar()
print bar

How can I perform such imports replacement ?

Answer

I suggest you to use the ast.NodeTransformer in order to accomplish such import replacement.

AST provides way to interact with the python code as with the trees of the Python abstract syntax grammar.

The ast.NodeTransformer can be used to traverse through your code and identifying ImportFrom node ( the code parsed with ast is represented as the tree of nodes). After identifying ImportFrom node you can replace it with group of nodes which correspond to the source code of the Bar class, which lead to your goal.

Please see code below which describes approach described below:

from ast import NodeTransformer, parse, fix_missing_locationsimport astorclass FromImportTransformer(NodeTransformer):""" General from imports transformer. """def visit_ImportFrom(self, node):new_node = self.get_sources(node)# Replace node.fix_missing_locations(node)return nodedef get_sources(self, node):""" Accepts importFrom node and build new ast tree from the sources described in import. """raise NotImplementeddef transform_imports(self, source_file):with open(source_file) as original_sources:sources = original_sources.read()root = parse(sources, source_file)try:root = FromImportTransformer().visit(root)except Exception as exc:raise excsources = astor.to_source(root, indent_with=' ' * 4, add_line_information=False)return processed_sourcespath_to_in_sources = '/tmp/in.py'
path_to_out_sources = '/tmp/out.py'
processed_sources = transform_imports(path_to_in_sources)with open(path_to_out_sources, 'wb+') as out:out.write(processed_sources)

NOTE 1: I suggest you to use the exec in order to compile sources with correct globals and locals dict.

NOTE 2: Take into account that you will need to handle nested imports ( if foo file stores imports you wish to replace to).

NOTE 3: I've used astor to convert code from ast tree into the python code.

https://en.xdnf.cn/q/119141.html

Related Q&A

How to use supported numpy and math functions with CUDA in Python?

According to numba 0.51.2 documentation, CUDA Python supports several math functions. However, it doesnt work in the following kernel function: @cuda.jit def find_angle(angles):i, j = cuda.grid(2)if i …

PYTHON - Remove tuple from list if contained in another list

I have a list of tuples:list_of_tuples = [(4, 35.26), (1, 48.19), (5, 90.0), (3, 90.0)]tuple[0] is an item_IDtuple[1] is an angleI have a list of item_IDs I want to remove/ignore from the list:ignore_I…

How to run a ij loop in Python, and not repeat (j,i) if (i,j) has already been done?

I am trying to implement an "i not equal to j" (i<j) loop, which skips cases where i = j, but I would further like to make the additional requirement that the loop does not repeat the perm…

Split a string with multiple delimiters

I have the string "open this and close that" and I want to obtain "open this and" and "close that". This is my best attempt:>>>print( re.split(r[ ](?=(open|clos…

Extracting a string between 2 chracters using python [duplicate]

This question already has answers here:Python-get string between to characters(4 answers)Closed 7 years ago.I need a Python regex to give me all the strings between ~ and ^ from a string like this:~~~~…

remove empty line printed from hive query output using python

i am performing a hive query and storing the output in a tsv file in the local FS. I am running a for loop for the hive query and passing different parameters. If the hive query returns no output once …

.exceptions.WebDriverException: Message: Can not connect to the Service

struggling to find a solution all over, have latest chrome 117 and also downloaded chromedriver and used the path accordingly in script also tried with chrome browser Although it opens the browser but …

How to call a previous function in a new function? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in the help center.Cl…

Using simpleauth to login in with GAE

This question is in the reference of this. As suggested I am using simpleauth to login via linkedin. Now I am having trouble with the redirect_uri. I have successfully deployed dev_appserver.py example…

How do i force my code to print in python

Im having trouble trying to work out an error in my code. It isnt printing the final product and leaving a blank space.playing = True string = "" Alphabet = (z,a,b, c, d, e, f, g, h, i, j, k,…