Python
From WiCWiki
|
Structure
About modules
import
Modules in python can be seen as classes. For example, if you import a module named base you can reach its contents with the . operator. Ex:
base.py
def DebugMessage( aDebugString ): """ Prints a given message to stdout """ print aDebugString
test.py
import base base.DebugMessage( "This is my debug message" )
from
When you import modules you can choose to just import some parts of a module. If we only need DebugMessage from base.py:
base.py
def DebugMessage( aDebugString ): """ Prints a given message to stdout """ print aDebugString def UnusedMethod( anUnusedArgument ): """ Does something we are not interested in """ return anUnusedArgument
test.py
from base import DebugMessage DebugMessage( "This is my debug message" )
WARNING By importing like this you disrupt the reload functionality. In the above example you will need to reimport DebugMessage into test.py after reloading the base module.
as
If you need to avoid naming conflicts or shorten down a long identifier you can use as importing. This way the imported entity will be referred to by another name. Ex:
base.py
def DebugMessage( aDebugString ): """ Prints a given message to stdout """ print aDebugString def UnusedMethod( anUnusedArgument ): """ Does something we are not interested in """ return anUnusedArgument
test.py
from base import DebugMessage as MSG def DebugMessage( aDebugString ): """ Prints given message to stdout with the prefix 'Woot' """ print 'Woot' + aDebugString MSG( "This is my debug message" ) DebugMessage( "This is my debugmessage prefixed with Woot" )
Another bonus is that this way will not affect the ability to reload. If you make a change in the above base.py and don't want to reload the game you can just reload base.py from the console and MSG will updated automagically.
Namespaces
If you have a scriptfile server.py ...:
server.py
import base, game def MyFunction( aString ): print aString
...and base.py would look like this...:
base.py
def MyFunction( aString ): print aString
... it would be perfectly ok to import base.py in server.py even if server.py already have it's own MyFunction. This because the entities imported from base will be in it's own namespace, base. If you would like to call base.py's MyFunction from server.py you just need to prefix it with base.