Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7175113
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T16:12:50+00:00 2026-05-28T16:12:50+00:00

I am trying to create a helper function to read a file and mock

  • 0

I am trying to create a helper function to read a file and mock out all imports for a unit test. I have to read the file vs import since i dont have those things on python path.

Example code:


#module.py
import com.stackoverflow.question
from com.stackoverflow.util import test_func
from com.stackoverflow.util import TestClass

#magic helper: what i want
magic = process('<path_to>/module.py')
for module in magic.modules_as_strings():
    #todo  would have to recuirsively add each path
    # so i would first create com, then com.stackoverflow, etc
    setattr(self, module, StubModules(module)
for obj in magic.sink:
    #these would be "from"  from x import Y
    #its basically just creating self.Y = object
    setattr(self, object)

Above is the mock code, I am really looking for the best way to just tokenize the file for “from/import statements”

That make sense? I know I could read the file line by line, but I was hoping for a cleaner/concise way.

Let me know if you have any questions.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T16:12:51+00:00Added an answer on May 28, 2026 at 4:12 pm

    Using the AST module, it is pretty easy:

    import ast
    from collections import namedtuple
    
    Import = namedtuple("Import", ["module", "name", "alias"])
    
    def get_imports(path):
        with open(path) as fh:        
           root = ast.parse(fh.read(), path)
    
        for node in ast.iter_child_nodes(root):
            if isinstance(node, ast.Import):
                module = []
            elif isinstance(node, ast.ImportFrom):  
                module = node.module.split('.')
            else:
                continue
    
            for n in node.names:
                yield Import(module, n.name.split('.'), n.asname)
    

    For a module like this:

    from coco import bunny
    from coco.bungy import carrot
    from meta import teta
    from rocket import spaceship as sp
    import bingo
    import com.stackoverflow
    import motorbike as car
    import module1, module2
    
    s="a random variable"
    
    def func():
        """And a function"""
    

    The output is:

    >>> for imp in get_imports("/path/to/file.py"): print imp
    Import(module=['coco'], name=['bunny'], alias=None)
    Import(module=['coco', 'bungy'], name=['carrot'], alias=None)
    Import(module=['meta'], name=['teta'], alias=None)
    Import(module=['rocket'], name=['spaceship'], alias='sp')
    Import(module=[], name=['bingo'], alias=None)
    Import(module=[], name=['com', 'stackoverflow'], alias=None)
    Import(module=[], name=['motorbike'], alias='car')
    Import(module=[], name=['module1'], alias=None)
    Import(module=[], name=['module2'], alias=None)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Having a problem trying to create a function, as part of a BizTalk helper
I am trying to create a little helper application, one scenario is file duplication
I was trying to create this helper function in C# that returns the first
I am trying to create a helper function (eg in application_helper.rb ) that generates
I am trying to create my own helper function in ASP.NET MVC 3. Not
I'm trying to create a simple helper module in rails, and I'm stumped on
I'm trying to create a custom HTML Helper to help simplify my masterpages menu,
Trying to create a user account in a test. But getting a Object reference
I am trying to create a photo upload function for a website, and there
I am trying to create an expression tree containing a function call to a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.