-1

I was just curious if it was possible to create a module object inside python at runtime, without loading from any python file. The purpose of this would be to create a new empty namespace where other objects can then be stored subsequently. If this is not possible, is there another way to make and pass namespaces in python without saving to disk?

Nick Pandolfi
  • 993
  • 1
  • 8
  • 22
  • 1
    `module = types.ModuleType('module_name')`. – martineau Jun 13 '14 at 16:52
  • 1
    You can also make an importable module that replaces itself with an arbitrary object. There's an example of this illustrated in this [answer](http://stackoverflow.com/questions/3711657/can-i-prevent-modifying-an-object-in-python/3712574#3712574) of mine. – martineau Jun 13 '14 at 21:19

3 Answers3

2

You can use a class with static methods.

class Namespace:

    @staticmethod
    def greet():
        print "hello, world!"

In Python 3 the @staticmethod decorator is not needed.

kindall
  • 178,883
  • 35
  • 278
  • 309
2

You can use a simple class:

class Namespace:
    pass

Now, to create a new namespace:

n = Namespace()

To store things in the namespace:

n.foo = 1
def square(x):
  return x*x
n.squared = square

To refer to things in the namespace:

print n.foo
print n.squared(12)

To pass the namespace:

def func_requiring_a_namesapce(space):
    print space.foo

func_requiring_a_namespace(n)
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
1

You could use a dictionary?

Modules Are Like Dictionaries

You know how a dictionary is created and used and that it is a way to map one thing to another. That means if you have a dictionary with a key 'apple' and you want to get it then you do this:

mystuff = {'apple': "I AM APPLES!"}
print mystuff['apple']

Imagine if I have a module that I decide to name mystuff.py and I put a function in it called apple. Here's the module mystuff.py:

# this goes in mystuff.py
def apple():
    print "I AM APPLES!"

Once I have that, I can use that module with import and then access the apple function:

import mystuff

mystuff.apple()

I could also put a variable in it named tangerine like this:

def apple():
    print "I AM APPLES!"

# this is just a variable
tangerine = "Living reflection of a dream"

Then again I can access that the same way:

import mystuff

mystuff.apple()
print mystuff.tangerine

Refer back to the dictionary, and you should start to see how this is similar to using a dictionary, but the syntax is different. Let's compare:

mystuff['apple'] # get apple from dict
mystuff.apple() # get apple from the module
mystuff.tangerine # same thing, it's just a variable

In the case of the dictionary, the key is a string and the syntax is [key]. In the case of the module, the key is an identifier, and the syntax is .key. Other than that they are nearly the same thing.

Editied from here

Community
  • 1
  • 1
Noelkd
  • 7,686
  • 2
  • 29
  • 43