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 6627571
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T22:01:48+00:00 2026-05-25T22:01:48+00:00

I have some code in the form of a string and would like to

  • 0

I have some code in the form of a string and would like to make a module out of it without writing to disk.

When I try using imp and a StringIO object to do this, I get:

>>> imp.load_source('my_module', '', StringIO('print "hello world"'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: load_source() argument 3 must be file, not instance
>>> imp.load_module('my_module', StringIO('print "hello world"'), '', ('', '', 0))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: load_module arg#2 should be a file or None

How can I create the module without having an actual file? Alternatively, how can I wrap a StringIO in a file without writing to disk?

UPDATE:

NOTE: This issue is also a problem in python3.

The code I’m trying to load is only partially trusted. I’ve gone through it with ast and determined that it doesn’t import anything or do anything I don’t like, but I don’t trust it enough to run it when I have local variables running around that could get modified, and I don’t trust my own code to stay out of the way of the code I’m trying to import.

I created an empty module that only contains the following:

def load(code):
    # Delete all local variables
    globals()['code'] = code
    del locals()['code']

    # Run the code
    exec(globals()['code'])

    # Delete any global variables we've added
    del globals()['load']
    del globals()['code']

    # Copy k so we can use it
    if 'k' in locals():
        globals()['k'] = locals()['k']
        del locals()['k']

    # Copy the rest of the variables
    for k in locals().keys():
        globals()[k] = locals()[k]

Then you can import mymodule and call mymodule.load(code). This works for me because I’ve ensured that the code I’m loading does not use globals. Also, the global keyword is only a parser directive and can’t refer to anything outside of the exec.

This really is way too much work to import the module without writing to disk, but if you ever want to do this, I believe it’s the best way.

  • 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-25T22:01:49+00:00Added an answer on May 25, 2026 at 10:01 pm

    Here is how to import a string as a module (Python 2.x):

    import sys,imp
    
    my_code = 'a = 5'
    mymodule = imp.new_module('mymodule')
    exec my_code in mymodule.__dict__
    

    In Python 3, exec is a function, so this should work:

    import sys,imp
    
    my_code = 'a = 5'
    mymodule = imp.new_module('mymodule')
    exec(my_code, mymodule.__dict__)
    

    Now access the module attributes (and functions, classes etc) as:

    print(mymodule.a)
    >>> 5
    

    To ignore any next attempt to import, add the module to sys:

    sys.modules['mymodule'] = mymodule
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have some code available in some form of AST and I would like
I have some code that builds a string array using data from a form:
I have some code like this in a winforms app I was writing to
I have a bunch of code of the form: someVector.push_back(Foo(some name, 1.0, 3.1415926); someVector.push_back(Foo(different
I have some code like this: If key.Equals(search, StringComparison.OrdinalIgnoreCase) Then DoSomething() End If I
I have a registration page and would like to perform some validation (in addition
I have some code for starting a thread on the .NET CF 2.0: ThreadStart
I have some code which collects points (consed integers) from a loop which looks
I have some code in a javascript file that needs to send queries back
I have some code that gives a user id to a utility that then

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.