Package flumotion :: Package common :: Module fraction
[hide private]

Source Code for Module flumotion.common.fraction

 1  # -*- Mode: Python; test-case-name: flumotion.test.test_config -*- 
 2  # vi:si:et:sw=4:sts=4:ts=4 
 3  # 
 4  # Flumotion - a streaming media server 
 5  # Copyright (C) 2008 Fluendo, S.L. (www.fluendo.com). 
 6  # All rights reserved. 
 7   
 8  # This file may be distributed and/or modified under the terms of 
 9  # the GNU General Public License version 2 as published by 
10  # the Free Software Foundation. 
11  # This file is distributed without any warranty; without even the implied 
12  # warranty of merchantability or fitness for a particular purpose. 
13  # See "LICENSE.GPL" in the source distribution for more information. 
14   
15  # Licensees having purchased or holding a valid Flumotion Advanced 
16  # Streaming Server license may use this file in accordance with the 
17  # Flumotion Advanced Streaming Server Commercial License Agreement. 
18  # See "LICENSE.Flumotion" in the source distribution for more information. 
19   
20  # Headers in this file shall remain intact. 
21   
22  """convert to and from fractions 
23  """ 
24   
25  __version__ = "$Rev: 7036 $" 
26   
27 -def fractionFromValue(value):
28 """ 29 Converts a value to a fraction 30 31 @param value: the value to convert to a tuple 32 @type value: one of 33 - string, unicode 34 - number, eg int/float/long 35 - two sized tuple 36 37 @returns: the fraction 38 @rtype: a two sized tuple with 2 integers 39 """ 40 def _frac(num, denom=1): 41 return int(num), int(denom)
42 43 if isinstance(value, basestring): 44 noSlashes = value.count('/') 45 if noSlashes == 0: 46 parts = [value] 47 elif noSlashes == 1: 48 parts = value.split('/') 49 else: 50 raise ValueError('Expected at most one /, not %r' % (value,)) 51 return _frac(*parts) 52 elif isinstance(value, tuple): 53 if len(value) != 2: 54 raise ValueError( 55 "Can only convert two sized tuple to fraction") 56 return value 57 elif isinstance(value, (float, int, long)): 58 return _frac(value) 59 else: 60 raise ValueError( 61 "Cannot convert %r of type %s to a fraction" % ( 62 value, type(value).__name__)) 63
64 -def fractionAsFloat(value):
65 """ 66 Converts a fraction to a float 67 @param value: the value to convert to a tuple, can be one of: 68 @type value: a two sized tuple with 2 integers 69 @returns: fraction representation in float 70 @rtype: float 71 """ 72 assert type(value) in [list, tuple], value 73 assert len(value) == 2, value 74 return float(value[0]) / float(value[1])
75
76 -def fractionAsString(value):
77 """ 78 Converts a fraction to a string 79 @param value: the value to convert to a tuple, can be one of: 80 @type value: a two sized tuple with 2 integers 81 @returns: fraction representation as a string 82 @rtype: string 83 """ 84 assert type(value) in [list, tuple], value 85 assert len(value) == 2, value 86 return '%s/%s' % value
87