Cleaning some unnecessary whitespace, overall cleanup of various source codes.

This commit is contained in:
Griatch 2012-03-30 23:47:22 +02:00
parent d4c97d7df8
commit c0322c9eae
27 changed files with 1342 additions and 1318 deletions

View file

@ -2,7 +2,7 @@
General helper functions that don't fit neatly under any given category.
They provide some useful string and conversion methods that might
be of use when designing your own game.
be of use when designing your own game.
"""
@ -27,7 +27,7 @@ def is_iter(iterable):
def make_iter(obj):
"Makes sure that the object is always iterable."
if not hasattr(obj, '__iter__'): return [obj]
return obj
return obj
def fill(text, width=78, indent=0):
"""
@ -53,8 +53,8 @@ def crop(text, width=78, suffix="[...]"):
ltext = len(to_str(text))
if ltext <= width:
return text
else:
lsuffix = len(suffix)
else:
lsuffix = len(suffix)
return "%s%s" % (text[:width-lsuffix], suffix)
def dedent(text):
@ -63,7 +63,7 @@ def dedent(text):
of a paragraph. This is useful for preserving
triple-quoted string indentation while still
shifting it all to be next to the left edge of
the display.
the display.
"""
if not text:
return ""
@ -92,11 +92,11 @@ def wildcard_to_regexp(instring):
regexp_string += "$"
return regexp_string
def time_format(seconds, style=0):
"""
Function to return a 'prettified' version of a value in seconds.
Style 0: 1d 08:30
Style 1: 1d
Style 2: 1 day, 8 hours, 30 minutes, 10 seconds
@ -105,15 +105,15 @@ def time_format(seconds, style=0):
seconds = 0
else:
# We'll just use integer math, no need for decimal precision.
seconds = int(seconds)
seconds = int(seconds)
days = seconds / 86400
seconds -= days * 86400
hours = seconds / 3600
seconds -= hours * 3600
minutes = seconds / 60
seconds -= minutes * 60
if style is 0:
"""
Standard colon-style output.
@ -122,7 +122,7 @@ def time_format(seconds, style=0):
retval = '%id %02i:%02i' % (days, hours, minutes,)
else:
retval = '%02i:%02i' % (hours, minutes,)
return retval
elif style is 1:
"""
@ -155,8 +155,8 @@ def time_format(seconds, style=0):
if minutes == 1:
minutes_str = '%i minute ' % minutes
else:
minutes_str = '%i minutes ' % minutes
retval = '%s%s%s' % (days_str, hours_str, minutes_str)
minutes_str = '%i minutes ' % minutes
retval = '%s%s%s' % (days_str, hours_str, minutes_str)
elif style is 3:
"""
Full-detailed, long-winded format. Includes seconds.
@ -176,20 +176,20 @@ def time_format(seconds, style=0):
if minutes == 1:
minutes_str = '%i minute ' % minutes
else:
minutes_str = '%i minutes ' % minutes
if minutes or seconds > 0:
minutes_str = '%i minutes ' % minutes
if minutes or seconds > 0:
if seconds == 1:
seconds_str = '%i second ' % seconds
else:
seconds_str = '%i seconds ' % seconds
retval = '%s%s%s%s' % (days_str, hours_str, minutes_str, seconds_str)
return retval
return retval
def datetime_format(dtobj):
"""
Takes a datetime object instance (e.g. from django's DateTimeField)
and returns a string describing how long ago that date was.
and returns a string describing how long ago that date was.
"""
year, month, day = dtobj.year, dtobj.month, dtobj.day
@ -197,7 +197,7 @@ def datetime_format(dtobj):
now = datetime.datetime.now()
if year < now.year:
# another year
# another year
timestring = str(dtobj.date())
elif dtobj.date() < now.date():
# another date, same year
@ -205,9 +205,9 @@ def datetime_format(dtobj):
elif hour < now.hour - 1:
# same day, more than 1 hour ago
timestring = "%02i:%02i" % (hour, minute)
else:
else:
# same day, less than 1 hour ago
timestring = "%02i:%02i:%02i" % (hour, minute, second)
timestring = "%02i:%02i:%02i" % (hour, minute, second)
return timestring
def host_os_is(osname):
@ -223,12 +223,12 @@ def get_evennia_version():
Check for the evennia version info.
"""
try:
with open(settings.BASE_PATH + os.sep + "VERSION") as f:
with open(settings.BASE_PATH + os.sep + "VERSION") as f:
return "%s-r%s" % (f.read().strip(), os.popen("hg id -i").read().strip())
return
return
except IOError:
return "Unknown version"
def pypath_to_realpath(python_path, file_ending='.py'):
"""
Converts a path on dot python form (e.g. 'src.objects.models') to
@ -238,17 +238,17 @@ def pypath_to_realpath(python_path, file_ending='.py'):
pathsplit = python_path.strip().split('.')
if not pathsplit:
return python_path
path = settings.BASE_PATH
path = settings.BASE_PATH
for directory in pathsplit:
path = os.path.join(path, directory)
if file_ending:
return "%s%s" % (path, file_ending)
return path
return "%s%s" % (path, file_ending)
return path
def dbref(dbref):
"""
Converts/checks if input is a valid dbref Valid forms of dbref
(database reference number) are either a string '#N' or
(database reference number) are either a string '#N' or
an integer N. Output is the integer part.
"""
if isinstance(dbref, basestring):
@ -256,11 +256,11 @@ def dbref(dbref):
try:
dbref = int(dbref)
if dbref < 1:
return None
return None
except Exception:
return None
return dbref
return None
return None
def to_unicode(obj, encoding='utf-8', force_string=False):
"""
@ -268,7 +268,7 @@ def to_unicode(obj, encoding='utf-8', force_string=False):
one needs to encode it back to utf-8 before writing to disk or
printing. Note that non-string objects are let through without
conversion - this is important for e.g. Attributes. Use
force_string to enforce conversion of objects to string. .
force_string to enforce conversion of objects to string. .
"""
if force_string and not isinstance(obj, basestring):
@ -279,28 +279,28 @@ def to_unicode(obj, encoding='utf-8', force_string=False):
elif hasattr(obj, '__unicode__'):
obj = obj.__unicode__()
else:
# last resort
# last resort
obj = str(obj)
if isinstance(obj, basestring) and not isinstance(obj, unicode):
try:
obj = unicode(obj, encoding)
return obj
return obj
except UnicodeDecodeError:
for alt_encoding in ENCODINGS:
for alt_encoding in ENCODINGS:
try:
obj = unicode(obj, alt_encoding)
return obj
except UnicodeDecodeError:
pass
pass
raise Exception("Error: '%s' contains invalid character(s) not in %s." % (obj, encoding))
return obj
return obj
def to_str(obj, encoding='utf-8', force_string=False):
"""
This encodes a unicode string back to byte-representation,
This encodes a unicode string back to byte-representation,
for printing, writing to disk etc. Note that non-string
objects are let through without modification - this is
objects are let through without modification - this is
required e.g. for Attributes. Use force_string to force
conversion of objects to strings.
"""
@ -313,7 +313,7 @@ def to_str(obj, encoding='utf-8', force_string=False):
elif hasattr(obj, '__unicode__'):
obj = obj.__unicode__()
else:
# last resort
# last resort
obj = str(obj)
if isinstance(obj, basestring) and isinstance(obj, unicode):
@ -334,14 +334,14 @@ def validate_email_address(emailaddress):
"""
Checks if an email address is syntactically correct.
(This snippet was adapted from
(This snippet was adapted from
http://commandline.org.uk/python/email-syntax-check.)
"""
emailaddress = r"%s" % emailaddress
domains = ("aero", "asia", "biz", "cat", "com", "coop",
"edu", "gov", "info", "int", "jobs", "mil", "mobi", "museum",
domains = ("aero", "asia", "biz", "cat", "com", "coop",
"edu", "gov", "info", "int", "jobs", "mil", "mobi", "museum",
"name", "net", "org", "pro", "tel", "travel")
# Email address must be more than 7 characters in total.
@ -372,11 +372,11 @@ def validate_email_address(emailaddress):
def inherits_from(obj, parent):
"""
Takes an object and tries to determine if it inherits at any distance
Takes an object and tries to determine if it inherits at any distance
from parent. What differs this function from e.g. isinstance()
is that obj may be both an instance and a class, and parent
< may be an instance, a class, or the python path to a class (counting
from the evennia root directory).
from the evennia root directory).
"""
if callable(obj):
@ -384,7 +384,7 @@ def inherits_from(obj, parent):
obj_paths = ["%s.%s" % (mod.__module__, mod.__name__) for mod in obj.mro()]
else:
obj_paths = ["%s.%s" % (mod.__module__, mod.__name__) for mod in obj.__class__.mro()]
if isinstance(parent, basestring):
# a given string path, for direct matching
parent_path = parent
@ -400,56 +400,56 @@ def format_table(table, extra_space=1):
"""
Takes a table of collumns: [[val,val,val,...], [val,val,val,...], ...]
where each val will be placed on a separate row in the column. All
collumns must have the same number of rows (some positions may be
empty though).
collumns must have the same number of rows (some positions may be
empty though).
The function formats the columns to be as wide as the widest member
of each column.
extra_space defines how much extra padding should minimum be left between
collumns.
print the resulting list e.g. with
extra_space defines how much extra padding should minimum be left between
collumns.
print the resulting list e.g. with
for ir, row in enumarate(ftable):
if ir == 0:
# make first row white
if ir == 0:
# make first row white
string += "\n{w" + ""join(row) + "{n"
else:
string += "\n" + "".join(row)
print string
print string
"""
if not table:
return [[]]
max_widths = [max([len(str(val)) for val in col]) for col in table]
ftable = []
for irow in range(len(table[0])):
ftable.append([str(col[irow]).ljust(max_widths[icol]) + " " * extra_space
ftable = []
for irow in range(len(table[0])):
ftable.append([str(col[irow]).ljust(max_widths[icol]) + " " * extra_space
for icol, col in enumerate(table)])
return ftable
def run_async(async_func, at_return=None, at_err=None):
"""
This wrapper will use Twisted's asynchronous features to run a slow
function using a separate reactor thread. In effect this means that
the server will not be blocked while the slow process finish.
function using a separate reactor thread. In effect this means that
the server will not be blocked while the slow process finish.
Use this function with restrain and only for features/commands
that you know has no influence on the cause-and-effect order of your
game (commands given after the async function might be executed before
it has finished).
async_func() - function that should be run asynchroneously
at_return(r) - if given, this function will be called when async_func returns
value r at the end of a successful execution
at_err(e) - if given, this function is called if async_func fails with an exception e.
at_err(e) - if given, this function is called if async_func fails with an exception e.
use e.trap(ExceptionType1, ExceptionType2)
"""
# create deferred object
# create deferred object
deferred = threads.deferToThread(async_func)
if at_return:
deferred.addCallback(at_return)
@ -458,7 +458,7 @@ def run_async(async_func, at_return=None, at_err=None):
# always add a logging errback as a last catch
def default_errback(e):
from src.utils import logger
logger.log_trace(e)
logger.log_trace(e)
deferred.addErrback(default_errback)
@ -491,7 +491,7 @@ def check_evennia_dependencies():
import twisted
tversion = twisted.version.short()
if tversion < twisted_min:
errstring += "\n WARNING: Twisted %s found. Evennia recommends version %s or higher." % (twisted.version.short(), twisted_min)
errstring += "\n WARNING: Twisted %s found. Evennia recommends version %s or higher." % (twisted.version.short(), twisted_min)
except ImportError:
errstring += "\n ERROR: Twisted does not seem to be installed."
no_error = False
@ -508,12 +508,12 @@ def check_evennia_dependencies():
# South
try:
import south
sversion = south.__version__
sversion = south.__version__
if sversion < south_min:
errstring += "\n WARNING: South version %s found. Evennia recommends version %s or higher." % (sversion, south_min)
errstring += "\n WARNING: South version %s found. Evennia recommends version %s or higher." % (sversion, south_min)
except ImportError:
pass
# IRC support
# IRC support
if settings.IRC_ENABLED:
try:
import twisted.words
@ -521,7 +521,7 @@ def check_evennia_dependencies():
errstring += "\n ERROR: IRC is enabled, but twisted.words is not installed. Please install it."
errstring += "\n Linux Debian/Ubuntu users should install package 'python-twisted-words', others"
errstring += "\n can get it from http://twistedmatrix.com/trac/wiki/TwistedWords."
no_error = False
no_error = False
errstring = errstring.strip()
if errstring:
print "%s\n %s\n%s" % ("-"*78, errstring, '-'*78)
@ -534,21 +534,21 @@ def has_parent(basepath, obj):
if basepath == "%s.%s" % (cls.__module__, cls.__name__))
except (TypeError, AttributeError):
# this can occur if we tried to store a class object, not an
# instance. Not sure if one should defend against this.
return False
# instance. Not sure if one should defend against this.
return False
def mod_import(mod_path, propname=None):
"""
Takes filename of a module (a python path or a full pathname)
and imports it. If property is given, return the named
property from this module instead of the module itself.
and imports it. If property is given, return the named
property from this module instead of the module itself.
"""
def log_trace(errmsg=None):
"""
Log a traceback to the log. This should be called
from within an exception. errmsg is optional and
adds an extra line with added info.
adds an extra line with added info.
"""
from traceback import format_exc
from twisted.python import log
@ -557,7 +557,7 @@ def mod_import(mod_path, propname=None):
tracestring = format_exc()
if tracestring:
for line in tracestring.splitlines():
log.msg('[::] %s' % line)
log.msg('[::] %s' % line)
if errmsg:
try:
errmsg = to_str(errmsg)
@ -569,10 +569,10 @@ def mod_import(mod_path, propname=None):
if not mod_path:
return None
# first try to import as a python path
try:
try:
mod = __import__(mod_path, fromlist=["None"])
except ImportError:
# try absolute path import instead
if not os.path.isabs(mod_path):
@ -583,13 +583,13 @@ def mod_import(mod_path, propname=None):
try:
result = imp.find_module(modname, [path])
except ImportError:
log_trace("Could not find module '%s' (%s.py) at path '%s'" % (modname, modname, path))
return
log_trace("Could not find module '%s' (%s.py) at path '%s'" % (modname, modname, path))
return
try:
mod = imp.load_module(modname, *result)
except ImportError:
log_trace("Could not find or import module %s at path '%s'" % (modname, path))
mod = None
mod = None
# we have to close the file handle manually
result[0].close()
@ -598,16 +598,16 @@ def mod_import(mod_path, propname=None):
try:
mod_prop = mod.__dict__[to_str(propname)]
except KeyError:
log_trace("Could not import property '%s' from module %s." % (propname, mod_path))
return None
log_trace("Could not import property '%s' from module %s." % (propname, mod_path))
return None
return mod_prop
return mod
return mod
def variable_from_module(modpath, variable, default=None):
"""
Retrieve a given variable from a module. The variable must be
defined globally in the module. This can be used to implement
arbitrary plugin imports in the server.
arbitrary plugin imports in the server.
If module cannot be imported or variable not found, default
is returned.
@ -627,7 +627,7 @@ def string_from_module(modpath, variable=None, default=None):
This obtains a string from a given module python path. Using a
specific variable name will also retrieve non-strings.
The variable must be global within that module - that is, defined
in the outermost scope of the module. The value of the variable
will be returned. If not found, default is returned. If no variable is
@ -640,8 +640,8 @@ def string_from_module(modpath, variable=None, default=None):
if variable:
return mod.__dict__.get(variable, default)
else:
mvars = [val for key, val in mod.__dict__.items()
if not key.startswith('_') and isinstance(val, basestring)]
mvars = [val for key, val in mod.__dict__.items()
if not key.startswith('_') and isinstance(val, basestring)]
if not mvars:
return default
return mvars[random.randint(0, len(mvars)-1)]
@ -651,8 +651,8 @@ def init_new_player(player):
Helper method to call all hooks, set flags etc on a newly created
player (and potentially their character, if it exists already)
"""
# the FIRST_LOGIN flags are necessary for the system to call
# the relevant first-login hooks.
# the FIRST_LOGIN flags are necessary for the system to call
# the relevant first-login hooks.
if player.character:
player.character.db.FIRST_LOGIN = True
player.db.FIRST_LOGIN = True
player.character.db.FIRST_LOGIN = True
player.db.FIRST_LOGIN = True