Run 2to3.

This commit is contained in:
Ryan Stein 2017-10-29 13:40:30 -04:00
parent a5a8d9dd57
commit 6fa280b9fd
157 changed files with 976 additions and 976 deletions

View file

@ -6,7 +6,7 @@ Created for the Player->Account renaming
Griatch 2017, released under the BSD license.
"""
from __future__ import print_function
import re
import sys
@ -130,7 +130,7 @@ def rename_in_tree(path, in_list, out_list, excl_list, fileend_list, is_interact
replacements in each file.
"""
repl_mapping = zip(in_list, out_list)
repl_mapping = list(zip(in_list, out_list))
for root, dirs, files in os.walk(path):
@ -155,13 +155,13 @@ def rename_in_tree(path, in_list, out_list, excl_list, fileend_list, is_interact
for src, dst in repl_mapping:
new_file = _case_sensitive_replace(new_file, src, dst)
if new_file != file:
inp = raw_input(_green("Rename %s\n -> %s\n Y/[N]? > " % (file, new_file)))
inp = input(_green("Rename %s\n -> %s\n Y/[N]? > " % (file, new_file)))
if inp.upper() == 'Y':
new_full_path = os.path.join(root, new_file)
try:
os.rename(full_path, new_full_path)
except OSError as err:
raw_input(_red("Could not rename - %s (return to skip)" % err))
input(_red("Could not rename - %s (return to skip)" % err))
else:
print("... Renamed.")
else:
@ -171,12 +171,12 @@ def rename_in_tree(path, in_list, out_list, excl_list, fileend_list, is_interact
for src, dst in repl_mapping:
new_root = _case_sensitive_replace(new_root, src, dst)
if new_root != root:
inp = raw_input(_green("Dir Rename %s\n -> %s\n Y/[N]? > " % (root, new_root)))
inp = input(_green("Dir Rename %s\n -> %s\n Y/[N]? > " % (root, new_root)))
if inp.upper() == 'Y':
try:
os.rename(root, new_root)
except OSError as err:
raw_input(_red("Could not rename - %s (return to skip)" % err))
input(_red("Could not rename - %s (return to skip)" % err))
else:
print("... Renamed.")
else:
@ -204,7 +204,7 @@ def rename_in_file(path, in_list, out_list, is_interactive):
with open(path, 'r') as fil:
org_text = fil.read()
repl_mapping = zip(in_list, out_list)
repl_mapping = list(zip(in_list, out_list))
if not is_interactive:
# just replace everything immediately
@ -239,12 +239,12 @@ def rename_in_file(path, in_list, out_list, is_interactive):
while True:
for iline, renamed_line in sorted(renamed.items(), key=lambda tup: tup[0]):
for iline, renamed_line in sorted(list(renamed.items()), key=lambda tup: tup[0]):
print("%3i orig: %s" % (iline + 1, org_lines[iline]))
print(" new : %s" % (_yellow(renamed_line)))
print(_green("%s (%i lines changed)" % (path, len(renamed))))
ret = raw_input(_green("Choose: "
ret = input(_green("Choose: "
"[q]uit, "
"[h]elp, "
"[s]kip file, "
@ -261,7 +261,7 @@ def rename_in_file(path, in_list, out_list, is_interactive):
break
elif ret == "a":
# save result
for iline, renamed_line in renamed.items():
for iline, renamed_line in list(renamed.items()):
org_lines[iline] = renamed_line
if FAKE_MODE:
@ -275,12 +275,12 @@ def rename_in_file(path, in_list, out_list, is_interactive):
print("Quit renaming program.")
sys.exit()
elif ret == "h":
raw_input(_HELP_TEXT.format(sources=in_list, targets=out_list))
input(_HELP_TEXT.format(sources=in_list, targets=out_list))
elif ret.startswith("i"):
# ignore one or more lines
ignores = [int(ind) - 1 for ind in ret[1:].split(',') if ind.strip().isdigit()]
if not ignores:
raw_input("Ignore example: i 2,7,34,133\n (return to continue)")
input("Ignore example: i 2,7,34,133\n (return to continue)")
continue
for ign in ignores:
renamed.pop(ign, None)

View file

@ -17,8 +17,8 @@ to launch such a shell (using python or ipython depending on your install).
See www.evennia.com for full documentation.
"""
from __future__ import print_function
from __future__ import absolute_import
from builtins import object
# Delayed loading of properties

View file

@ -491,7 +491,7 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)):
"""
# handle me, self and *me, *self
if isinstance(searchdata, basestring):
if isinstance(searchdata, str):
# handle wrapping of common terms
if searchdata.lower() in ("me", "*me", "self", "*self",):
return self
@ -983,7 +983,7 @@ class DefaultGuest(DefaultAccount):
characters = self.db._playable_characters
for character in characters:
if character:
print "deleting Character:", character
print("deleting Character:", character)
character.delete()
def at_post_disconnect(self, **kwargs):

View file

@ -3,7 +3,7 @@ Bots are a special child typeclasses of
Account that are controlled by the server.
"""
from __future__ import print_function
import time
from django.conf import settings
from evennia.accounts.accounts import DefaultAccount

View file

@ -165,9 +165,9 @@ class AccountDBManager(TypedObjectManager, UserManager):
if typeclass:
# we accept both strings and actual typeclasses
if callable(typeclass):
typeclass = u"%s.%s" % (typeclass.__module__, typeclass.__name__)
typeclass = "%s.%s" % (typeclass.__module__, typeclass.__name__)
else:
typeclass = u"%s" % typeclass
typeclass = "%s" % typeclass
query["db_typeclass_path"] = typeclass
if exact:
return self.filter(**query)

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import evennia.accounts.manager

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-09-05 09:02
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-06 17:31
from __future__ import unicode_literals
import django.contrib.auth.validators
from django.db import migrations, models

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-03 19:17
from __future__ import unicode_literals
from django.apps import apps as global_apps
from django.db import migrations

View file

@ -139,7 +139,7 @@ class AccountDB(TypedObject, AbstractUser):
return smart_str("%s(account %s)" % (self.name, self.dbid))
def __unicode__(self):
return u"%s(account#%s)" % (self.name, self.dbid)
return "%s(account#%s)" % (self.name, self.dbid)
#@property
def __username_get(self):

View file

@ -190,7 +190,7 @@ def _progressive_cmd_run(cmd, generator, response=None):
try:
if response is None:
value = generator.next()
value = next(generator)
else:
value = generator.send(response)
except StopIteration:
@ -198,7 +198,7 @@ def _progressive_cmd_run(cmd, generator, response=None):
else:
if isinstance(value, (int, float)):
utils.delay(value, _progressive_cmd_run, cmd, generator)
elif isinstance(value, basestring):
elif isinstance(value, str):
_GET_INPUT(cmd.caller, value, _process_input, cmd=cmd, generator=generator)
else:
raise ValueError("unknown type for a yielded value in command: {}".format(type(value)))
@ -443,7 +443,7 @@ def get_and_merge_cmdsets(caller, session, account, obj, callertype, raw_string)
tempmergers[prio] = cmdset
# sort cmdsets after reverse priority (highest prio are merged in last)
cmdsets = yield sorted(tempmergers.values(), key=lambda x: x.priority)
cmdsets = yield sorted(list(tempmergers.values()), key=lambda x: x.priority)
# Merge all command sets into one, beginning with the lowest-prio one
cmdset = cmdsets[0]
@ -567,7 +567,7 @@ def cmdhandler(called_by, raw_string, _testing=False, callertype="session", sess
returnValue(cmd)
# assign custom kwargs to found cmd object
for key, val in kwargs.items():
for key, val in list(kwargs.items()):
setattr(cmd, key, val)
_COMMAND_NESTING[called_by] += 1

View file

@ -5,7 +5,7 @@ replacing cmdparser function. The replacement parser must accept the
same inputs as the default one.
"""
from __future__ import division
import re
from django.conf import settings
@ -70,7 +70,7 @@ def cmdparser(raw_string, cmdset, caller, match_index=None):
the `raw_cmdname` is the cmdname unmodified by eventual prefix-stripping.
"""
cmdlen, strlen = len(unicode(cmdname)), len(unicode(string))
cmdlen, strlen = len(str(cmdname)), len(str(string))
mratio = 1 - (strlen - cmdlen) / (1.0 * strlen)
args = string[cmdlen:]
return (cmdname, args, cmdobj, cmdlen, mratio, raw_cmdname)

View file

@ -422,13 +422,13 @@ class CmdSetHandler(object):
it's a 'quirk' that has to be documented.
"""
if not (isinstance(cmdset, basestring) or utils.inherits_from(cmdset, CmdSet)):
if not (isinstance(cmdset, str) or utils.inherits_from(cmdset, CmdSet)):
string = _("Only CmdSets can be added to the cmdsethandler!")
raise Exception(string)
if callable(cmdset):
cmdset = cmdset(self.obj)
elif isinstance(cmdset, basestring):
elif isinstance(cmdset, str):
# this is (maybe) a python path. Try to import from cache.
cmdset = self._import_cmdset(cmdset)
if cmdset and cmdset.key != '_CMDSET_ERROR':
@ -586,11 +586,11 @@ class CmdSetHandler(object):
"""
if callable(cmdset) and hasattr(cmdset, 'path'):
# try it as a callable
print "Try callable", cmdset
print("Try callable", cmdset)
if must_be_default:
return self.cmdset_stack and (self.cmdset_stack[0].path == cmdset.path)
else:
print [cset.path for cset in self.cmdset_stack], cmdset.path
print([cset.path for cset in self.cmdset_stack], cmdset.path)
return any([cset for cset in self.cmdset_stack
if cset.path == cmdset.path])
else:

View file

@ -65,7 +65,7 @@ def _init_command(cls, **kwargs):
temp.append(lockstring)
cls.lock_storage = ";".join(temp)
if hasattr(cls, 'arg_regex') and isinstance(cls.arg_regex, basestring):
if hasattr(cls, 'arg_regex') and isinstance(cls.arg_regex, str):
cls.arg_regex = re.compile(r"%s" % cls.arg_regex, re.I + re.UNICODE)
if not hasattr(cls, "auto_help"):
cls.auto_help = True
@ -266,7 +266,7 @@ class Command(with_metaclass(CommandMeta, object)):
caches are properly updated as well.
"""
if isinstance(new_aliases, basestring):
if isinstance(new_aliases, str):
new_aliases = new_aliases.split(';')
aliases = (str(alias).strip().lower() for alias in make_iter(new_aliases))
self.aliases = list(set(alias for alias in aliases if alias != self.key))

View file

@ -502,13 +502,13 @@ class CmdOption(COMMAND_DEFAULT_CLASS):
options["SCREENWIDTH"] = options["SCREENWIDTH"][0]
else:
options["SCREENWIDTH"] = " \n".join("%s : %s" % (screenid, size)
for screenid, size in options["SCREENWIDTH"].iteritems())
for screenid, size in options["SCREENWIDTH"].items())
if "SCREENHEIGHT" in options:
if len(options["SCREENHEIGHT"]) == 1:
options["SCREENHEIGHT"] = options["SCREENHEIGHT"][0]
else:
options["SCREENHEIGHT"] = " \n".join("%s : %s" % (screenid, size)
for screenid, size in options["SCREENHEIGHT"].iteritems())
for screenid, size in options["SCREENHEIGHT"].items())
options.pop("TTYPE", None)
header = ("Name", "Value", "Saved") if saved_options else ("Name", "Value")

View file

@ -1541,7 +1541,7 @@ class CmdSetAttribute(ObjManipCommand):
def load(caller):
"""Called for the editor to load the buffer"""
old_value = obj.attributes.get(attr)
if old_value is not None and not isinstance(old_value, basestring):
if old_value is not None and not isinstance(old_value, str):
typ = type(old_value).__name__
self.caller.msg("|RWARNING! Saving this buffer will overwrite the "
"current attribute (of type %s) with a string!|n" % typ)
@ -1937,7 +1937,7 @@ class CmdExamine(ObjManipCommand):
Formats a single attribute line.
"""
if crop:
if not isinstance(value, basestring):
if not isinstance(value, str):
value = utils.to_str(value, force_string=True)
value = utils.crop(value)
value = utils.to_unicode(value)
@ -2058,7 +2058,7 @@ class CmdExamine(ObjManipCommand):
except (TypeError, AttributeError):
# an error means we are merging an object without a session
pass
all_cmdsets = [cmdset for cmdset in dict(all_cmdsets).values()]
all_cmdsets = [cmdset for cmdset in list(dict(all_cmdsets).values())]
all_cmdsets.sort(key=lambda x: x.priority, reverse=True)
string += "\n|wMerged Cmdset(s)|n:\n %s" % ("\n ".join("%s [%s] (%s, prio %s)" % (
cmdset.path, cmdset.key, cmdset.mergetype, cmdset.priority) for cmdset in all_cmdsets))
@ -2707,7 +2707,7 @@ class CmdSpawn(COMMAND_DEFAULT_CLASS):
self.caller.msg(string)
return
if isinstance(prototype, basestring):
if isinstance(prototype, str):
# A prototype key
keystr = prototype
prototype = prototypes.get(prototype, None)

View file

@ -754,7 +754,7 @@ class CmdPage(COMMAND_DEFAULT_CLASS):
recobjs = []
for receiver in set(receivers):
if isinstance(receiver, basestring):
if isinstance(receiver, str):
pobj = caller.search(receiver)
elif hasattr(receiver, 'character'):
pobj = receiver

View file

@ -3,7 +3,7 @@
System commands
"""
from __future__ import division
import traceback
import os
@ -440,7 +440,7 @@ class CmdObjects(COMMAND_DEFAULT_CLASS):
typetable = EvTable("|wtypeclass|n", "|wcount|n", "|w%%|n", border="table", align="l")
typetable.align = 'l'
dbtotals = ObjectDB.objects.object_totals()
for path, count in dbtotals.items():
for path, count in list(dbtotals.items()):
typetable.add_row(path, count, "%.2f" % ((float(count) / nobjs) * 100))
# last N table
@ -487,7 +487,7 @@ class CmdAccounts(COMMAND_DEFAULT_CLASS):
# typeclass table
dbtotals = AccountDB.objects.object_totals()
typetable = EvTable("|wtypeclass|n", "|wcount|n", "|w%%|n", border="cells", align="l")
for path, count in dbtotals.items():
for path, count in list(dbtotals.items()):
typetable.add_row(path, count, "%.2f" % ((float(count) / naccounts) * 100))
# last N table
plyrs = AccountDB.objects.all().order_by("db_date_created")[max(0, naccounts - nlim):]
@ -544,7 +544,7 @@ class CmdService(COMMAND_DEFAULT_CLASS):
table = EvTable("|wService|n (use @services/start|stop|delete)", "|wstatus", align="l")
for service in service_collection.services:
table.add_row(service.name, service.running and "|gRunning" or "|rNot Running")
caller.msg(unicode(table))
caller.msg(str(table))
return
# Get the service to start / stop
@ -663,7 +663,7 @@ class CmdTime(COMMAND_DEFAULT_CLASS):
table2.add_row("Total time passed:", utils.time_format(gametime.gametime(), 2))
table2.add_row("Current time ", datetime.datetime.fromtimestamp(gametime.gametime(absolute=True)))
table2.reformat_column(0, width=30)
self.caller.msg(unicode(table1) + "\n" + unicode(table2))
self.caller.msg(str(table1) + "\n" + str(table2))
class CmdServerLoad(COMMAND_DEFAULT_CLASS):
@ -799,7 +799,7 @@ class CmdServerLoad(COMMAND_DEFAULT_CLASS):
# object cache count (note that sys.getsiseof is not called so this works for pypy too.
total_num, cachedict = _IDMAPPER.cache_size()
sorted_cache = sorted([(key, num) for key, num in cachedict.items() if num > 0],
sorted_cache = sorted([(key, num) for key, num in list(cachedict.items()) if num > 0],
key=lambda tup: tup[1], reverse=True)
memtable = EvTable("entity name", "number", "idmapper %", align="l")
for tup in sorted_cache:
@ -841,4 +841,4 @@ class CmdTickers(COMMAND_DEFAULT_CLASS):
sub[1] if sub[1] else sub[2],
sub[4] or "[Unset]",
"*" if sub[5] else "-")
self.caller.msg("|wActive tickers|n:\n" + unicode(table))
self.caller.msg("|wActive tickers|n:\n" + str(table))

View file

@ -78,7 +78,7 @@ class CommandTest(EvenniaTest):
cmdobj.parse()
ret = cmdobj.func()
if isinstance(ret, types.GeneratorType):
ret.next()
next(ret)
cmdobj.at_post_cmd()
except StopIteration:
pass
@ -128,9 +128,9 @@ class TestGeneral(CommandTest):
self.call(general.CmdNick(), "testalias = testaliasedstring1", "Nick 'testalias' mapped to 'testaliasedstring1'.")
self.call(general.CmdNick(), "/account testalias = testaliasedstring2", "Nick 'testalias' mapped to 'testaliasedstring2'.")
self.call(general.CmdNick(), "/object testalias = testaliasedstring3", "Nick 'testalias' mapped to 'testaliasedstring3'.")
self.assertEqual(u"testaliasedstring1", self.char1.nicks.get("testalias"))
self.assertEqual(u"testaliasedstring2", self.char1.nicks.get("testalias", category="account"))
self.assertEqual(u"testaliasedstring3", self.char1.nicks.get("testalias", category="object"))
self.assertEqual("testaliasedstring1", self.char1.nicks.get("testalias"))
self.assertEqual("testaliasedstring2", self.char1.nicks.get("testalias", category="account"))
self.assertEqual("testaliasedstring3", self.char1.nicks.get("testalias", category="object"))
def test_get_and_drop(self):
self.call(general.CmdGet(), "Obj", "You pick up Obj.")

View file

@ -271,7 +271,7 @@ class ChannelHandler(object):
if channelname:
channel = self._cached_channels.get(channelname.lower(), None)
return [channel] if channel else []
return self._cached_channels.values()
return list(self._cached_channels.values())
def get_cmdset(self, source_object):
"""
@ -292,7 +292,7 @@ class ChannelHandler(object):
else:
# create a new cmdset holding all viable channels
chan_cmdset = None
chan_cmds = [channelcmd for channel, channelcmd in self._cached_channel_cmds.iteritems()
chan_cmds = [channelcmd for channel, channelcmd in self._cached_channel_cmds.items()
if channel.subscriptions.has(source_object) and
channelcmd.access(source_object, 'send')]
if chan_cmds:

View file

@ -325,7 +325,7 @@ class DefaultChannel(with_metaclass(TypeclassBase, ChannelDB)):
"""
senders = make_iter(senders) if senders else []
if isinstance(msgobj, basestring):
if isinstance(msgobj, str):
# given msgobj is a string - convert to msgobject (always TempMsg)
msgobj = TempMsg(senders=senders, header=header, message=msgobj, channels=[self])
# we store the logging setting for use in distribute_message()

View file

@ -3,7 +3,7 @@ These managers define helper methods for accessing the database from
Comm system components.
"""
from __future__ import print_function
from django.db.models import Q
from evennia.typeclasses.managers import (TypedObjectManager, TypeclassManager)
@ -43,9 +43,9 @@ def dbref(inp, reqhash=True):
dbref, otherwise `None`.
"""
if reqhash and not (isinstance(inp, basestring) and inp.startswith("#")):
if reqhash and not (isinstance(inp, str) and inp.startswith("#")):
return None
if isinstance(inp, basestring):
if isinstance(inp, str):
inp = inp.lstrip('#')
try:
if int(inp) < 0:
@ -77,7 +77,7 @@ def identify_object(inp):
return inp, "object"
elif clsname == "ChannelDB":
return inp, "channel"
if isinstance(inp, basestring):
if isinstance(inp, str):
return inp, "string"
elif dbref(inp):
return dbref(inp), "dbref"

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-09-05 09:02
from __future__ import unicode_literals
from django.db import migrations

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-09-21 17:31
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9.11 on 2016-12-06 19:12
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9.11 on 2017-02-17 20:39
from __future__ import unicode_literals
from django.db import migrations, models

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-06 17:31
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-17 20:17
from __future__ import unicode_literals
from django.db import migrations

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-05 17:26
from __future__ import unicode_literals
from django.db import migrations, models, connection

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-05 17:36
from __future__ import unicode_literals
from django.db import migrations

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-06 20:41
from __future__ import unicode_literals
from django.db import migrations, connection

View file

@ -166,7 +166,7 @@ class Msg(SharedMemoryModel):
for sender in make_iter(senders):
if not sender:
continue
if isinstance(sender, basestring):
if isinstance(sender, str):
self.db_sender_external = sender
self.extra_senders.append(sender)
self.save(update_fields=["db_sender_external"])
@ -203,7 +203,7 @@ class Msg(SharedMemoryModel):
for sender in make_iter(senders):
if not sender:
continue
if isinstance(sender, basestring):
if isinstance(sender, str):
self.db_sender_external = ""
self.save(update_fields=["db_sender_external"])
if not hasattr(sender, "__dbclass__"):

View file

@ -93,7 +93,7 @@ cmdset. This will make the trade (or barter) command available
in-game.
"""
from __future__ import print_function
from builtins import object
from evennia import Command, DefaultScript, CmdSet

View file

@ -187,7 +187,7 @@ def clothing_type_count(clothes_list):
for garment in clothes_list:
if garment.db.clothing_type:
type = garment.db.clothing_type
if type not in types_count.keys():
if type not in list(types_count.keys()):
types_count[type] = 1
else:
types_count[type] += 1
@ -380,7 +380,7 @@ class CmdWear(MuxCommand):
# Apply individual clothing type limits.
if clothing.db.clothing_type and not clothing.db.worn:
type_count = single_type_count(get_worn_clothes(self.caller), clothing.db.clothing_type)
if clothing.db.clothing_type in CLOTHING_TYPE_LIMIT.keys():
if clothing.db.clothing_type in list(CLOTHING_TYPE_LIMIT.keys()):
if type_count >= CLOTHING_TYPE_LIMIT[clothing.db.clothing_type]:
self.caller.msg("You can't wear any more clothes of the type '%s'." % clothing.db.clothing_type)
return

View file

@ -105,7 +105,7 @@ def gametime_to_realtime(format=False, **kwargs):
"""
# Dynamically creates the list of units based on kwarg names and UNITs list
rtime = 0
for name, value in kwargs.items():
for name, value in list(kwargs.items()):
# Allow plural names (like mins instead of min)
if name not in UNITS and name.endswith("s"):
name = name[:-1]
@ -197,7 +197,7 @@ def real_seconds_until(**kwargs):
# For each keyword, add in the unit's
units.append(1)
higher_unit = None
for unit, value in kwargs.items():
for unit, value in list(kwargs.items()):
# Get the unit's index
if unit not in UNITS:
raise ValueError("unknown unit".format(unit))

View file

@ -1,4 +1,4 @@
import urllib
import urllib.request, urllib.parse, urllib.error
import platform
import warnings
@ -107,7 +107,7 @@ class EvenniaGameIndexClient(object):
'django_version': django.get_version(),
'server_platform': platform.platform(),
}
data = urllib.urlencode(values)
data = urllib.parse.urlencode(values)
d = agent.request(
'POST', self.report_url,

View file

@ -66,7 +66,7 @@ Installation/testing:
3) Use `desc` and `detail` to customize the room, then play around!
"""
from __future__ import division
import datetime
import re
@ -398,7 +398,7 @@ class CmdExtendedDesc(default_cmds.CmdDesc):
# No args given. Return all details on location
string = "|wDetails on %s|n:" % location
details = "\n".join(" |w%s|n: %s"
% (key, utils.crop(text)) for key, text in location.db.details.items())
% (key, utils.crop(text)) for key, text in list(location.db.details.items()))
caller.msg("%s\n%s" % (string, details) if details else "%s None." % string)
return
if not self.rhs:

View file

@ -36,7 +36,7 @@ class CallbackHandler(object):
handler = type(self).script
if handler:
dicts = handler.get_callbacks(self.obj)
for callback_name, in_list in dicts.items():
for callback_name, in_list in list(dicts.items()):
new_list = []
for callback in in_list:
callback = self.format_callback(callback)

View file

@ -253,7 +253,7 @@ class CmdCallback(COMMAND_DEFAULT_CLASS):
row.append("Yes" if callback.get("valid") else "No")
table.add_row(*row)
self.msg(unicode(table))
self.msg(str(table))
else:
names = list(set(list(types.keys()) + list(callbacks.keys())))
table = EvTable("Callback name", "Number", "Description",
@ -269,7 +269,7 @@ class CmdCallback(COMMAND_DEFAULT_CLASS):
description = description.strip("\n").splitlines()[0]
table.add_row(name, no, description)
self.msg(unicode(table))
self.msg(str(table))
def add_callback(self):
"""Add a callback."""
@ -457,7 +457,7 @@ class CmdCallback(COMMAND_DEFAULT_CLASS):
updated_on = "|gUnknown|n"
table.add_row(obj.id, type_name, obj, name, by, updated_on)
self.msg(unicode(table))
self.msg(str(table))
return
# An object was specified
@ -503,7 +503,7 @@ class CmdCallback(COMMAND_DEFAULT_CLASS):
obj = self.obj
callback_name = self.callback_name
handler = self.handler
tasks = [(k, v[0], v[1], v[2]) for k, v in handler.db.tasks.items()]
tasks = [(k, v[0], v[1], v[2]) for k, v in list(handler.db.tasks.items())]
if obj:
tasks = [task for task in tasks if task[2] is obj]
if callback_name:
@ -518,7 +518,7 @@ class CmdCallback(COMMAND_DEFAULT_CLASS):
delta = time_format((future - now).total_seconds(), 1)
table.add_row(task_id, key, callback_name, delta)
self.msg(unicode(table))
self.msg(str(table))
# Private functions to handle editing

View file

@ -3,7 +3,7 @@ Scripts for the in-game Python system.
"""
from datetime import datetime, timedelta
from Queue import Queue
from queue import Queue
import re
import sys
import traceback
@ -129,7 +129,7 @@ class EventHandler(DefaultScript):
while not classes.empty():
typeclass = classes.get()
typeclass_name = typeclass.__module__ + "." + typeclass.__name__
for key, etype in all_events.get(typeclass_name, {}).items():
for key, etype in list(all_events.get(typeclass_name, {}).items()):
if key in invalid:
continue
if etype[0] is None: # Invalidate
@ -186,7 +186,7 @@ class EventHandler(DefaultScript):
"""
obj_callbacks = self.db.callbacks.get(obj, {})
callbacks = {}
for callback_name, callback_list in obj_callbacks.items():
for callback_name, callback_list in list(obj_callbacks.items()):
new_list = []
for i, callback in enumerate(callback_list):
callback = dict(callback)
@ -436,7 +436,7 @@ class EventHandler(DefaultScript):
type(obj), variable, i))
return False
else:
locals = {key: value for key, value in locals.items()}
locals = {key: value for key, value in list(locals.items())}
callbacks = self.get_callbacks(obj).get(callback_name, [])
if event:
@ -576,7 +576,7 @@ class EventHandler(DefaultScript):
# Collect and freeze current locals
locals = {}
for key, value in self.ndb.current_locals.items():
for key, value in list(self.ndb.current_locals.items()):
try:
dbserialize(value)
except TypeError:

View file

@ -224,13 +224,13 @@ class TestEventHandler(EvenniaTest):
self.assertEqual(callback.code, "pass")
self.assertEqual(callback.author, self.char1)
self.assertEqual(callback.valid, True)
self.assertIn([callback], self.room1.callbacks.all().values())
self.assertIn([callback], list(self.room1.callbacks.all().values()))
# Edit this very callback
new = self.room1.callbacks.edit("dummy", 0, "character.db.say = True",
author=self.char1, valid=True)
self.assertIn([new], self.room1.callbacks.all().values())
self.assertNotIn([callback], self.room1.callbacks.all().values())
self.assertIn([new], list(self.room1.callbacks.all().values()))
self.assertNotIn([callback], list(self.room1.callbacks.all().values()))
# Try to call this callback
self.assertTrue(self.room1.callbacks.call("dummy",

View file

@ -50,7 +50,7 @@ def register_events(path_or_typeclass):
temporary storage, waiting for the script to be initialized.
"""
if isinstance(path_or_typeclass, basestring):
if isinstance(path_or_typeclass, str):
typeclass = class_from_module(path_or_typeclass)
else:
typeclass = path_or_typeclass
@ -65,7 +65,7 @@ def register_events(path_or_typeclass):
# If the script is started, add the event directly.
# Otherwise, add it to the temporary storage.
for name, tup in getattr(typeclass, "_events", {}).items():
for name, tup in list(getattr(typeclass, "_events", {}).items()):
if len(tup) == 4:
variables, help_text, custom_call, custom_add = tup
elif len(tup) == 3:
@ -116,7 +116,7 @@ def get_next_wait(format):
units = ["min", "hour", "day", "month", "year"]
elif calendar == "custom":
rsu = custom_rsu
back = dict([(value, name) for name, value in UNITS.items()])
back = dict([(value, name) for name, value in list(UNITS.items())])
sorted_units = sorted(back.items())
del sorted_units[0]
units = [n for v, n in sorted_units]

View file

@ -259,7 +259,7 @@ class CmdMail(default_cmds.MuxCommand):
table.reformat_column(4, width=7)
self.caller.msg(_HEAD_CHAR * _WIDTH)
self.caller.msg(unicode(table))
self.caller.msg(str(table))
self.caller.msg(_HEAD_CHAR * _WIDTH)
else:
self.caller.msg("There are no messages in your inbox.")

View file

@ -139,7 +139,7 @@ def example1_build_mountains(x, y, **kwargs):
room.db.desc = random.choice(room_desc)
# Create a random number of objects to populate the room.
for i in xrange(randint(0, 3)):
for i in range(randint(0, 3)):
rock = create_object(key="Rock", location=room)
rock.db.desc = "An ordinary rock."
@ -286,7 +286,7 @@ def _map_to_list(game_map):
"""
list_map = game_map.split('\n')
return [character.decode('UTF-8') if isinstance(character, basestring)
return [character.decode('UTF-8') if isinstance(character, str)
else character for character in list_map]
@ -321,9 +321,9 @@ def build_map(caller, game_map, legend, iterations=1, build_exits=True):
room_dict = {}
caller.msg("Creating Landmass...")
for iteration in xrange(iterations):
for y in xrange(len(game_map)):
for x in xrange(len(game_map[y])):
for iteration in range(iterations):
for y in range(len(game_map)):
for x in range(len(game_map[y])):
for key in legend:
# obs - we must use == for unicode
if utils.to_unicode(game_map[y][x]) == utils.to_unicode(key):
@ -336,7 +336,7 @@ def build_map(caller, game_map, legend, iterations=1, build_exits=True):
if build_exits:
# Creating exits. Assumes single room object in dict entry
caller.msg("Connecting Areas...")
for loc_key, location in room_dict.iteritems():
for loc_key, location in room_dict.items():
x = loc_key[0]
y = loc_key[1]

View file

@ -232,7 +232,7 @@ class LanguageHandler(DefaultScript):
translation = {}
if auto_translations:
if isinstance(auto_translations, basestring):
if isinstance(auto_translations, str):
# path to a file rather than a list
with open(auto_translations, 'r') as f:
auto_translations = f.readlines()
@ -254,7 +254,7 @@ class LanguageHandler(DefaultScript):
if manual_translations:
# update with manual translations
translation.update(dict((key.lower(), value.lower()) for key, value in manual_translations.items()))
translation.update(dict((key.lower(), value.lower()) for key, value in list(manual_translations.items())))
# store data
storage = {"translation": translation,

View file

@ -511,7 +511,7 @@ def send_emote(sender, receivers, emote, anonymous_add="first"):
process_language = receiver.process_language
except AttributeError:
process_language = _dummy_process
for key, (langname, saytext) in language_mapping.iteritems():
for key, (langname, saytext) in language_mapping.items():
# color says
receiver_lang_mapping[key] = process_language(saytext, sender, langname)
# map the language {##num} markers. This will convert the escaped sdesc markers on
@ -531,11 +531,11 @@ def send_emote(sender, receivers, emote, anonymous_add="first"):
try:
recog_get = receiver.recog.get
receiver_sdesc_mapping = dict((ref, process_recog(recog_get(obj), obj)) for ref, obj in obj_mapping.items())
receiver_sdesc_mapping = dict((ref, process_recog(recog_get(obj), obj)) for ref, obj in list(obj_mapping.items()))
except AttributeError:
receiver_sdesc_mapping = dict((ref, process_sdesc(obj.sdesc.get(), obj)
if hasattr(obj, "sdesc") else process_sdesc(obj.key, obj))
for ref, obj in obj_mapping.items())
for ref, obj in list(obj_mapping.items()))
# make sure receiver always sees their real name
rkey = "#%i" % receiver.id
if rkey in receiver_sdesc_mapping:
@ -684,9 +684,9 @@ class RecogHandler(object):
obj2regex = self.obj.attributes.get("_recog_obj2regex", default={})
obj2recog = self.obj.attributes.get("_recog_obj2recog", default={})
self.obj2regex = dict((obj, re.compile(regex, _RE_FLAGS))
for obj, regex in obj2regex.items() if obj)
for obj, regex in list(obj2regex.items()) if obj)
self.obj2recog = dict((obj, recog)
for obj, recog in obj2recog.items() if obj)
for obj, recog in list(obj2recog.items()) if obj)
def add(self, obj, recog, max_length=60):
"""
@ -981,7 +981,7 @@ class CmdPose(RPCommand): # set current pose and default pose
# set the pose. We do one-time ref->sdesc mapping here.
parsed, mapping = parse_sdescs_and_recogs(caller, caller.location.contents, pose)
mapping = dict((ref, obj.sdesc.get() if hasattr(obj, "sdesc") else obj.key)
for ref, obj in mapping.iteritems())
for ref, obj in mapping.items())
pose = parsed.format(**mapping)
if len(target_name) + len(pose) > 60:
@ -1223,7 +1223,7 @@ class ContribRPObject(DefaultObject):
messaging is assumed to be handled by the caller.
"""
is_string = isinstance(searchdata, basestring)
is_string = isinstance(searchdata, str)
if is_string:
# searchdata is a string; wrap some common self-references

View file

@ -355,14 +355,14 @@ class TestWilderness(EvenniaTest):
wilderness.enter_wilderness(self.char1)
self.assertIsInstance(self.char1.location, wilderness.WildernessRoom)
w = self.get_wilderness_script()
self.assertEquals(w.db.itemcoordinates[self.char1], (0, 0))
self.assertEqual(w.db.itemcoordinates[self.char1], (0, 0))
def test_enter_wilderness_custom_coordinates(self):
wilderness.create_wilderness()
wilderness.enter_wilderness(self.char1, coordinates=(1, 2))
self.assertIsInstance(self.char1.location, wilderness.WildernessRoom)
w = self.get_wilderness_script()
self.assertEquals(w.db.itemcoordinates[self.char1], (1, 2))
self.assertEqual(w.db.itemcoordinates[self.char1], (1, 2))
def test_enter_wilderness_custom_name(self):
name = "customnname"
@ -381,7 +381,7 @@ class TestWilderness(EvenniaTest):
i.access(self.char1, "view") or
i.access(self.char1, "traverse"))]
self.assertEquals(len(exits), 3)
self.assertEqual(len(exits), 3)
exitsok = ["north", "northeast", "east"]
for each_exit in exitsok:
self.assertTrue(any([e for e in exits if e.key == each_exit]))
@ -393,7 +393,7 @@ class TestWilderness(EvenniaTest):
if i.destination and (
i.access(self.char1, "view") or
i.access(self.char1, "traverse"))]
self.assertEquals(len(exits), 8)
self.assertEqual(len(exits), 8)
exitsok = ["north", "northeast", "east", "southeast", "south",
"southwest", "west", "northwest"]
for each_exit in exitsok:
@ -410,25 +410,25 @@ class TestWilderness(EvenniaTest):
w = self.get_wilderness_script()
# We should have no unused room after moving the first account in.
self.assertEquals(len(w.db.unused_rooms), 0)
self.assertEqual(len(w.db.unused_rooms), 0)
w.move_obj(self.char1, (0, 0))
self.assertEquals(len(w.db.unused_rooms), 0)
self.assertEqual(len(w.db.unused_rooms), 0)
# And also no unused room after moving the second one in.
w.move_obj(self.char2, (1, 1))
self.assertEquals(len(w.db.unused_rooms), 0)
self.assertEqual(len(w.db.unused_rooms), 0)
# But if char2 moves into char1's room, we should have one unused room
# Which should be char2's old room that got created.
w.move_obj(self.char2, (0, 0))
self.assertEquals(len(w.db.unused_rooms), 1)
self.assertEquals(self.char1.location, self.char2.location)
self.assertEqual(len(w.db.unused_rooms), 1)
self.assertEqual(self.char1.location, self.char2.location)
# And if char2 moves back out, that unused room should be put back to
# use again.
w.move_obj(self.char2, (1, 1))
self.assertNotEquals(self.char1.location, self.char2.location)
self.assertEquals(len(w.db.unused_rooms), 0)
self.assertNotEqual(self.char1.location, self.char2.location)
self.assertEqual(len(w.db.unused_rooms), 0)
def test_get_new_coordinates(self):
loc = (1, 1)
@ -440,9 +440,9 @@ class TestWilderness(EvenniaTest):
"southwest": (0, 0),
"west": (0, 1),
"northwest": (0, 2)}
for direction, correct_loc in directions.iteritems(): # Not compatible with Python 3
for direction, correct_loc in directions.items(): # Not compatible with Python 3
new_loc = wilderness.get_new_coordinates(loc, direction)
self.assertEquals(new_loc, correct_loc, direction)
self.assertEqual(new_loc, correct_loc, direction)
# Testing chargen contrib

View file

@ -2,6 +2,6 @@
"""
This package holds the demo game of Evennia.
"""
from __future__ import absolute_import
from . import mob, objects, rooms

View file

@ -689,7 +689,7 @@ class CrumblingWall(TutorialObject, DefaultExit):
"crisscross the wall, making it hard to clearly see its stony surface. Maybe you could "
"try to |wshift|n or |wmove|n them.\n"]
# display the root positions to help with the puzzle
for key, pos in self.db.root_pos.items():
for key, pos in list(self.db.root_pos.items()):
result.append("\n" + self._translate_position(key, pos))
self.db.desc = "".join(result)

View file

@ -8,7 +8,7 @@ commands needed to control them. Those commands could also have been
in a separate module (e.g. if they could have been re-used elsewhere.)
"""
from __future__ import print_function
import random
from evennia import TICKER_HANDLER

View file

@ -249,10 +249,10 @@ class WildernessScript(DefaultScript):
"""
Called when the script is started and also after server reloads.
"""
for coordinates, room in self.db.rooms.items():
for coordinates, room in list(self.db.rooms.items()):
room.ndb.wildernessscript = self
room.ndb.active_coordinates = coordinates
for item in self.db.itemcoordinates.keys():
for item in list(self.db.itemcoordinates.keys()):
# Items deleted from the wilderness leave None type 'ghosts'
# that must be cleaned out
if item is None:
@ -302,7 +302,7 @@ class WildernessScript(DefaultScript):
[Object, ]: list of Objects at coordinates
"""
result = []
for item, item_coordinates in self.itemcoordinates.items():
for item, item_coordinates in list(self.itemcoordinates.items()):
# Items deleted from the wilderness leave None type 'ghosts'
# that must be cleaned out
if item is None:

View file

@ -62,4 +62,4 @@ AMP_PORT = 4006
try:
from server.conf.secret_settings import *
except ImportError:
print "secret_settings.py file not found or failed to import."
print("secret_settings.py file not found or failed to import.")

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-06 17:31
from __future__ import unicode_literals
from django.db import migrations, models

View file

@ -97,7 +97,7 @@ class HelpEntry(SharedMemoryModel):
return self.key
def __unicode__(self):
return u'%s' % self.key
return '%s' % self.key
def access(self, accessing_obj, access_type='read', default=False):
"""

View file

@ -87,7 +87,7 @@ DefaultLock: Exits: controls who may traverse the exit to
Dark/light script
```
"""
from __future__ import print_function
from django.conf import settings
from evennia.utils import utils

View file

@ -103,7 +103,7 @@ restricted @perm command sets them, but otherwise they are identical
to any other identifier you can use.
"""
from __future__ import print_function
from builtins import object
import re
@ -269,7 +269,7 @@ class LockHandler(object):
"""
Store locks to obj
"""
self.obj.lock_storage = ";".join([tup[2] for tup in self.locks.values()])
self.obj.lock_storage = ";".join([tup[2] for tup in list(self.locks.values())])
def cache_lock_bypass(self, obj):
"""
@ -302,7 +302,7 @@ class LockHandler(object):
error.
"""
if isinstance(lockstring, basestring):
if isinstance(lockstring, str):
lockdefs = lockstring.split(";")
else:
lockdefs = [lockdef for locks in lockstring for lockdef in locks.split(";")]

View file

@ -27,29 +27,29 @@ class TestLockCheck(EvenniaTest):
dbref = self.obj2.dbref
self.obj1.locks.add("owner:dbref(%s);edit:dbref(%s) or perm(Admin);examine:perm(Builder) and id(%s);delete:perm(Admin);get:all()" % (dbref, dbref, dbref))
self.obj2.permissions.add('Admin')
self.assertEquals(True, self.obj1.locks.check(self.obj2, 'owner'))
self.assertEquals(True, self.obj1.locks.check(self.obj2, 'edit'))
self.assertEquals(True, self.obj1.locks.check(self.obj2, 'examine'))
self.assertEquals(True, self.obj1.locks.check(self.obj2, 'delete'))
self.assertEquals(True, self.obj1.locks.check(self.obj2, 'get'))
self.assertEqual(True, self.obj1.locks.check(self.obj2, 'owner'))
self.assertEqual(True, self.obj1.locks.check(self.obj2, 'edit'))
self.assertEqual(True, self.obj1.locks.check(self.obj2, 'examine'))
self.assertEqual(True, self.obj1.locks.check(self.obj2, 'delete'))
self.assertEqual(True, self.obj1.locks.check(self.obj2, 'get'))
self.obj1.locks.add("get:false()")
self.assertEquals(False, self.obj1.locks.check(self.obj2, 'get'))
self.assertEquals(True, self.obj1.locks.check(self.obj2, 'not_exist', default=True))
self.assertEqual(False, self.obj1.locks.check(self.obj2, 'get'))
self.assertEqual(True, self.obj1.locks.check(self.obj2, 'not_exist', default=True))
class TestLockfuncs(EvenniaTest):
def testrun(self):
self.obj2.permissions.add('Admin')
self.assertEquals(True, lockfuncs.true(self.obj2, self.obj1))
self.assertEquals(False, lockfuncs.false(self.obj2, self.obj1))
self.assertEquals(True, lockfuncs.perm(self.obj2, self.obj1, 'Admin'))
self.assertEquals(True, lockfuncs.perm_above(self.obj2, self.obj1, 'Builder'))
self.assertEqual(True, lockfuncs.true(self.obj2, self.obj1))
self.assertEqual(False, lockfuncs.false(self.obj2, self.obj1))
self.assertEqual(True, lockfuncs.perm(self.obj2, self.obj1, 'Admin'))
self.assertEqual(True, lockfuncs.perm_above(self.obj2, self.obj1, 'Builder'))
dbref = self.obj2.dbref
self.assertEquals(True, lockfuncs.dbref(self.obj2, self.obj1, '%s' % dbref))
self.assertEqual(True, lockfuncs.dbref(self.obj2, self.obj1, '%s' % dbref))
self.obj2.db.testattr = 45
self.assertEquals(True, lockfuncs.attr(self.obj2, self.obj1, 'testattr', '45'))
self.assertEquals(False, lockfuncs.attr_gt(self.obj2, self.obj1, 'testattr', '45'))
self.assertEquals(True, lockfuncs.attr_ge(self.obj2, self.obj1, 'testattr', '45'))
self.assertEquals(False, lockfuncs.attr_lt(self.obj2, self.obj1, 'testattr', '45'))
self.assertEquals(True, lockfuncs.attr_le(self.obj2, self.obj1, 'testattr', '45'))
self.assertEquals(False, lockfuncs.attr_ne(self.obj2, self.obj1, 'testattr', '45'))
self.assertEqual(True, lockfuncs.attr(self.obj2, self.obj1, 'testattr', '45'))
self.assertEqual(False, lockfuncs.attr_gt(self.obj2, self.obj1, 'testattr', '45'))
self.assertEqual(True, lockfuncs.attr_ge(self.obj2, self.obj1, 'testattr', '45'))
self.assertEqual(False, lockfuncs.attr_lt(self.obj2, self.obj1, 'testattr', '45'))
self.assertEqual(True, lockfuncs.attr_le(self.obj2, self.obj1, 'testattr', '45'))
self.assertEqual(False, lockfuncs.attr_ne(self.obj2, self.obj1, 'testattr', '45'))

View file

@ -151,7 +151,7 @@ class ObjectDBManager(TypedObjectManager):
# This doesn't work if attribute_value is an object. Workaround below
if isinstance(attribute_value, (basestring, int, float, bool)):
if isinstance(attribute_value, (str, int, float, bool)):
return self.filter(cand_restriction & type_restriction & Q(db_attributes__db_key=attribute_name,
db_attributes__db_value=attribute_value))
else:
@ -196,9 +196,9 @@ class ObjectDBManager(TypedObjectManager):
typeclasses (list, optional): List of typeclass-path strings to restrict matches with
"""
if isinstance(property_value, basestring):
if isinstance(property_value, str):
property_value = to_unicode(property_value)
if isinstance(property_name, basestring):
if isinstance(property_name, str):
if not property_name.startswith('db_'):
property_name = "db_%s" % property_name
querykwargs = {property_name: property_value}
@ -244,7 +244,7 @@ class ObjectDBManager(TypedObjectManager):
Returns:
matches (list): A list of matches of length 0, 1 or more.
"""
if not isinstance(ostring, basestring):
if not isinstance(ostring, str):
if hasattr(ostring, "key"):
ostring = ostring.key
else:
@ -365,9 +365,9 @@ class ObjectDBManager(TypedObjectManager):
typeclasses = make_iter(typeclass)
for i, typeclass in enumerate(make_iter(typeclasses)):
if callable(typeclass):
typeclasses[i] = u"%s.%s" % (typeclass.__module__, typeclass.__name__)
typeclasses[i] = "%s.%s" % (typeclass.__module__, typeclass.__name__)
else:
typeclasses[i] = u"%s" % typeclass
typeclasses[i] = "%s" % typeclass
typeclass = typeclasses
if candidates is not None:

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-06 17:31
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-05 17:27
from __future__ import unicode_literals
from django.db import migrations, models, connection
import django.db.models.deletion

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-05 17:36
from __future__ import unicode_literals
from django.db import migrations

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-06 20:41
from __future__ import unicode_literals
from django.db import migrations, connection

View file

@ -231,7 +231,7 @@ class ObjectDB(TypedObject):
def __location_set(self, location):
"""Set location, checking for loops and allowing dbref"""
if isinstance(location, (basestring, int)):
if isinstance(location, (str, int)):
# allow setting of #dbref
dbid = dbref(location, reqhash=False)
if dbid:

View file

@ -359,7 +359,7 @@ class DefaultObject(with_metaclass(TypeclassBase, ObjectDB)):
messaging is assumed to be handled by the caller.
"""
is_string = isinstance(searchdata, basestring)
is_string = isinstance(searchdata, str)
if is_string:
@ -436,7 +436,7 @@ class DefaultObject(with_metaclass(TypeclassBase, ObjectDB)):
matching Accounts.
"""
if isinstance(searchdata, basestring):
if isinstance(searchdata, str):
# searchdata is a string; wrap some common self-references
if searchdata.lower() in ("me", "self",):
return [self.account] if quiet else self.account
@ -615,7 +615,7 @@ class DefaultObject(with_metaclass(TypeclassBase, ObjectDB)):
if mapping:
substitutions = {t: sub.get_display_name(obj)
if hasattr(sub, 'get_display_name')
else str(sub) for t, sub in mapping.items()}
else str(sub) for t, sub in list(mapping.items())}
outmessage = inmessage.format(**substitutions)
else:
outmessage = inmessage
@ -959,7 +959,7 @@ class DefaultObject(with_metaclass(TypeclassBase, ObjectDB)):
self.attributes.batch_add(*cdict["attributes"])
if cdict.get("nattributes"):
# this should be a dict of nattrname:value
for key, value in cdict["nattributes"].items():
for key, value in list(cdict["nattributes"].items()):
self.nattributes.add(key, value)
del self._createdict

View file

@ -240,9 +240,9 @@ class ScriptDBManager(TypedObjectManager):
if typeclass:
if callable(typeclass):
typeclass = u"%s.%s" % (typeclass.__module__, typeclass.__name__)
typeclass = "%s.%s" % (typeclass.__module__, typeclass.__name__)
else:
typeclass = u"%s" % typeclass
typeclass = "%s" % typeclass
# not a dbref; normal search
obj_restriction = obj and Q(db_obj=obj) or Q()

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations

View file

@ -1,16 +1,16 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def remove_manage_scripts(apps, schema_editor):
ScriptDB = apps.get_model("scripts", "ScriptDB")
for script in ScriptDB.objects.filter(db_typeclass_path__in=(u'evennia.scripts.scripts.CheckSessions',
u'evennia.scripts.scripts.ValidateScripts',
u'evennia.scripts.scripts.ValidateChannelHandler',
u'evennia.scripts.scripts.ValidateIdmapperCache',
u'evennia.utils.gametime.GameTime')):
for script in ScriptDB.objects.filter(db_typeclass_path__in=('evennia.scripts.scripts.CheckSessions',
'evennia.scripts.scripts.ValidateScripts',
'evennia.scripts.scripts.ValidateChannelHandler',
'evennia.scripts.scripts.ValidateIdmapperCache',
'evennia.utils.gametime.GameTime')):
script.delete()

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations

View file

@ -1,16 +1,16 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def remove_manage_scripts(apps, schema_editor):
ScriptDB = apps.get_model("scripts", "ScriptDB")
for script in ScriptDB.objects.filter(db_typeclass_path__in=(u'src.scripts.scripts.CheckSessions',
u'src.scripts.scripts.ValidateScripts',
u'src.scripts.scripts.ValidateChannelHandler',
u'src.scripts.scripts.ValidateIdmapperCache',
u'src.utils.gametime.GameTime')):
for script in ScriptDB.objects.filter(db_typeclass_path__in=('src.scripts.scripts.CheckSessions',
'src.scripts.scripts.ValidateScripts',
'src.scripts.scripts.ValidateChannelHandler',
'src.scripts.scripts.ValidateIdmapperCache',
'src.utils.gametime.GameTime')):
script.delete()

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-06 17:31
from __future__ import unicode_literals
from django.db import migrations, models

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-05 17:27
from __future__ import unicode_literals
from django.db import migrations, models, connection
import django.db.models.deletion

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-05 17:36
from __future__ import unicode_literals
from django.db import migrations

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-06 20:41
from __future__ import unicode_literals
from django.db import migrations, connection

View file

@ -141,7 +141,7 @@ class ScriptDB(TypedObject):
except AttributeError:
# deprecated ...
pass
if isinstance(value, (basestring, int)):
if isinstance(value, (str, int)):
from evennia.objects.models import ObjectDB
value = to_str(value, force_string=True)
if (value.isdigit() or value.startswith("#")):

View file

@ -50,8 +50,8 @@ class MonitorHandler(object):
if self.monitors:
for obj in self.monitors:
for fieldname in self.monitors[obj]:
for idstring, (callback, persistent, kwargs) in self.monitors[obj][fieldname].iteritems():
path = "%s.%s" % (callback.__module__, callback.func_name)
for idstring, (callback, persistent, kwargs) in self.monitors[obj][fieldname].items():
path = "%s.%s" % (callback.__module__, callback.__name__)
savedata.append((obj, fieldname, idstring, path, persistent, kwargs))
savedata = dbserialize(savedata)
ServerConfig.objects.conf(key=self.savekey, value=savedata)
@ -97,7 +97,7 @@ class MonitorHandler(object):
"""
to_delete = []
if obj in self.monitors and fieldname in self.monitors[obj]:
for idstring, (callback, persistent, kwargs) in self.monitors[obj][fieldname].iteritems():
for idstring, (callback, persistent, kwargs) in self.monitors[obj][fieldname].items():
try:
callback(obj=obj, fieldname=fieldname, **kwargs)
except Exception:
@ -183,7 +183,7 @@ class MonitorHandler(object):
output = []
for obj in self.monitors:
for fieldname in self.monitors[obj]:
for idstring, (callback, persistent, kwargs) in self.monitors[obj][fieldname].iteritems():
for idstring, (callback, persistent, kwargs) in self.monitors[obj][fieldname].items():
output.append((obj, fieldname, idstring, persistent, kwargs))
return output

View file

@ -41,13 +41,13 @@ class TaskHandler(object):
"""
to_save = False
value = ServerConfig.objects.conf("delayed_tasks", default={})
if isinstance(value, basestring):
if isinstance(value, str):
tasks = dbunserialize(value)
else:
tasks = value
# At this point, `tasks` contains a dictionary of still-serialized tasks
for task_id, value in tasks.items():
for task_id, value in list(tasks.items()):
date, callback, args, kwargs = dbunserialize(value)
if isinstance(callback, tuple):
# `callback` can be an object and name for instance methods
@ -64,7 +64,7 @@ class TaskHandler(object):
def save(self):
"""Save the tasks in ServerConfig."""
for task_id, (date, callback, args, kwargs) in self.tasks.items():
for task_id, (date, callback, args, kwargs) in list(self.tasks.items()):
if task_id in self.to_save:
continue
@ -111,7 +111,7 @@ class TaskHandler(object):
# Choose a free task_id
safe_args = []
safe_kwargs = {}
used_ids = self.tasks.keys()
used_ids = list(self.tasks.keys())
task_id = 1
while task_id in used_ids:
task_id += 1
@ -127,7 +127,7 @@ class TaskHandler(object):
else:
safe_args.append(arg)
for key, value in kwargs.items():
for key, value in list(kwargs.items()):
try:
dbserialize(value)
except (TypeError, AttributeError):
@ -187,7 +187,7 @@ class TaskHandler(object):
"""
now = datetime.now()
for task_id, (date, callbac, args, kwargs) in self.tasks.items():
for task_id, (date, callbac, args, kwargs) in list(self.tasks.items()):
seconds = max(0, (date - now).total_seconds())
task.deferLater(reactor, seconds, self.do_task, task_id)

View file

@ -113,7 +113,7 @@ class Ticker(object):
self._to_add = []
self._to_remove = []
self._is_ticking = True
for store_key, (args, kwargs) in self.subscriptions.iteritems():
for store_key, (args, kwargs) in self.subscriptions.items():
callback = yield kwargs.pop("_callback", "at_tick")
obj = yield kwargs.pop("_obj", None)
try:
@ -286,7 +286,7 @@ class TickerPool(object):
if interval and interval in self.tickers:
self.tickers[interval].stop()
else:
for ticker in self.tickers.values():
for ticker in list(self.tickers.values()):
ticker.stop()
@ -332,10 +332,10 @@ class TickerHandler(object):
outobj, outpath, outcallfunc = None, None, None
if callable(callback):
if inspect.ismethod(callback):
outobj = callback.im_self
outcallfunc = callback.im_func.func_name
outobj = callback.__self__
outcallfunc = callback.__func__.__name__
elif inspect.isfunction(callback):
outpath = "%s.%s" % (callback.__module__, callback.func_name)
outpath = "%s.%s" % (callback.__module__, callback.__name__)
outcallfunc = callback
else:
raise TypeError("%s is not a callable function or method." % callback)
@ -371,8 +371,8 @@ class TickerHandler(object):
interval = int(interval)
persistent = bool(persistent)
packed_obj = pack_dbobj(obj)
methodname = callfunc if callfunc and isinstance(callfunc, basestring) else None
outpath = path if path and isinstance(path, basestring) else None
methodname = callfunc if callfunc and isinstance(callfunc, str) else None
outpath = path if path and isinstance(path, str) else None
return (packed_obj, methodname, outpath, interval, idstring, persistent)
def save(self):
@ -386,16 +386,16 @@ class TickerHandler(object):
if self.ticker_storage:
# get the current times so the tickers can be restarted with a delay later
start_delays = dict((interval, ticker.task.next_call_time())
for interval, ticker in self.ticker_pool.tickers.items())
for interval, ticker in list(self.ticker_pool.tickers.items()))
# remove any subscriptions that lost its object in the interim
to_save = {store_key: (args, kwargs) for store_key, (args, kwargs) in self.ticker_storage.items()
to_save = {store_key: (args, kwargs) for store_key, (args, kwargs) in list(self.ticker_storage.items())
if ((store_key[1] and ("_obj" in kwargs and kwargs["_obj"].pk) and
hasattr(kwargs["_obj"], store_key[1])) or # a valid method with existing obj
store_key[2])} # a path given
# update the timers for the tickers
for store_key, (args, kwargs) in to_save.items():
for store_key, (args, kwargs) in list(to_save.items()):
interval = store_key[1]
# this is a mutable, so it's updated in-place in ticker_storage
kwargs["_start_delay"] = start_delays.get(interval, None)
@ -423,7 +423,7 @@ class TickerHandler(object):
restored_tickers = dbunserialize(restored_tickers)
self.ticker_storage = {}
for store_key, (args, kwargs) in restored_tickers.iteritems():
for store_key, (args, kwargs) in restored_tickers.items():
try:
# at this point obj is the actual object (or None) due to how
# the dbunserialize works
@ -431,7 +431,7 @@ class TickerHandler(object):
if not persistent and not server_reload:
# this ticker will not be restarted
continue
if isinstance(callfunc, basestring) and not obj:
if isinstance(callfunc, str) and not obj:
# methods must have an existing object
continue
# we must rebuild the store_key here since obj must not be
@ -562,7 +562,7 @@ class TickerHandler(object):
if interval is None:
# return dict of all, ordered by interval
return dict((interval, ticker.subscriptions)
for interval, ticker in self.ticker_pool.tickers.iteritems())
for interval, ticker in self.ticker_pool.tickers.items())
else:
# get individual interval
ticker = self.ticker_pool.tickers.get(interval, None)
@ -579,8 +579,8 @@ class TickerHandler(object):
"""
store_keys = []
for ticker in self.ticker_pool.tickers.itervalues():
for (objtup, callfunc, path, interval, idstring, persistent), (args, kwargs) in ticker.subscriptions.iteritems():
for ticker in self.ticker_pool.tickers.values():
for (objtup, callfunc, path, interval, idstring, persistent), (args, kwargs) in ticker.subscriptions.items():
store_keys.append((kwargs.get("_obj", None), callfunc, path, interval, idstring, persistent))
return store_keys

View file

@ -15,16 +15,16 @@ Server - (AMP server) Handles all mud operations. The server holds its own list
at startup and when a session connects/disconnects
"""
from __future__ import print_function
# imports needed on both server and portal side
import os
import time
from collections import defaultdict, namedtuple
from itertools import count
from cStringIO import StringIO
from io import StringIO
try:
import cPickle as pickle
import pickle as pickle
except ImportError:
import pickle
from twisted.protocols import amp

View file

@ -9,7 +9,7 @@ and portal through the evennia_runner. Run without arguments to get a
menu. Run the script with the -h flag to see usage information.
"""
from __future__ import print_function
from builtins import input, range
import os
@ -535,7 +535,7 @@ def create_settings_file(init=True, secret_settings=False):
if not init:
# if not --init mode, settings file may already exist from before
if os.path.exists(settings_path):
inp = input("%s already exists. Do you want to reset it? y/[N]> " % settings_path)
inp = eval(input("%s already exists. Do you want to reset it? y/[N]> " % settings_path))
if not inp.lower() == 'y':
print ("Aborted.")
return
@ -601,9 +601,9 @@ def check_database():
# Check so a database exists and is accessible
from django.db import connection
tables = connection.introspection.get_table_list(connection.cursor())
if not tables or not isinstance(tables[0], basestring): # django 1.8+
if not tables or not isinstance(tables[0], str): # django 1.8+
tables = [tableinfo.name for tableinfo in tables]
if tables and u'accounts_accountdb' in tables:
if tables and 'accounts_accountdb' in tables:
# database exists and seems set up. Initialize evennia.
evennia._init()
# Try to get Account#1
@ -632,7 +632,7 @@ def check_database():
res = ""
while res.upper() != "Y":
# ask for permission
res = input("Continue [Y]/N: ")
res = eval(input("Continue [Y]/N: "))
if res.upper() == "N":
sys.exit()
elif not res:
@ -993,9 +993,9 @@ def list_settings(keys):
# a specific key
table = evtable.EvTable(width=131)
keys = [key.upper() for key in keys]
confs = dict((key, var) for key, var in evsettings.__dict__.items()
confs = dict((key, var) for key, var in list(evsettings.__dict__.items())
if key in keys)
for key, val in confs.items():
for key, val in list(confs.items()):
table.add_row(key, str(val))
print(table)
@ -1009,18 +1009,18 @@ def run_menu():
# menu loop
print(MENU)
inp = input(" option > ")
inp = eval(input(" option > "))
# quitting and help
if inp.lower() == 'q':
return
elif inp.lower() == 'h':
print(HELP_ENTRY)
input("press <return> to continue ...")
eval(input("press <return> to continue ..."))
continue
elif inp.lower() in ('v', 'i', 'a'):
print(show_version_info(about=True))
input("press <return> to continue ...")
eval(input("press <return> to continue ..."))
continue
# options

View file

@ -14,13 +14,13 @@ upon returning, or not. A process returning != 0 will always stop, no
matter the value of this file.
"""
from __future__ import print_function
import os
import sys
from argparse import ArgumentParser
from subprocess import Popen
import Queue
import thread
import queue
import _thread
import evennia
try:
@ -143,7 +143,7 @@ def start_services(server_argv, portal_argv, doexit=False):
and then restarts them when they finish.
"""
global SERVER, PORTAL
processes = Queue.Queue()
processes = queue.Queue()
def server_waiter(queue):
try:
@ -167,7 +167,7 @@ def start_services(server_argv, portal_argv, doexit=False):
try:
if not doexit and get_restart_mode(PORTAL_RESTART) == "True":
# start portal as interactive, reloadable thread
PORTAL = thread.start_new_thread(portal_waiter, (processes, ))
PORTAL = _thread.start_new_thread(portal_waiter, (processes, ))
else:
# normal operation: start portal as a daemon;
# we don't care to monitor it for restart
@ -182,7 +182,7 @@ def start_services(server_argv, portal_argv, doexit=False):
SERVER = Popen(server_argv, env=getenv())
else:
# start server as a reloadable thread
SERVER = thread.start_new_thread(server_waiter, (processes, ))
SERVER = _thread.start_new_thread(server_waiter, (processes, ))
except IOError as e:
print(PROCESS_IOERROR.format(component="Server", traceback=e))
return
@ -207,14 +207,14 @@ def start_services(server_argv, portal_argv, doexit=False):
if (message == "server_stopped" and int(rc) == 0 and
get_restart_mode(SERVER_RESTART) in ("True", "reload", "reset")):
print(PROCESS_RESTART.format(component="Server"))
SERVER = thread.start_new_thread(server_waiter, (processes, ))
SERVER = _thread.start_new_thread(server_waiter, (processes, ))
continue
# normally the portal is not reloaded since it's run as a daemon.
if (message == "portal_stopped" and int(rc) == 0 and
get_restart_mode(PORTAL_RESTART) == "True"):
print(PROCESS_RESTART.format(component="Portal"))
PORTAL = thread.start_new_thread(portal_waiter, (processes, ))
PORTAL = _thread.start_new_thread(portal_waiter, (processes, ))
continue
break
except ReactorNotRunning:

View file

@ -5,7 +5,7 @@ other things.
Everything starts at handle_setup()
"""
from __future__ import print_function
import time
from django.conf import settings

Some files were not shown because too many files have changed in this diff Show more