I'm having trouble with the following code:
import tweepy
from tweet import TweetBuilder
from libs.session import Session
class GameHandler:
open_sessions = []
def get_session(self, sessionname):
for session in GameHandler.open_sessions:
#FOLLOWING STATEMENT GOES WRONG
if session.roomname == sessionname:
return session
return None
def session_create(self, sessionname, owner_id, owner_name):
new = Session(sessionname, owner_id, owner_name).add_player(owner_id, owner_name)
GameHandler.open_sessions.append(new)
return TweetBuilder.new_session(sessionname, owner_name)
def session_join(self, sessionname, player_id, player_name):
session = self.get_session(sessionname)
if session != None:
session.add_player(player_id, player_name)
return TweetBuilder.join_session(session, player_name)
return ""
Also part of the Session class:
class Session:
def __init__(self, name, owner_id, owner_name):
#keep track of tweets
self.tweetid_start = None
self.tweetid_current = None
#game elements
self.roomname = name
#THIS LINE WORKS CORRECTLY
print(self.roomname)
self.players = []
self.currentround = None
self.roundnumber = 0
self.players.append(Player(owner_id, owner_name))
When I call session_create()
everything works fine. The app runs Session.__init__()
, the print statement prints self.roomname
.
When I call session_join()
, and session_join()
calls get_session()
problems arise. The for loop is supposed to iterate over the Session-array called open_sessions
, but the moment it tries to access the Session-attribute called 'roomname' it gives me the following error:
'NoneType' object has no attribute 'roomname'
Why are my Session-objects suddenly NoneType?
Thanks in advance.
The problem is here:
new = Session(sessionname, owner_id, owner_name).add_player(owner_id, owner_name)
GameHandler.open_sessions.append(new)
By immediately calling add_player
on the newly created Session
, new
is not the Session
but the result of add_player
, and whatever that does, it seems to return None
. Thus you are adding a bunch of None
objects to your open_sessions
list. Use this instead:
new = Session(sessionname, owner_id, owner_name)
new.add_player(owner_id, owner_name)
GameHandler.open_sessions.append(new)
Or if you want to keep it the way it was, you could change your Session
class to provide kind of a "fluent interface" and have add_player
(and other methods) return self
:
class Session:
...
def add_player(self, id_, name):
....
return self