getInfoTypeForString not working via import

Xyth

History Rewritten
Joined
Jul 14, 2004
Messages
4,106
Location
Aotearoa
I'm trying to consolidate a number of constants that I use into a single, imported Python file so they can be easily reassigned later if need be. These are all defined at the top of the file, in the global namespace:

HR.py
Code:
gc = CyGlobalContext()
Civic_CorporationExtraProduction	= gc.getInfoTypeForString('CIVIC_INDUSTRIALISM'), 2
Civic_CorporationExtraCommerce		= gc.getInfoTypeForString('CIVIC_FREE_MARKET'), 2
Civic_CorporationHappiness		= gc.getInfoTypeForString('CIVIC_SOCIAL_WELFARE'), 2
Civic_CorporationHealth			= gc.getInfoTypeForString('CIVIC_ENVIRONMENTALISM'), 2
Civic_ExtraChoppingProduction		= gc.getInfoTypeForString('CIVIC_INDUSTRIALISM')
Civic_GreatPeopleGoldenAge		= gc.getInfoTypeForString('CIVIC_EQUAL_RIGHTS')

However if I do this, either from CvEventManager.py or the python console in game:

Code:
import HR
print HR.Civic_ExtraChoppingProduction
print HR.Civic_CorporationHappiness

The output is:


The InfoType for the civic is always -1, with any of the above, even though those civic definitions all exist and work elsewhere. There's other ways I could implement this but it would be good to know what am I misunderstanding. Any ideas?
 
Python is loaded before the XML data. Statements at the module level (not inside a class or function definition) in a Python file are executed when the file is loaded. The event manager is loaded when Python is initialized, and therefore everything imported by it at the module level is loaded then too.

Looking for a non-existant info type value always returns -1. Since none of that data has been loaded yet, none of those definitions exist and you therefore get -1.

What you need is to have the definitions in a function that is called after the game's XML is loaded. Perhaps the onGameStart event handler (and onLoadGame too, since that is run instead when loading a saved game). They can be set up at the module level (defined to be -1, or whatever) and in the function where the values are assigned you declare them as global.

Example:
Contents of the file Foo.py:
Code:
gc = CyGlobalContext()
theFoo = -1

def initFoo():
	global theFoo
	theFoo = gc.getInfoTypeForString('THING_FOO')

Import this file into CvEventManager.py.
In onGameStart run the initFoo function.
Also in onLoadGame.
Bingo.

Alternatively, it should work to run it in the event manager's __init__ function instead of 2 different places.

Or something like that.
 
Ah that makes sense now. Thanks!
 
Back
Top Bottom