Welcome, guest | Sign In | My Account | Store | Cart

Finally! This code allows you to import any activestate recipe right into your code!

Example:

>>> from activestate.recipe194373 import mreplace
>>> print mreplace('ectave steta racipas rock!', ('a', 'e'), ('e', 'a'))
active state recipes rock!

Save this as activestate.py

Python, 68 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# Copyright (c) 2010 Clovis Fabricio Costa - All rights reserved
# Distribution allowed under MIT license

"""
This module can give you an infinite arsenal of python functions and classes!

Save this as activestate.py
Then you can run:

>>> from activestate.recipe194373 import mreplace
>>> print mreplace('ectave steta racipas rock!', ('a', 'e'), ('e', 'a'))
active state recipes rock!

"""

import sys
import imp
import re
import urllib2

if __name__ == '__main__':
    raise ImportError("This module can't be executed directly - it should be imported")

class RecipeImporter(object):
    _regex = re.compile('%s\.recipe(\d+)' % re.escape(__name__))
    url = 'http://code.activestate.com/recipes/%s/download/1/'
    
    def find_module(self, name, pathlist):
        if name == __name__:
            return self
        base, sep, part = name.partition('.')
        if part.startswith('recipe'):
            return self

    def _create_module(self, modulename):
        mod = imp.new_module(modulename)
        mod.__file__ = "<(%s)>" % (modulename,)
        mod.__loader__ = self
        sys.modules[modulename] = mod
        return mod

    def load_module(self, fullname):
        if fullname in sys.modules:
            mod = sys.modules[fullname]
        else:
            mod = self._get_module(fullname)
        return mod

    def _get_module(self, fullname):
        if fullname == __name__:
            mod = self._create_module(fullname)
            mod.__path__ = []
        else:
            m = self._regex.match(fullname)
            if m:
                try:
                    code = urllib2.urlopen(self.url % m.groups()).read()
                except (urllib2.HTTPError, urllib2.URLError) as e:
                    raise ImportError("Can't load recipe %s: %s" %
                        (m.group(1), e))
                mod = self._create_module(fullname)
                exec code in mod.__dict__
            else:
                raise ImportError("Don't know how to import %r" % (fullname,))
        return mod

sys.meta_path.append(RecipeImporter())
__path__ = []

This is a joke. Don't use it in real code.

1 comment

Garel Alex 12 years, 5 months ago  # | flag

Ahah this is a funny one :-)