File: GenericTools.py

package info (click to toggle)
python-biopython 1.42-2
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 17,584 kB
  • ctags: 12,272
  • sloc: python: 80,461; xml: 13,834; ansic: 7,902; cpp: 1,855; sql: 1,144; makefile: 203
file content (174 lines) | stat: -rwxr-xr-x 4,101 bytes parent folder | download | duplicates (2)
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
#!/usr/bin/env python
#
# Copyright 2002 by Michael Hoffman.  All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license.  Please see the LICENSE file that should have been included
# as part of this package.

"""
Docstring
"""

from __future__ import generators

__version__ = "$Revision: 1.3 $"
# $Source: /home/repository/biopython/biopython/Bio/GFF/GenericTools.py,v $

import exceptions
import os
import sys
import tempfile

class AppendableListDictionary(dict):
    """
    a dictionary of lists
    """
    def append_to(self, key, value):
        try:
            dict.__getitem__(self, key).append(value)
        except KeyError:
            self[key] = [value]

class ForgivingDictionary(AppendableListDictionary):
    def __getitem__(self, key):
        try:
            return dict.__getitem__(self, key)
        except KeyError:
            return None

class VerboseDict(dict):
    def __str__(self):
        dict_copy = {}
        for key in self:
            dict_copy[key] = str(self[key])
        return str(dict_copy)

class VerboseList(list):
    def __str__(self):
        return str(map(lambda x: str(x), self))

class TempFile(file):
    def __init__(self, suffix = ".python-temp", keep = 0):
        self.removed = 0
        self.keep = keep
        # XXX: this is a race condition:
        file.__init__(self, tempfile.mktemp(suffix), "w")

    def __del__(self):
        self.remove()

    def remove(self):
        if self.keep == 0:
            if self.removed == 0:
                try:
                    try:
                        self.close()
                        os.remove(self.name)
                    finally:
                        self.removed = 1
                except exceptions.OSError:
                    pass

class SurrogateNotInitedError(exceptions.AttributeError):
    pass

class Surrogate(object):
    """
    the data is stored in _data
    """
    def __init__(self, data):
        self._data = data

    def __getattr__(self, name):
        if name == "_data":
            raise SurrogateNotInitedError, name
        else:
            try:
                return getattr(self._data, name)
            except SurrogateNotInitedError:
                raise SurrogateNotInitedError, name


def defline_text(defline):
    if defline[0] == ">":
        return defline[1:]
    else:
        return defline

def is_nestable(x):
    """
    Returns 1 if x is a tuple or list (sequence types that can nest)
    Returns 0 otherwise

    >>> is_nestable("string")
    0
    >>> is_nestable((0,))
    1
    >>> is_nestable(range(5))
    1
    """
    return isinstance(x, (tuple, list))

def dump_list(l):
    """
    returns strings of list
    """
    try:
        return '[%s]' % ', '.join(map(str, l))
    except TypeError:
        return str(l)

def reverse_text(text):
    """
    >>> reverse_text('abracadabra')
    'arbadacarba'
    """
    l = list(text)
    l.reverse()
    return ''.join(l)

def enumerate(collection):
    """
    Generates an indexed series:  (0,coll[0]), (1,coll[1]) ...

    >>> for i, item in enumerate([4, 5, 6]):
    ...     print "%d: %d" % (i, item)
    0: 4
    1: 5
    2: 6
    """
    i = 0
    for item in collection:
        yield (i, item)
        i += 1

class ArgsParser(object):
    """
    >>> unparsed_args = ["moocow"]
    >>> args = ArgsParser(unparsed_args, [('infile', 'defaultin'), ('outfile', 'defaultout')])
    >>> args.infile
    'moocow'
    >>> args.outfile
    'defaultout'
    """
    def __init__(self, args, defaults):
        for i, default in enumerate(defaults):
            try:
                self.__dict__[default[0]] = args[i]
                continue
            except TypeError:
                pass
            except IndexError:
                pass
            self.__dict__[default[0]] = default[1]

def all(iterator):
    return [item for item in iterator]

def _test(*args, **keywds):
    import doctest, sys
    doctest.testmod(sys.modules[__name__], *args, **keywds)

if __name__ == "__main__":
    if __debug__:
        _test()