code
stringlengths
2.5k
150k
kind
stringclasses
1 value
python quopri — Encode and decode MIME quoted-printable data quopri — Encode and decode MIME quoted-printable data ===================================================== **Source code:** [Lib/quopri.py](https://github.com/python/cpython/tree/3.9/Lib/quopri.py) This module performs quoted-printable transport encoding and decoding, as defined in [**RFC 1521**](https://tools.ietf.org/html/rfc1521.html): “MIME (Multipurpose Internet Mail Extensions) Part One: Mechanisms for Specifying and Describing the Format of Internet Message Bodies”. The quoted-printable encoding is designed for data where there are relatively few nonprintable characters; the base64 encoding scheme available via the [`base64`](base64#module-base64 "base64: RFC 3548: Base16, Base32, Base64 Data Encodings; Base85 and Ascii85") module is more compact if there are many such characters, as when sending a graphics file. `quopri.decode(input, output, header=False)` Decode the contents of the *input* file and write the resulting decoded binary data to the *output* file. *input* and *output* must be [binary file objects](../glossary#term-file-object). If the optional argument *header* is present and true, underscore will be decoded as space. This is used to decode “Q”-encoded headers as described in [**RFC 1522**](https://tools.ietf.org/html/rfc1522.html): “MIME (Multipurpose Internet Mail Extensions) Part Two: Message Header Extensions for Non-ASCII Text”. `quopri.encode(input, output, quotetabs, header=False)` Encode the contents of the *input* file and write the resulting quoted-printable data to the *output* file. *input* and *output* must be [binary file objects](../glossary#term-file-object). *quotetabs*, a non-optional flag which controls whether to encode embedded spaces and tabs; when true it encodes such embedded whitespace, and when false it leaves them unencoded. Note that spaces and tabs appearing at the end of lines are always encoded, as per [**RFC 1521**](https://tools.ietf.org/html/rfc1521.html). *header* is a flag which controls if spaces are encoded as underscores as per [**RFC 1522**](https://tools.ietf.org/html/rfc1522.html). `quopri.decodestring(s, header=False)` Like [`decode()`](#quopri.decode "quopri.decode"), except that it accepts a source [`bytes`](stdtypes#bytes "bytes") and returns the corresponding decoded [`bytes`](stdtypes#bytes "bytes"). `quopri.encodestring(s, quotetabs=False, header=False)` Like [`encode()`](#quopri.encode "quopri.encode"), except that it accepts a source [`bytes`](stdtypes#bytes "bytes") and returns the corresponding encoded [`bytes`](stdtypes#bytes "bytes"). By default, it sends a `False` value to *quotetabs* parameter of the [`encode()`](#quopri.encode "quopri.encode") function. See also `Module` [`base64`](base64#module-base64 "base64: RFC 3548: Base16, Base32, Base64 Data Encodings; Base85 and Ascii85") Encode and decode MIME base64 data python wsgiref — WSGI Utilities and Reference Implementation wsgiref — WSGI Utilities and Reference Implementation ===================================================== The Web Server Gateway Interface (WSGI) is a standard interface between web server software and web applications written in Python. Having a standard interface makes it easy to use an application that supports WSGI with a number of different web servers. Only authors of web servers and programming frameworks need to know every detail and corner case of the WSGI design. You don’t need to understand every detail of WSGI just to install a WSGI application or to write a web application using an existing framework. [`wsgiref`](#module-wsgiref "wsgiref: WSGI Utilities and Reference Implementation.") is a reference implementation of the WSGI specification that can be used to add WSGI support to a web server or framework. It provides utilities for manipulating WSGI environment variables and response headers, base classes for implementing WSGI servers, a demo HTTP server that serves WSGI applications, and a validation tool that checks WSGI servers and applications for conformance to the WSGI specification ([**PEP 3333**](https://www.python.org/dev/peps/pep-3333)). See [wsgi.readthedocs.io](https://wsgi.readthedocs.io/) for more information about WSGI, and links to tutorials and other resources. wsgiref.util – WSGI environment utilities ----------------------------------------- This module provides a variety of utility functions for working with WSGI environments. A WSGI environment is a dictionary containing HTTP request variables as described in [**PEP 3333**](https://www.python.org/dev/peps/pep-3333). All of the functions taking an *environ* parameter expect a WSGI-compliant dictionary to be supplied; please see [**PEP 3333**](https://www.python.org/dev/peps/pep-3333) for a detailed specification. `wsgiref.util.guess_scheme(environ)` Return a guess for whether `wsgi.url_scheme` should be “http” or “https”, by checking for a `HTTPS` environment variable in the *environ* dictionary. The return value is a string. This function is useful when creating a gateway that wraps CGI or a CGI-like protocol such as FastCGI. Typically, servers providing such protocols will include a `HTTPS` variable with a value of “1”, “yes”, or “on” when a request is received via SSL. So, this function returns “https” if such a value is found, and “http” otherwise. `wsgiref.util.request_uri(environ, include_query=True)` Return the full request URI, optionally including the query string, using the algorithm found in the “URL Reconstruction” section of [**PEP 3333**](https://www.python.org/dev/peps/pep-3333). If *include\_query* is false, the query string is not included in the resulting URI. `wsgiref.util.application_uri(environ)` Similar to [`request_uri()`](#wsgiref.util.request_uri "wsgiref.util.request_uri"), except that the `PATH_INFO` and `QUERY_STRING` variables are ignored. The result is the base URI of the application object addressed by the request. `wsgiref.util.shift_path_info(environ)` Shift a single name from `PATH_INFO` to `SCRIPT_NAME` and return the name. The *environ* dictionary is *modified* in-place; use a copy if you need to keep the original `PATH_INFO` or `SCRIPT_NAME` intact. If there are no remaining path segments in `PATH_INFO`, `None` is returned. Typically, this routine is used to process each portion of a request URI path, for example to treat the path as a series of dictionary keys. This routine modifies the passed-in environment to make it suitable for invoking another WSGI application that is located at the target URI. For example, if there is a WSGI application at `/foo`, and the request URI path is `/foo/bar/baz`, and the WSGI application at `/foo` calls [`shift_path_info()`](#wsgiref.util.shift_path_info "wsgiref.util.shift_path_info"), it will receive the string “bar”, and the environment will be updated to be suitable for passing to a WSGI application at `/foo/bar`. That is, `SCRIPT_NAME` will change from `/foo` to `/foo/bar`, and `PATH_INFO` will change from `/bar/baz` to `/baz`. When `PATH_INFO` is just a “/”, this routine returns an empty string and appends a trailing slash to `SCRIPT_NAME`, even though empty path segments are normally ignored, and `SCRIPT_NAME` doesn’t normally end in a slash. This is intentional behavior, to ensure that an application can tell the difference between URIs ending in `/x` from ones ending in `/x/` when using this routine to do object traversal. `wsgiref.util.setup_testing_defaults(environ)` Update *environ* with trivial defaults for testing purposes. This routine adds various parameters required for WSGI, including `HTTP_HOST`, `SERVER_NAME`, `SERVER_PORT`, `REQUEST_METHOD`, `SCRIPT_NAME`, `PATH_INFO`, and all of the [**PEP 3333**](https://www.python.org/dev/peps/pep-3333)-defined `wsgi.*` variables. It only supplies default values, and does not replace any existing settings for these variables. This routine is intended to make it easier for unit tests of WSGI servers and applications to set up dummy environments. It should NOT be used by actual WSGI servers or applications, since the data is fake! Example usage: ``` from wsgiref.util import setup_testing_defaults from wsgiref.simple_server import make_server # A relatively simple WSGI application. It's going to print out the # environment dictionary after being updated by setup_testing_defaults def simple_app(environ, start_response): setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/plain; charset=utf-8')] start_response(status, headers) ret = [("%s: %s\n" % (key, value)).encode("utf-8") for key, value in environ.items()] return ret with make_server('', 8000, simple_app) as httpd: print("Serving on port 8000...") httpd.serve_forever() ``` In addition to the environment functions above, the [`wsgiref.util`](#module-wsgiref.util "wsgiref.util: WSGI environment utilities.") module also provides these miscellaneous utilities: `wsgiref.util.is_hop_by_hop(header_name)` Return `True` if ‘header\_name’ is an HTTP/1.1 “Hop-by-Hop” header, as defined by [**RFC 2616**](https://tools.ietf.org/html/rfc2616.html). `class wsgiref.util.FileWrapper(filelike, blksize=8192)` A wrapper to convert a file-like object to an [iterator](../glossary#term-iterator). The resulting objects support both [`__getitem__()`](../reference/datamodel#object.__getitem__ "object.__getitem__") and [`__iter__()`](../reference/datamodel#object.__iter__ "object.__iter__") iteration styles, for compatibility with Python 2.1 and Jython. As the object is iterated over, the optional *blksize* parameter will be repeatedly passed to the *filelike* object’s `read()` method to obtain bytestrings to yield. When `read()` returns an empty bytestring, iteration is ended and is not resumable. If *filelike* has a `close()` method, the returned object will also have a `close()` method, and it will invoke the *filelike* object’s `close()` method when called. Example usage: ``` from io import StringIO from wsgiref.util import FileWrapper # We're using a StringIO-buffer for as the file-like object filelike = StringIO("This is an example file-like object"*10) wrapper = FileWrapper(filelike, blksize=5) for chunk in wrapper: print(chunk) ``` Deprecated since version 3.8: Support for [`sequence protocol`](../reference/datamodel#object.__getitem__ "object.__getitem__") is deprecated. wsgiref.headers – WSGI response header tools -------------------------------------------- This module provides a single class, [`Headers`](#wsgiref.headers.Headers "wsgiref.headers.Headers"), for convenient manipulation of WSGI response headers using a mapping-like interface. `class wsgiref.headers.Headers([headers])` Create a mapping-like object wrapping *headers*, which must be a list of header name/value tuples as described in [**PEP 3333**](https://www.python.org/dev/peps/pep-3333). The default value of *headers* is an empty list. [`Headers`](#wsgiref.headers.Headers "wsgiref.headers.Headers") objects support typical mapping operations including [`__getitem__()`](../reference/datamodel#object.__getitem__ "object.__getitem__"), `get()`, [`__setitem__()`](../reference/datamodel#object.__setitem__ "object.__setitem__"), `setdefault()`, [`__delitem__()`](../reference/datamodel#object.__delitem__ "object.__delitem__") and [`__contains__()`](../reference/datamodel#object.__contains__ "object.__contains__"). For each of these methods, the key is the header name (treated case-insensitively), and the value is the first value associated with that header name. Setting a header deletes any existing values for that header, then adds a new value at the end of the wrapped header list. Headers’ existing order is generally maintained, with new headers added to the end of the wrapped list. Unlike a dictionary, [`Headers`](#wsgiref.headers.Headers "wsgiref.headers.Headers") objects do not raise an error when you try to get or delete a key that isn’t in the wrapped header list. Getting a nonexistent header just returns `None`, and deleting a nonexistent header does nothing. [`Headers`](#wsgiref.headers.Headers "wsgiref.headers.Headers") objects also support `keys()`, `values()`, and `items()` methods. The lists returned by `keys()` and `items()` can include the same key more than once if there is a multi-valued header. The `len()` of a [`Headers`](#wsgiref.headers.Headers "wsgiref.headers.Headers") object is the same as the length of its `items()`, which is the same as the length of the wrapped header list. In fact, the `items()` method just returns a copy of the wrapped header list. Calling `bytes()` on a [`Headers`](#wsgiref.headers.Headers "wsgiref.headers.Headers") object returns a formatted bytestring suitable for transmission as HTTP response headers. Each header is placed on a line with its value, separated by a colon and a space. Each line is terminated by a carriage return and line feed, and the bytestring is terminated with a blank line. In addition to their mapping interface and formatting features, [`Headers`](#wsgiref.headers.Headers "wsgiref.headers.Headers") objects also have the following methods for querying and adding multi-valued headers, and for adding headers with MIME parameters: `get_all(name)` Return a list of all the values for the named header. The returned list will be sorted in the order they appeared in the original header list or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. If no fields exist with the given name, returns an empty list. `add_header(name, value, **_params)` Add a (possibly multi-valued) header, with optional MIME parameters specified via keyword arguments. *name* is the header field to add. Keyword arguments can be used to set MIME parameters for the header field. Each parameter must be a string or `None`. Underscores in parameter names are converted to dashes, since dashes are illegal in Python identifiers, but many MIME parameter names include dashes. If the parameter value is a string, it is added to the header value parameters in the form `name="value"`. If it is `None`, only the parameter name is added. (This is used for MIME parameters without a value.) Example usage: ``` h.add_header('content-disposition', 'attachment', filename='bud.gif') ``` The above will add a header that looks like this: ``` Content-Disposition: attachment; filename="bud.gif" ``` Changed in version 3.5: *headers* parameter is optional. wsgiref.simple\_server – a simple WSGI HTTP server -------------------------------------------------- This module implements a simple HTTP server (based on [`http.server`](http.server#module-http.server "http.server: HTTP server and request handlers.")) that serves WSGI applications. Each server instance serves a single WSGI application on a given host and port. If you want to serve multiple applications on a single host and port, you should create a WSGI application that parses `PATH_INFO` to select which application to invoke for each request. (E.g., using the `shift_path_info()` function from [`wsgiref.util`](#module-wsgiref.util "wsgiref.util: WSGI environment utilities.").) `wsgiref.simple_server.make_server(host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler)` Create a new WSGI server listening on *host* and *port*, accepting connections for *app*. The return value is an instance of the supplied *server\_class*, and will process requests using the specified *handler\_class*. *app* must be a WSGI application object, as defined by [**PEP 3333**](https://www.python.org/dev/peps/pep-3333). Example usage: ``` from wsgiref.simple_server import make_server, demo_app with make_server('', 8000, demo_app) as httpd: print("Serving HTTP on port 8000...") # Respond to requests until process is killed httpd.serve_forever() # Alternative: serve one request, then exit httpd.handle_request() ``` `wsgiref.simple_server.demo_app(environ, start_response)` This function is a small but complete WSGI application that returns a text page containing the message “Hello world!” and a list of the key/value pairs provided in the *environ* parameter. It’s useful for verifying that a WSGI server (such as [`wsgiref.simple_server`](#module-wsgiref.simple_server "wsgiref.simple_server: A simple WSGI HTTP server.")) is able to run a simple WSGI application correctly. `class wsgiref.simple_server.WSGIServer(server_address, RequestHandlerClass)` Create a [`WSGIServer`](#wsgiref.simple_server.WSGIServer "wsgiref.simple_server.WSGIServer") instance. *server\_address* should be a `(host,port)` tuple, and *RequestHandlerClass* should be the subclass of [`http.server.BaseHTTPRequestHandler`](http.server#http.server.BaseHTTPRequestHandler "http.server.BaseHTTPRequestHandler") that will be used to process requests. You do not normally need to call this constructor, as the [`make_server()`](#wsgiref.simple_server.make_server "wsgiref.simple_server.make_server") function can handle all the details for you. [`WSGIServer`](#wsgiref.simple_server.WSGIServer "wsgiref.simple_server.WSGIServer") is a subclass of [`http.server.HTTPServer`](http.server#http.server.HTTPServer "http.server.HTTPServer"), so all of its methods (such as `serve_forever()` and `handle_request()`) are available. [`WSGIServer`](#wsgiref.simple_server.WSGIServer "wsgiref.simple_server.WSGIServer") also provides these WSGI-specific methods: `set_app(application)` Sets the callable *application* as the WSGI application that will receive requests. `get_app()` Returns the currently-set application callable. Normally, however, you do not need to use these additional methods, as [`set_app()`](#wsgiref.simple_server.WSGIServer.set_app "wsgiref.simple_server.WSGIServer.set_app") is normally called by [`make_server()`](#wsgiref.simple_server.make_server "wsgiref.simple_server.make_server"), and the [`get_app()`](#wsgiref.simple_server.WSGIServer.get_app "wsgiref.simple_server.WSGIServer.get_app") exists mainly for the benefit of request handler instances. `class wsgiref.simple_server.WSGIRequestHandler(request, client_address, server)` Create an HTTP handler for the given *request* (i.e. a socket), *client\_address* (a `(host,port)` tuple), and *server* ([`WSGIServer`](#wsgiref.simple_server.WSGIServer "wsgiref.simple_server.WSGIServer") instance). You do not need to create instances of this class directly; they are automatically created as needed by [`WSGIServer`](#wsgiref.simple_server.WSGIServer "wsgiref.simple_server.WSGIServer") objects. You can, however, subclass this class and supply it as a *handler\_class* to the [`make_server()`](#wsgiref.simple_server.make_server "wsgiref.simple_server.make_server") function. Some possibly relevant methods for overriding in subclasses: `get_environ()` Returns a dictionary containing the WSGI environment for a request. The default implementation copies the contents of the [`WSGIServer`](#wsgiref.simple_server.WSGIServer "wsgiref.simple_server.WSGIServer") object’s `base_environ` dictionary attribute and then adds various headers derived from the HTTP request. Each call to this method should return a new dictionary containing all of the relevant CGI environment variables as specified in [**PEP 3333**](https://www.python.org/dev/peps/pep-3333). `get_stderr()` Return the object that should be used as the `wsgi.errors` stream. The default implementation just returns `sys.stderr`. `handle()` Process the HTTP request. The default implementation creates a handler instance using a [`wsgiref.handlers`](#module-wsgiref.handlers "wsgiref.handlers: WSGI server/gateway base classes.") class to implement the actual WSGI application interface. wsgiref.validate — WSGI conformance checker ------------------------------------------- When creating new WSGI application objects, frameworks, servers, or middleware, it can be useful to validate the new code’s conformance using [`wsgiref.validate`](#module-wsgiref.validate "wsgiref.validate: WSGI conformance checker."). This module provides a function that creates WSGI application objects that validate communications between a WSGI server or gateway and a WSGI application object, to check both sides for protocol conformance. Note that this utility does not guarantee complete [**PEP 3333**](https://www.python.org/dev/peps/pep-3333) compliance; an absence of errors from this module does not necessarily mean that errors do not exist. However, if this module does produce an error, then it is virtually certain that either the server or application is not 100% compliant. This module is based on the `paste.lint` module from Ian Bicking’s “Python Paste” library. `wsgiref.validate.validator(application)` Wrap *application* and return a new WSGI application object. The returned application will forward all requests to the original *application*, and will check that both the *application* and the server invoking it are conforming to the WSGI specification and to [**RFC 2616**](https://tools.ietf.org/html/rfc2616.html). Any detected nonconformance results in an [`AssertionError`](exceptions#AssertionError "AssertionError") being raised; note, however, that how these errors are handled is server-dependent. For example, [`wsgiref.simple_server`](#module-wsgiref.simple_server "wsgiref.simple_server: A simple WSGI HTTP server.") and other servers based on [`wsgiref.handlers`](#module-wsgiref.handlers "wsgiref.handlers: WSGI server/gateway base classes.") (that don’t override the error handling methods to do something else) will simply output a message that an error has occurred, and dump the traceback to `sys.stderr` or some other error stream. This wrapper may also generate output using the [`warnings`](warnings#module-warnings "warnings: Issue warning messages and control their disposition.") module to indicate behaviors that are questionable but which may not actually be prohibited by [**PEP 3333**](https://www.python.org/dev/peps/pep-3333). Unless they are suppressed using Python command-line options or the [`warnings`](warnings#module-warnings "warnings: Issue warning messages and control their disposition.") API, any such warnings will be written to `sys.stderr` (*not* `wsgi.errors`, unless they happen to be the same object). Example usage: ``` from wsgiref.validate import validator from wsgiref.simple_server import make_server # Our callable object which is intentionally not compliant to the # standard, so the validator is going to break def simple_app(environ, start_response): status = '200 OK' # HTTP Status headers = [('Content-type', 'text/plain')] # HTTP Headers start_response(status, headers) # This is going to break because we need to return a list, and # the validator is going to inform us return b"Hello World" # This is the application wrapped in a validator validator_app = validator(simple_app) with make_server('', 8000, validator_app) as httpd: print("Listening on port 8000....") httpd.serve_forever() ``` wsgiref.handlers – server/gateway base classes ---------------------------------------------- This module provides base handler classes for implementing WSGI servers and gateways. These base classes handle most of the work of communicating with a WSGI application, as long as they are given a CGI-like environment, along with input, output, and error streams. `class wsgiref.handlers.CGIHandler` CGI-based invocation via `sys.stdin`, `sys.stdout`, `sys.stderr` and `os.environ`. This is useful when you have a WSGI application and want to run it as a CGI script. Simply invoke `CGIHandler().run(app)`, where `app` is the WSGI application object you wish to invoke. This class is a subclass of [`BaseCGIHandler`](#wsgiref.handlers.BaseCGIHandler "wsgiref.handlers.BaseCGIHandler") that sets `wsgi.run_once` to true, `wsgi.multithread` to false, and `wsgi.multiprocess` to true, and always uses [`sys`](sys#module-sys "sys: Access system-specific parameters and functions.") and [`os`](os#module-os "os: Miscellaneous operating system interfaces.") to obtain the necessary CGI streams and environment. `class wsgiref.handlers.IISCGIHandler` A specialized alternative to [`CGIHandler`](#wsgiref.handlers.CGIHandler "wsgiref.handlers.CGIHandler"), for use when deploying on Microsoft’s IIS web server, without having set the config allowPathInfo option (IIS>=7) or metabase allowPathInfoForScriptMappings (IIS<7). By default, IIS gives a `PATH_INFO` that duplicates the `SCRIPT_NAME` at the front, causing problems for WSGI applications that wish to implement routing. This handler strips any such duplicated path. IIS can be configured to pass the correct `PATH_INFO`, but this causes another bug where `PATH_TRANSLATED` is wrong. Luckily this variable is rarely used and is not guaranteed by WSGI. On IIS<7, though, the setting can only be made on a vhost level, affecting all other script mappings, many of which break when exposed to the `PATH_TRANSLATED` bug. For this reason IIS<7 is almost never deployed with the fix (Even IIS7 rarely uses it because there is still no UI for it.). There is no way for CGI code to tell whether the option was set, so a separate handler class is provided. It is used in the same way as [`CGIHandler`](#wsgiref.handlers.CGIHandler "wsgiref.handlers.CGIHandler"), i.e., by calling `IISCGIHandler().run(app)`, where `app` is the WSGI application object you wish to invoke. New in version 3.2. `class wsgiref.handlers.BaseCGIHandler(stdin, stdout, stderr, environ, multithread=True, multiprocess=False)` Similar to [`CGIHandler`](#wsgiref.handlers.CGIHandler "wsgiref.handlers.CGIHandler"), but instead of using the [`sys`](sys#module-sys "sys: Access system-specific parameters and functions.") and [`os`](os#module-os "os: Miscellaneous operating system interfaces.") modules, the CGI environment and I/O streams are specified explicitly. The *multithread* and *multiprocess* values are used to set the `wsgi.multithread` and `wsgi.multiprocess` flags for any applications run by the handler instance. This class is a subclass of [`SimpleHandler`](#wsgiref.handlers.SimpleHandler "wsgiref.handlers.SimpleHandler") intended for use with software other than HTTP “origin servers”. If you are writing a gateway protocol implementation (such as CGI, FastCGI, SCGI, etc.) that uses a `Status:` header to send an HTTP status, you probably want to subclass this instead of [`SimpleHandler`](#wsgiref.handlers.SimpleHandler "wsgiref.handlers.SimpleHandler"). `class wsgiref.handlers.SimpleHandler(stdin, stdout, stderr, environ, multithread=True, multiprocess=False)` Similar to [`BaseCGIHandler`](#wsgiref.handlers.BaseCGIHandler "wsgiref.handlers.BaseCGIHandler"), but designed for use with HTTP origin servers. If you are writing an HTTP server implementation, you will probably want to subclass this instead of [`BaseCGIHandler`](#wsgiref.handlers.BaseCGIHandler "wsgiref.handlers.BaseCGIHandler"). This class is a subclass of [`BaseHandler`](#wsgiref.handlers.BaseHandler "wsgiref.handlers.BaseHandler"). It overrides the [`__init__()`](../reference/datamodel#object.__init__ "object.__init__"), `get_stdin()`, `get_stderr()`, `add_cgi_vars()`, `_write()`, and `_flush()` methods to support explicitly setting the environment and streams via the constructor. The supplied environment and streams are stored in the `stdin`, `stdout`, `stderr`, and `environ` attributes. The [`write()`](io#io.BufferedIOBase.write "io.BufferedIOBase.write") method of *stdout* should write each chunk in full, like [`io.BufferedIOBase`](io#io.BufferedIOBase "io.BufferedIOBase"). `class wsgiref.handlers.BaseHandler` This is an abstract base class for running WSGI applications. Each instance will handle a single HTTP request, although in principle you could create a subclass that was reusable for multiple requests. [`BaseHandler`](#wsgiref.handlers.BaseHandler "wsgiref.handlers.BaseHandler") instances have only one method intended for external use: `run(app)` Run the specified WSGI application, *app*. All of the other [`BaseHandler`](#wsgiref.handlers.BaseHandler "wsgiref.handlers.BaseHandler") methods are invoked by this method in the process of running the application, and thus exist primarily to allow customizing the process. The following methods MUST be overridden in a subclass: `_write(data)` Buffer the bytes *data* for transmission to the client. It’s okay if this method actually transmits the data; [`BaseHandler`](#wsgiref.handlers.BaseHandler "wsgiref.handlers.BaseHandler") just separates write and flush operations for greater efficiency when the underlying system actually has such a distinction. `_flush()` Force buffered data to be transmitted to the client. It’s okay if this method is a no-op (i.e., if [`_write()`](#wsgiref.handlers.BaseHandler._write "wsgiref.handlers.BaseHandler._write") actually sends the data). `get_stdin()` Return an input stream object suitable for use as the `wsgi.input` of the request currently being processed. `get_stderr()` Return an output stream object suitable for use as the `wsgi.errors` of the request currently being processed. `add_cgi_vars()` Insert CGI variables for the current request into the `environ` attribute. Here are some other methods and attributes you may wish to override. This list is only a summary, however, and does not include every method that can be overridden. You should consult the docstrings and source code for additional information before attempting to create a customized [`BaseHandler`](#wsgiref.handlers.BaseHandler "wsgiref.handlers.BaseHandler") subclass. Attributes and methods for customizing the WSGI environment: `wsgi_multithread` The value to be used for the `wsgi.multithread` environment variable. It defaults to true in [`BaseHandler`](#wsgiref.handlers.BaseHandler "wsgiref.handlers.BaseHandler"), but may have a different default (or be set by the constructor) in the other subclasses. `wsgi_multiprocess` The value to be used for the `wsgi.multiprocess` environment variable. It defaults to true in [`BaseHandler`](#wsgiref.handlers.BaseHandler "wsgiref.handlers.BaseHandler"), but may have a different default (or be set by the constructor) in the other subclasses. `wsgi_run_once` The value to be used for the `wsgi.run_once` environment variable. It defaults to false in [`BaseHandler`](#wsgiref.handlers.BaseHandler "wsgiref.handlers.BaseHandler"), but [`CGIHandler`](#wsgiref.handlers.CGIHandler "wsgiref.handlers.CGIHandler") sets it to true by default. `os_environ` The default environment variables to be included in every request’s WSGI environment. By default, this is a copy of `os.environ` at the time that [`wsgiref.handlers`](#module-wsgiref.handlers "wsgiref.handlers: WSGI server/gateway base classes.") was imported, but subclasses can either create their own at the class or instance level. Note that the dictionary should be considered read-only, since the default value is shared between multiple classes and instances. `server_software` If the [`origin_server`](#wsgiref.handlers.BaseHandler.origin_server "wsgiref.handlers.BaseHandler.origin_server") attribute is set, this attribute’s value is used to set the default `SERVER_SOFTWARE` WSGI environment variable, and also to set a default `Server:` header in HTTP responses. It is ignored for handlers (such as [`BaseCGIHandler`](#wsgiref.handlers.BaseCGIHandler "wsgiref.handlers.BaseCGIHandler") and [`CGIHandler`](#wsgiref.handlers.CGIHandler "wsgiref.handlers.CGIHandler")) that are not HTTP origin servers. Changed in version 3.3: The term “Python” is replaced with implementation specific term like “CPython”, “Jython” etc. `get_scheme()` Return the URL scheme being used for the current request. The default implementation uses the `guess_scheme()` function from [`wsgiref.util`](#module-wsgiref.util "wsgiref.util: WSGI environment utilities.") to guess whether the scheme should be “http” or “https”, based on the current request’s `environ` variables. `setup_environ()` Set the `environ` attribute to a fully-populated WSGI environment. The default implementation uses all of the above methods and attributes, plus the [`get_stdin()`](#wsgiref.handlers.BaseHandler.get_stdin "wsgiref.handlers.BaseHandler.get_stdin"), [`get_stderr()`](#wsgiref.handlers.BaseHandler.get_stderr "wsgiref.handlers.BaseHandler.get_stderr"), and [`add_cgi_vars()`](#wsgiref.handlers.BaseHandler.add_cgi_vars "wsgiref.handlers.BaseHandler.add_cgi_vars") methods and the [`wsgi_file_wrapper`](#wsgiref.handlers.BaseHandler.wsgi_file_wrapper "wsgiref.handlers.BaseHandler.wsgi_file_wrapper") attribute. It also inserts a `SERVER_SOFTWARE` key if not present, as long as the [`origin_server`](#wsgiref.handlers.BaseHandler.origin_server "wsgiref.handlers.BaseHandler.origin_server") attribute is a true value and the [`server_software`](#wsgiref.handlers.BaseHandler.server_software "wsgiref.handlers.BaseHandler.server_software") attribute is set. Methods and attributes for customizing exception handling: `log_exception(exc_info)` Log the *exc\_info* tuple in the server log. *exc\_info* is a `(type, value, traceback)` tuple. The default implementation simply writes the traceback to the request’s `wsgi.errors` stream and flushes it. Subclasses can override this method to change the format or retarget the output, mail the traceback to an administrator, or whatever other action may be deemed suitable. `traceback_limit` The maximum number of frames to include in tracebacks output by the default [`log_exception()`](#wsgiref.handlers.BaseHandler.log_exception "wsgiref.handlers.BaseHandler.log_exception") method. If `None`, all frames are included. `error_output(environ, start_response)` This method is a WSGI application to generate an error page for the user. It is only invoked if an error occurs before headers are sent to the client. This method can access the current error information using `sys.exc_info()`, and should pass that information to *start\_response* when calling it (as described in the “Error Handling” section of [**PEP 3333**](https://www.python.org/dev/peps/pep-3333)). The default implementation just uses the [`error_status`](#wsgiref.handlers.BaseHandler.error_status "wsgiref.handlers.BaseHandler.error_status"), [`error_headers`](#wsgiref.handlers.BaseHandler.error_headers "wsgiref.handlers.BaseHandler.error_headers"), and [`error_body`](#wsgiref.handlers.BaseHandler.error_body "wsgiref.handlers.BaseHandler.error_body") attributes to generate an output page. Subclasses can override this to produce more dynamic error output. Note, however, that it’s not recommended from a security perspective to spit out diagnostics to any old user; ideally, you should have to do something special to enable diagnostic output, which is why the default implementation doesn’t include any. `error_status` The HTTP status used for error responses. This should be a status string as defined in [**PEP 3333**](https://www.python.org/dev/peps/pep-3333); it defaults to a 500 code and message. `error_headers` The HTTP headers used for error responses. This should be a list of WSGI response headers (`(name, value)` tuples), as described in [**PEP 3333**](https://www.python.org/dev/peps/pep-3333). The default list just sets the content type to `text/plain`. `error_body` The error response body. This should be an HTTP response body bytestring. It defaults to the plain text, “A server error occurred. Please contact the administrator.” Methods and attributes for [**PEP 3333**](https://www.python.org/dev/peps/pep-3333)’s “Optional Platform-Specific File Handling” feature: `wsgi_file_wrapper` A `wsgi.file_wrapper` factory, or `None`. The default value of this attribute is the [`wsgiref.util.FileWrapper`](#wsgiref.util.FileWrapper "wsgiref.util.FileWrapper") class. `sendfile()` Override to implement platform-specific file transmission. This method is called only if the application’s return value is an instance of the class specified by the [`wsgi_file_wrapper`](#wsgiref.handlers.BaseHandler.wsgi_file_wrapper "wsgiref.handlers.BaseHandler.wsgi_file_wrapper") attribute. It should return a true value if it was able to successfully transmit the file, so that the default transmission code will not be executed. The default implementation of this method just returns a false value. Miscellaneous methods and attributes: `origin_server` This attribute should be set to a true value if the handler’s [`_write()`](#wsgiref.handlers.BaseHandler._write "wsgiref.handlers.BaseHandler._write") and [`_flush()`](#wsgiref.handlers.BaseHandler._flush "wsgiref.handlers.BaseHandler._flush") are being used to communicate directly to the client, rather than via a CGI-like gateway protocol that wants the HTTP status in a special `Status:` header. This attribute’s default value is true in [`BaseHandler`](#wsgiref.handlers.BaseHandler "wsgiref.handlers.BaseHandler"), but false in [`BaseCGIHandler`](#wsgiref.handlers.BaseCGIHandler "wsgiref.handlers.BaseCGIHandler") and [`CGIHandler`](#wsgiref.handlers.CGIHandler "wsgiref.handlers.CGIHandler"). `http_version` If [`origin_server`](#wsgiref.handlers.BaseHandler.origin_server "wsgiref.handlers.BaseHandler.origin_server") is true, this string attribute is used to set the HTTP version of the response set to the client. It defaults to `"1.0"`. `wsgiref.handlers.read_environ()` Transcode CGI variables from `os.environ` to [**PEP 3333**](https://www.python.org/dev/peps/pep-3333) “bytes in unicode” strings, returning a new dictionary. This function is used by [`CGIHandler`](#wsgiref.handlers.CGIHandler "wsgiref.handlers.CGIHandler") and [`IISCGIHandler`](#wsgiref.handlers.IISCGIHandler "wsgiref.handlers.IISCGIHandler") in place of directly using `os.environ`, which is not necessarily WSGI-compliant on all platforms and web servers using Python 3 – specifically, ones where the OS’s actual environment is Unicode (i.e. Windows), or ones where the environment is bytes, but the system encoding used by Python to decode it is anything other than ISO-8859-1 (e.g. Unix systems using UTF-8). If you are implementing a CGI-based handler of your own, you probably want to use this routine instead of just copying values out of `os.environ` directly. New in version 3.2. Examples -------- This is a working “Hello World” WSGI application: ``` from wsgiref.simple_server import make_server # Every WSGI application must have an application object - a callable # object that accepts two arguments. For that purpose, we're going to # use a function (note that you're not limited to a function, you can # use a class for example). The first argument passed to the function # is a dictionary containing CGI-style environment variables and the # second variable is the callable object. def hello_world_app(environ, start_response): status = '200 OK' # HTTP Status headers = [('Content-type', 'text/plain; charset=utf-8')] # HTTP Headers start_response(status, headers) # The returned object is going to be printed return [b"Hello World"] with make_server('', 8000, hello_world_app) as httpd: print("Serving on port 8000...") # Serve until process is killed httpd.serve_forever() ``` Example of a WSGI application serving the current directory, accept optional directory and port number (default: 8000) on the command line: ``` #!/usr/bin/env python3 ''' Small wsgiref based web server. Takes a path to serve from and an optional port number (defaults to 8000), then tries to serve files. Mime types are guessed from the file names, 404 errors are raised if the file is not found. Used for the make serve target in Doc. ''' import sys import os import mimetypes from wsgiref import simple_server, util def app(environ, respond): fn = os.path.join(path, environ['PATH_INFO'][1:]) if '.' not in fn.split(os.path.sep)[-1]: fn = os.path.join(fn, 'index.html') type = mimetypes.guess_type(fn)[0] if os.path.exists(fn): respond('200 OK', [('Content-Type', type)]) return util.FileWrapper(open(fn, "rb")) else: respond('404 Not Found', [('Content-Type', 'text/plain')]) return [b'not found'] if __name__ == '__main__': path = sys.argv[1] if len(sys.argv) > 1 else os.getcwd() port = int(sys.argv[2]) if len(sys.argv) > 2 else 8000 httpd = simple_server.make_server('', port, app) print("Serving {} on port {}, control-C to stop".format(path, port)) try: httpd.serve_forever() except KeyboardInterrupt: print("Shutting down.") httpd.server_close() ```
programming_docs
python Custom Python Interpreters Custom Python Interpreters ========================== The modules described in this chapter allow writing interfaces similar to Python’s interactive interpreter. If you want a Python interpreter that supports some special feature in addition to the Python language, you should look at the [`code`](code#module-code "code: Facilities to implement read-eval-print loops.") module. (The [`codeop`](codeop#module-codeop "codeop: Compile (possibly incomplete) Python code.") module is lower-level, used to support compiling a possibly-incomplete chunk of Python code.) The full list of modules described in this chapter is: * [`code` — Interpreter base classes](code) + [Interactive Interpreter Objects](code#interactive-interpreter-objects) + [Interactive Console Objects](code#interactive-console-objects) * [`codeop` — Compile Python code](codeop) python configparser — Configuration file parser configparser — Configuration file parser ======================================== **Source code:** [Lib/configparser.py](https://github.com/python/cpython/tree/3.9/Lib/configparser.py) This module provides the [`ConfigParser`](#configparser.ConfigParser "configparser.ConfigParser") class which implements a basic configuration language which provides a structure similar to what’s found in Microsoft Windows INI files. You can use this to write Python programs which can be customized by end users easily. Note This library does *not* interpret or write the value-type prefixes used in the Windows Registry extended version of INI syntax. See also `Module` [`shlex`](shlex#module-shlex "shlex: Simple lexical analysis for Unix shell-like languages.") Support for creating Unix shell-like mini-languages which can be used as an alternate format for application configuration files. `Module` [`json`](json#module-json "json: Encode and decode the JSON format.") The json module implements a subset of JavaScript syntax which can also be used for this purpose. Quick Start ----------- Let’s take a very basic configuration file that looks like this: ``` [DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no ``` The structure of INI files is described [in the following section](#supported-ini-file-structure). Essentially, the file consists of sections, each of which contains keys with values. [`configparser`](#module-configparser "configparser: Configuration file parser.") classes can read and write such files. Let’s start by creating the above configuration file programmatically. ``` >>> import configparser >>> config = configparser.ConfigParser() >>> config['DEFAULT'] = {'ServerAliveInterval': '45', ... 'Compression': 'yes', ... 'CompressionLevel': '9'} >>> config['bitbucket.org'] = {} >>> config['bitbucket.org']['User'] = 'hg' >>> config['topsecret.server.com'] = {} >>> topsecret = config['topsecret.server.com'] >>> topsecret['Port'] = '50022' # mutates the parser >>> topsecret['ForwardX11'] = 'no' # same here >>> config['DEFAULT']['ForwardX11'] = 'yes' >>> with open('example.ini', 'w') as configfile: ... config.write(configfile) ... ``` As you can see, we can treat a config parser much like a dictionary. There are differences, [outlined later](#mapping-protocol-access), but the behavior is very close to what you would expect from a dictionary. Now that we have created and saved a configuration file, let’s read it back and explore the data it holds. ``` >>> config = configparser.ConfigParser() >>> config.sections() [] >>> config.read('example.ini') ['example.ini'] >>> config.sections() ['bitbucket.org', 'topsecret.server.com'] >>> 'bitbucket.org' in config True >>> 'bytebong.com' in config False >>> config['bitbucket.org']['User'] 'hg' >>> config['DEFAULT']['Compression'] 'yes' >>> topsecret = config['topsecret.server.com'] >>> topsecret['ForwardX11'] 'no' >>> topsecret['Port'] '50022' >>> for key in config['bitbucket.org']: ... print(key) user compressionlevel serveraliveinterval compression forwardx11 >>> config['bitbucket.org']['ForwardX11'] 'yes' ``` As we can see above, the API is pretty straightforward. The only bit of magic involves the `DEFAULT` section which provides default values for all other sections [1](#id15). Note also that keys in sections are case-insensitive and stored in lowercase [1](#id15). Supported Datatypes ------------------- Config parsers do not guess datatypes of values in configuration files, always storing them internally as strings. This means that if you need other datatypes, you should convert on your own: ``` >>> int(topsecret['Port']) 50022 >>> float(topsecret['CompressionLevel']) 9.0 ``` Since this task is so common, config parsers provide a range of handy getter methods to handle integers, floats and booleans. The last one is the most interesting because simply passing the value to `bool()` would do no good since `bool('False')` is still `True`. This is why config parsers also provide [`getboolean()`](#configparser.ConfigParser.getboolean "configparser.ConfigParser.getboolean"). This method is case-insensitive and recognizes Boolean values from `'yes'`/`'no'`, `'on'`/`'off'`, `'true'`/`'false'` and `'1'`/`'0'` [1](#id15). For example: ``` >>> topsecret.getboolean('ForwardX11') False >>> config['bitbucket.org'].getboolean('ForwardX11') True >>> config.getboolean('bitbucket.org', 'Compression') True ``` Apart from [`getboolean()`](#configparser.ConfigParser.getboolean "configparser.ConfigParser.getboolean"), config parsers also provide equivalent [`getint()`](#configparser.ConfigParser.getint "configparser.ConfigParser.getint") and [`getfloat()`](#configparser.ConfigParser.getfloat "configparser.ConfigParser.getfloat") methods. You can register your own converters and customize the provided ones. [1](#id15) Fallback Values --------------- As with a dictionary, you can use a section’s `get()` method to provide fallback values: ``` >>> topsecret.get('Port') '50022' >>> topsecret.get('CompressionLevel') '9' >>> topsecret.get('Cipher') >>> topsecret.get('Cipher', '3des-cbc') '3des-cbc' ``` Please note that default values have precedence over fallback values. For instance, in our example the `'CompressionLevel'` key was specified only in the `'DEFAULT'` section. If we try to get it from the section `'topsecret.server.com'`, we will always get the default, even if we specify a fallback: ``` >>> topsecret.get('CompressionLevel', '3') '9' ``` One more thing to be aware of is that the parser-level `get()` method provides a custom, more complex interface, maintained for backwards compatibility. When using this method, a fallback value can be provided via the `fallback` keyword-only argument: ``` >>> config.get('bitbucket.org', 'monster', ... fallback='No such things as monsters') 'No such things as monsters' ``` The same `fallback` argument can be used with the [`getint()`](#configparser.ConfigParser.getint "configparser.ConfigParser.getint"), [`getfloat()`](#configparser.ConfigParser.getfloat "configparser.ConfigParser.getfloat") and [`getboolean()`](#configparser.ConfigParser.getboolean "configparser.ConfigParser.getboolean") methods, for example: ``` >>> 'BatchMode' in topsecret False >>> topsecret.getboolean('BatchMode', fallback=True) True >>> config['DEFAULT']['BatchMode'] = 'no' >>> topsecret.getboolean('BatchMode', fallback=True) False ``` Supported INI File Structure ---------------------------- A configuration file consists of sections, each led by a `[section]` header, followed by key/value entries separated by a specific string (`=` or `:` by default [1](#id15)). By default, section names are case sensitive but keys are not [1](#id15). Leading and trailing whitespace is removed from keys and values. Values can be omitted if the parser is configured to allow it [1](#id15), in which case the key/value delimiter may also be left out. Values can also span multiple lines, as long as they are indented deeper than the first line of the value. Depending on the parser’s mode, blank lines may be treated as parts of multiline values or ignored. By default, a valid section name can be any string that does not contain ‘\n’ or ‘]’. To change this, see [`ConfigParser.SECTCRE`](#configparser.ConfigParser.SECTCRE "configparser.ConfigParser.SECTCRE"). Configuration files may include comments, prefixed by specific characters (`#` and `;` by default [1](#id15)). Comments may appear on their own on an otherwise empty line, possibly indented. [1](#id15) For example: ``` [Simple Values] key=value spaces in keys=allowed spaces in values=allowed as well spaces around the delimiter = obviously you can also use : to delimit keys from values [All Values Are Strings] values like this: 1000000 or this: 3.14159265359 are they treated as numbers? : no integers, floats and booleans are held as: strings can use the API to get converted values directly: true [Multiline Values] chorus: I'm a lumberjack, and I'm okay I sleep all night and I work all day [No Values] key_without_value empty string value here = [You can use comments] # like this ; or this # By default only in an empty line. # Inline comments can be harmful because they prevent users # from using the delimiting characters as parts of values. # That being said, this can be customized. [Sections Can Be Indented] can_values_be_as_well = True does_that_mean_anything_special = False purpose = formatting for readability multiline_values = are handled just fine as long as they are indented deeper than the first line of a value # Did I mention we can indent comments, too? ``` Interpolation of values ----------------------- On top of the core functionality, [`ConfigParser`](#configparser.ConfigParser "configparser.ConfigParser") supports interpolation. This means values can be preprocessed before returning them from `get()` calls. `class configparser.BasicInterpolation` The default implementation used by [`ConfigParser`](#configparser.ConfigParser "configparser.ConfigParser"). It enables values to contain format strings which refer to other values in the same section, or values in the special default section [1](#id15). Additional default values can be provided on initialization. For example: ``` [Paths] home_dir: /Users my_dir: %(home_dir)s/lumberjack my_pictures: %(my_dir)s/Pictures [Escape] # use a %% to escape the % sign (% is the only character that needs to be escaped): gain: 80%% ``` In the example above, [`ConfigParser`](#configparser.ConfigParser "configparser.ConfigParser") with *interpolation* set to `BasicInterpolation()` would resolve `%(home_dir)s` to the value of `home_dir` (`/Users` in this case). `%(my_dir)s` in effect would resolve to `/Users/lumberjack`. All interpolations are done on demand so keys used in the chain of references do not have to be specified in any specific order in the configuration file. With `interpolation` set to `None`, the parser would simply return `%(my_dir)s/Pictures` as the value of `my_pictures` and `%(home_dir)s/lumberjack` as the value of `my_dir`. `class configparser.ExtendedInterpolation` An alternative handler for interpolation which implements a more advanced syntax, used for instance in `zc.buildout`. Extended interpolation is using `${section:option}` to denote a value from a foreign section. Interpolation can span multiple levels. For convenience, if the `section:` part is omitted, interpolation defaults to the current section (and possibly the default values from the special section). For example, the configuration specified above with basic interpolation, would look like this with extended interpolation: ``` [Paths] home_dir: /Users my_dir: ${home_dir}/lumberjack my_pictures: ${my_dir}/Pictures [Escape] # use a $$ to escape the $ sign ($ is the only character that needs to be escaped): cost: $$80 ``` Values from other sections can be fetched as well: ``` [Common] home_dir: /Users library_dir: /Library system_dir: /System macports_dir: /opt/local [Frameworks] Python: 3.2 path: ${Common:system_dir}/Library/Frameworks/ [Arthur] nickname: Two Sheds last_name: Jackson my_dir: ${Common:home_dir}/twosheds my_pictures: ${my_dir}/Pictures python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python} ``` Mapping Protocol Access ----------------------- New in version 3.2. Mapping protocol access is a generic name for functionality that enables using custom objects as if they were dictionaries. In case of [`configparser`](#module-configparser "configparser: Configuration file parser."), the mapping interface implementation is using the `parser['section']['option']` notation. `parser['section']` in particular returns a proxy for the section’s data in the parser. This means that the values are not copied but they are taken from the original parser on demand. What’s even more important is that when values are changed on a section proxy, they are actually mutated in the original parser. [`configparser`](#module-configparser "configparser: Configuration file parser.") objects behave as close to actual dictionaries as possible. The mapping interface is complete and adheres to the [`MutableMapping`](collections.abc#collections.abc.MutableMapping "collections.abc.MutableMapping") ABC. However, there are a few differences that should be taken into account: * By default, all keys in sections are accessible in a case-insensitive manner [1](#id15). E.g. `for option in parser["section"]` yields only `optionxform`’ed option key names. This means lowercased keys by default. At the same time, for a section that holds the key `'a'`, both expressions return `True`: ``` "a" in parser["section"] "A" in parser["section"] ``` * All sections include `DEFAULTSECT` values as well which means that `.clear()` on a section may not leave the section visibly empty. This is because default values cannot be deleted from the section (because technically they are not there). If they are overridden in the section, deleting causes the default value to be visible again. Trying to delete a default value causes a [`KeyError`](exceptions#KeyError "KeyError"). * `DEFAULTSECT` cannot be removed from the parser: + trying to delete it raises [`ValueError`](exceptions#ValueError "ValueError"), + `parser.clear()` leaves it intact, + `parser.popitem()` never returns it. * `parser.get(section, option, **kwargs)` - the second argument is **not** a fallback value. Note however that the section-level `get()` methods are compatible both with the mapping protocol and the classic configparser API. * `parser.items()` is compatible with the mapping protocol (returns a list of *section\_name*, *section\_proxy* pairs including the DEFAULTSECT). However, this method can also be invoked with arguments: `parser.items(section, raw, vars)`. The latter call returns a list of *option*, *value* pairs for a specified `section`, with all interpolations expanded (unless `raw=True` is provided). The mapping protocol is implemented on top of the existing legacy API so that subclasses overriding the original interface still should have mappings working as expected. Customizing Parser Behaviour ---------------------------- There are nearly as many INI format variants as there are applications using it. [`configparser`](#module-configparser "configparser: Configuration file parser.") goes a long way to provide support for the largest sensible set of INI styles available. The default functionality is mainly dictated by historical background and it’s very likely that you will want to customize some of the features. The most common way to change the way a specific config parser works is to use the [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") options: * *defaults*, default value: `None` This option accepts a dictionary of key-value pairs which will be initially put in the `DEFAULT` section. This makes for an elegant way to support concise configuration files that don’t specify values which are the same as the documented default. Hint: if you want to specify default values for a specific section, use `read_dict()` before you read the actual file. * *dict\_type*, default value: [`dict`](stdtypes#dict "dict") This option has a major impact on how the mapping protocol will behave and how the written configuration files look. With the standard dictionary, every section is stored in the order they were added to the parser. Same goes for options within sections. An alternative dictionary type can be used for example to sort sections and options on write-back. Please note: there are ways to add a set of key-value pairs in a single operation. When you use a regular dictionary in those operations, the order of the keys will be ordered. For example: ``` >>> parser = configparser.ConfigParser() >>> parser.read_dict({'section1': {'key1': 'value1', ... 'key2': 'value2', ... 'key3': 'value3'}, ... 'section2': {'keyA': 'valueA', ... 'keyB': 'valueB', ... 'keyC': 'valueC'}, ... 'section3': {'foo': 'x', ... 'bar': 'y', ... 'baz': 'z'} ... }) >>> parser.sections() ['section1', 'section2', 'section3'] >>> [option for option in parser['section3']] ['foo', 'bar', 'baz'] ``` * *allow\_no\_value*, default value: `False` Some configuration files are known to include settings without values, but which otherwise conform to the syntax supported by [`configparser`](#module-configparser "configparser: Configuration file parser."). The *allow\_no\_value* parameter to the constructor can be used to indicate that such values should be accepted: ``` >>> import configparser >>> sample_config = """ ... [mysqld] ... user = mysql ... pid-file = /var/run/mysqld/mysqld.pid ... skip-external-locking ... old_passwords = 1 ... skip-bdb ... # we don't need ACID today ... skip-innodb ... """ >>> config = configparser.ConfigParser(allow_no_value=True) >>> config.read_string(sample_config) >>> # Settings with values are treated as before: >>> config["mysqld"]["user"] 'mysql' >>> # Settings without values provide None: >>> config["mysqld"]["skip-bdb"] >>> # Settings which aren't specified still raise an error: >>> config["mysqld"]["does-not-exist"] Traceback (most recent call last): ... KeyError: 'does-not-exist' ``` * *delimiters*, default value: `('=', ':')` Delimiters are substrings that delimit keys from values within a section. The first occurrence of a delimiting substring on a line is considered a delimiter. This means values (but not keys) can contain the delimiters. See also the *space\_around\_delimiters* argument to [`ConfigParser.write()`](#configparser.ConfigParser.write "configparser.ConfigParser.write"). * *comment\_prefixes*, default value: `('#', ';')` * *inline\_comment\_prefixes*, default value: `None` Comment prefixes are strings that indicate the start of a valid comment within a config file. *comment\_prefixes* are used only on otherwise empty lines (optionally indented) whereas *inline\_comment\_prefixes* can be used after every valid value (e.g. section names, options and empty lines as well). By default inline comments are disabled and `'#'` and `';'` are used as prefixes for whole line comments. Changed in version 3.2: In previous versions of [`configparser`](#module-configparser "configparser: Configuration file parser.") behaviour matched `comment_prefixes=('#',';')` and `inline_comment_prefixes=(';',)`. Please note that config parsers don’t support escaping of comment prefixes so using *inline\_comment\_prefixes* may prevent users from specifying option values with characters used as comment prefixes. When in doubt, avoid setting *inline\_comment\_prefixes*. In any circumstances, the only way of storing comment prefix characters at the beginning of a line in multiline values is to interpolate the prefix, for example: ``` >>> from configparser import ConfigParser, ExtendedInterpolation >>> parser = ConfigParser(interpolation=ExtendedInterpolation()) >>> # the default BasicInterpolation could be used as well >>> parser.read_string(""" ... [DEFAULT] ... hash = # ... ... [hashes] ... shebang = ... ${hash}!/usr/bin/env python ... ${hash} -*- coding: utf-8 -*- ... ... extensions = ... enabled_extension ... another_extension ... #disabled_by_comment ... yet_another_extension ... ... interpolation not necessary = if # is not at line start ... even in multiline values = line #1 ... line #2 ... line #3 ... """) >>> print(parser['hashes']['shebang']) #!/usr/bin/env python # -*- coding: utf-8 -*- >>> print(parser['hashes']['extensions']) enabled_extension another_extension yet_another_extension >>> print(parser['hashes']['interpolation not necessary']) if # is not at line start >>> print(parser['hashes']['even in multiline values']) line #1 line #2 line #3 ``` * *strict*, default value: `True` When set to `True`, the parser will not allow for any section or option duplicates while reading from a single source (using `read_file()`, `read_string()` or `read_dict()`). It is recommended to use strict parsers in new applications. Changed in version 3.2: In previous versions of [`configparser`](#module-configparser "configparser: Configuration file parser.") behaviour matched `strict=False`. * *empty\_lines\_in\_values*, default value: `True` In config parsers, values can span multiple lines as long as they are indented more than the key that holds them. By default parsers also let empty lines to be parts of values. At the same time, keys can be arbitrarily indented themselves to improve readability. In consequence, when configuration files get big and complex, it is easy for the user to lose track of the file structure. Take for instance: ``` [Section] key = multiline value with a gotcha this = is still a part of the multiline value of 'key' ``` This can be especially problematic for the user to see if she’s using a proportional font to edit the file. That is why when your application does not need values with empty lines, you should consider disallowing them. This will make empty lines split keys every time. In the example above, it would produce two keys, `key` and `this`. * *default\_section*, default value: `configparser.DEFAULTSECT` (that is: `"DEFAULT"`) The convention of allowing a special section of default values for other sections or interpolation purposes is a powerful concept of this library, letting users create complex declarative configurations. This section is normally called `"DEFAULT"` but this can be customized to point to any other valid section name. Some typical values include: `"general"` or `"common"`. The name provided is used for recognizing default sections when reading from any source and is used when writing configuration back to a file. Its current value can be retrieved using the `parser_instance.default_section` attribute and may be modified at runtime (i.e. to convert files from one format to another). * *interpolation*, default value: `configparser.BasicInterpolation` Interpolation behaviour may be customized by providing a custom handler through the *interpolation* argument. `None` can be used to turn off interpolation completely, `ExtendedInterpolation()` provides a more advanced variant inspired by `zc.buildout`. More on the subject in the [dedicated documentation section](#interpolation-of-values). [`RawConfigParser`](#configparser.RawConfigParser "configparser.RawConfigParser") has a default value of `None`. * *converters*, default value: not set Config parsers provide option value getters that perform type conversion. By default [`getint()`](#configparser.ConfigParser.getint "configparser.ConfigParser.getint"), [`getfloat()`](#configparser.ConfigParser.getfloat "configparser.ConfigParser.getfloat"), and [`getboolean()`](#configparser.ConfigParser.getboolean "configparser.ConfigParser.getboolean") are implemented. Should other getters be desirable, users may define them in a subclass or pass a dictionary where each key is a name of the converter and each value is a callable implementing said conversion. For instance, passing `{'decimal': decimal.Decimal}` would add `getdecimal()` on both the parser object and all section proxies. In other words, it will be possible to write both `parser_instance.getdecimal('section', 'key', fallback=0)` and `parser_instance['section'].getdecimal('key', 0)`. If the converter needs to access the state of the parser, it can be implemented as a method on a config parser subclass. If the name of this method starts with `get`, it will be available on all section proxies, in the dict-compatible form (see the `getdecimal()` example above). More advanced customization may be achieved by overriding default values of these parser attributes. The defaults are defined on the classes, so they may be overridden by subclasses or by attribute assignment. `ConfigParser.BOOLEAN_STATES` By default when using [`getboolean()`](#configparser.ConfigParser.getboolean "configparser.ConfigParser.getboolean"), config parsers consider the following values `True`: `'1'`, `'yes'`, `'true'`, `'on'` and the following values `False`: `'0'`, `'no'`, `'false'`, `'off'`. You can override this by specifying a custom dictionary of strings and their Boolean outcomes. For example: ``` >>> custom = configparser.ConfigParser() >>> custom['section1'] = {'funky': 'nope'} >>> custom['section1'].getboolean('funky') Traceback (most recent call last): ... ValueError: Not a boolean: nope >>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False} >>> custom['section1'].getboolean('funky') False ``` Other typical Boolean pairs include `accept`/`reject` or `enabled`/`disabled`. `ConfigParser.optionxform(option)` This method transforms option names on every read, get, or set operation. The default converts the name to lowercase. This also means that when a configuration file gets written, all keys will be lowercase. Override this method if that’s unsuitable. For example: ``` >>> config = """ ... [Section1] ... Key = Value ... ... [Section2] ... AnotherKey = Value ... """ >>> typical = configparser.ConfigParser() >>> typical.read_string(config) >>> list(typical['Section1'].keys()) ['key'] >>> list(typical['Section2'].keys()) ['anotherkey'] >>> custom = configparser.RawConfigParser() >>> custom.optionxform = lambda option: option >>> custom.read_string(config) >>> list(custom['Section1'].keys()) ['Key'] >>> list(custom['Section2'].keys()) ['AnotherKey'] ``` Note The optionxform function transforms option names to a canonical form. This should be an idempotent function: if the name is already in canonical form, it should be returned unchanged. `ConfigParser.SECTCRE` A compiled regular expression used to parse section headers. The default matches `[section]` to the name `"section"`. Whitespace is considered part of the section name, thus `[  larch  ]` will be read as a section of name `"  larch  "`. Override this attribute if that’s unsuitable. For example: ``` >>> import re >>> config = """ ... [Section 1] ... option = value ... ... [ Section 2 ] ... another = val ... """ >>> typical = configparser.ConfigParser() >>> typical.read_string(config) >>> typical.sections() ['Section 1', ' Section 2 '] >>> custom = configparser.ConfigParser() >>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]") >>> custom.read_string(config) >>> custom.sections() ['Section 1', 'Section 2'] ``` Note While ConfigParser objects also use an `OPTCRE` attribute for recognizing option lines, it’s not recommended to override it because that would interfere with constructor options *allow\_no\_value* and *delimiters*. Legacy API Examples ------------------- Mainly because of backwards compatibility concerns, [`configparser`](#module-configparser "configparser: Configuration file parser.") provides also a legacy API with explicit `get`/`set` methods. While there are valid use cases for the methods outlined below, mapping protocol access is preferred for new projects. The legacy API is at times more advanced, low-level and downright counterintuitive. An example of writing to a configuration file: ``` import configparser config = configparser.RawConfigParser() # Please note that using RawConfigParser's set functions, you can assign # non-string values to keys internally, but will receive an error when # attempting to write to a file or when you get it in non-raw mode. Setting # values using the mapping protocol or ConfigParser's set() does not allow # such assignments to take place. config.add_section('Section1') config.set('Section1', 'an_int', '15') config.set('Section1', 'a_bool', 'true') config.set('Section1', 'a_float', '3.1415') config.set('Section1', 'baz', 'fun') config.set('Section1', 'bar', 'Python') config.set('Section1', 'foo', '%(bar)s is %(baz)s!') # Writing our configuration file to 'example.cfg' with open('example.cfg', 'w') as configfile: config.write(configfile) ``` An example of reading the configuration file again: ``` import configparser config = configparser.RawConfigParser() config.read('example.cfg') # getfloat() raises an exception if the value is not a float # getint() and getboolean() also do this for their respective types a_float = config.getfloat('Section1', 'a_float') an_int = config.getint('Section1', 'an_int') print(a_float + an_int) # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'. # This is because we are using a RawConfigParser(). if config.getboolean('Section1', 'a_bool'): print(config.get('Section1', 'foo')) ``` To get interpolation, use [`ConfigParser`](#configparser.ConfigParser "configparser.ConfigParser"): ``` import configparser cfg = configparser.ConfigParser() cfg.read('example.cfg') # Set the optional *raw* argument of get() to True if you wish to disable # interpolation in a single get operation. print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!" print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!" # The optional *vars* argument is a dict with members that will take # precedence in interpolation. print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation', 'baz': 'evil'})) # The optional *fallback* argument can be used to provide a fallback value print(cfg.get('Section1', 'foo')) # -> "Python is fun!" print(cfg.get('Section1', 'foo', fallback='Monty is not.')) # -> "Python is fun!" print(cfg.get('Section1', 'monster', fallback='No such things as monsters.')) # -> "No such things as monsters." # A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError # but we can also use: print(cfg.get('Section1', 'monster', fallback=None)) # -> None ``` Default values are available in both types of ConfigParsers. They are used in interpolation if an option used is not defined elsewhere. ``` import configparser # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'}) config.read('example.cfg') print(config.get('Section1', 'foo')) # -> "Python is fun!" config.remove_option('Section1', 'bar') config.remove_option('Section1', 'baz') print(config.get('Section1', 'foo')) # -> "Life is hard!" ``` ConfigParser Objects -------------------- `class configparser.ConfigParser(defaults=None, dict_type=dict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation(), converters={})` The main configuration parser. When *defaults* is given, it is initialized into the dictionary of intrinsic defaults. When *dict\_type* is given, it will be used to create the dictionary objects for the list of sections, for the options within a section, and for the default values. When *delimiters* is given, it is used as the set of substrings that divide keys from values. When *comment\_prefixes* is given, it will be used as the set of substrings that prefix comments in otherwise empty lines. Comments can be indented. When *inline\_comment\_prefixes* is given, it will be used as the set of substrings that prefix comments in non-empty lines. When *strict* is `True` (the default), the parser won’t allow for any section or option duplicates while reading from a single source (file, string or dictionary), raising [`DuplicateSectionError`](#configparser.DuplicateSectionError "configparser.DuplicateSectionError") or [`DuplicateOptionError`](#configparser.DuplicateOptionError "configparser.DuplicateOptionError"). When *empty\_lines\_in\_values* is `False` (default: `True`), each empty line marks the end of an option. Otherwise, internal empty lines of a multiline option are kept as part of the value. When *allow\_no\_value* is `True` (default: `False`), options without values are accepted; the value held for these is `None` and they are serialized without the trailing delimiter. When *default\_section* is given, it specifies the name for the special section holding default values for other sections and interpolation purposes (normally named `"DEFAULT"`). This value can be retrieved and changed on runtime using the `default_section` instance attribute. Interpolation behaviour may be customized by providing a custom handler through the *interpolation* argument. `None` can be used to turn off interpolation completely, `ExtendedInterpolation()` provides a more advanced variant inspired by `zc.buildout`. More on the subject in the [dedicated documentation section](#interpolation-of-values). All option names used in interpolation will be passed through the [`optionxform()`](#configparser.ConfigParser.optionxform "configparser.ConfigParser.optionxform") method just like any other option name reference. For example, using the default implementation of [`optionxform()`](#configparser.ConfigParser.optionxform "configparser.ConfigParser.optionxform") (which converts option names to lower case), the values `foo %(bar)s` and `foo %(BAR)s` are equivalent. When *converters* is given, it should be a dictionary where each key represents the name of a type converter and each value is a callable implementing the conversion from string to the desired datatype. Every converter gets its own corresponding `get*()` method on the parser object and section proxies. Changed in version 3.1: The default *dict\_type* is [`collections.OrderedDict`](collections#collections.OrderedDict "collections.OrderedDict"). Changed in version 3.2: *allow\_no\_value*, *delimiters*, *comment\_prefixes*, *strict*, *empty\_lines\_in\_values*, *default\_section* and *interpolation* were added. Changed in version 3.5: The *converters* argument was added. Changed in version 3.7: The *defaults* argument is read with [`read_dict()`](#configparser.ConfigParser.read_dict "configparser.ConfigParser.read_dict"), providing consistent behavior across the parser: non-string keys and values are implicitly converted to strings. Changed in version 3.8: The default *dict\_type* is [`dict`](stdtypes#dict "dict"), since it now preserves insertion order. `defaults()` Return a dictionary containing the instance-wide defaults. `sections()` Return a list of the sections available; the *default section* is not included in the list. `add_section(section)` Add a section named *section* to the instance. If a section by the given name already exists, [`DuplicateSectionError`](#configparser.DuplicateSectionError "configparser.DuplicateSectionError") is raised. If the *default section* name is passed, [`ValueError`](exceptions#ValueError "ValueError") is raised. The name of the section must be a string; if not, [`TypeError`](exceptions#TypeError "TypeError") is raised. Changed in version 3.2: Non-string section names raise [`TypeError`](exceptions#TypeError "TypeError"). `has_section(section)` Indicates whether the named *section* is present in the configuration. The *default section* is not acknowledged. `options(section)` Return a list of options available in the specified *section*. `has_option(section, option)` If the given *section* exists, and contains the given *option*, return [`True`](constants#True "True"); otherwise return [`False`](constants#False "False"). If the specified *section* is [`None`](constants#None "None") or an empty string, DEFAULT is assumed. `read(filenames, encoding=None)` Attempt to read and parse an iterable of filenames, returning a list of filenames which were successfully parsed. If *filenames* is a string, a [`bytes`](stdtypes#bytes "bytes") object or a [path-like object](../glossary#term-path-like-object), it is treated as a single filename. If a file named in *filenames* cannot be opened, that file will be ignored. This is designed so that you can specify an iterable of potential configuration file locations (for example, the current directory, the user’s home directory, and some system-wide directory), and all existing configuration files in the iterable will be read. If none of the named files exist, the [`ConfigParser`](#configparser.ConfigParser "configparser.ConfigParser") instance will contain an empty dataset. An application which requires initial values to be loaded from a file should load the required file or files using [`read_file()`](#configparser.ConfigParser.read_file "configparser.ConfigParser.read_file") before calling [`read()`](#configparser.ConfigParser.read "configparser.ConfigParser.read") for any optional files: ``` import configparser, os config = configparser.ConfigParser() config.read_file(open('defaults.cfg')) config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')], encoding='cp1250') ``` New in version 3.2: The *encoding* parameter. Previously, all files were read using the default encoding for [`open()`](functions#open "open"). New in version 3.6.1: The *filenames* parameter accepts a [path-like object](../glossary#term-path-like-object). New in version 3.7: The *filenames* parameter accepts a [`bytes`](stdtypes#bytes "bytes") object. `read_file(f, source=None)` Read and parse configuration data from *f* which must be an iterable yielding Unicode strings (for example files opened in text mode). Optional argument *source* specifies the name of the file being read. If not given and *f* has a `name` attribute, that is used for *source*; the default is `'<???>'`. New in version 3.2: Replaces [`readfp()`](#configparser.ConfigParser.readfp "configparser.ConfigParser.readfp"). `read_string(string, source='<string>')` Parse configuration data from a string. Optional argument *source* specifies a context-specific name of the string passed. If not given, `'<string>'` is used. This should commonly be a filesystem path or a URL. New in version 3.2. `read_dict(dictionary, source='<dict>')` Load configuration from any object that provides a dict-like `items()` method. Keys are section names, values are dictionaries with keys and values that should be present in the section. If the used dictionary type preserves order, sections and their keys will be added in order. Values are automatically converted to strings. Optional argument *source* specifies a context-specific name of the dictionary passed. If not given, `<dict>` is used. This method can be used to copy state between parsers. New in version 3.2. `get(section, option, *, raw=False, vars=None[, fallback])` Get an *option* value for the named *section*. If *vars* is provided, it must be a dictionary. The *option* is looked up in *vars* (if provided), *section*, and in *DEFAULTSECT* in that order. If the key is not found and *fallback* is provided, it is used as a fallback value. `None` can be provided as a *fallback* value. All the `'%'` interpolations are expanded in the return values, unless the *raw* argument is true. Values for interpolation keys are looked up in the same manner as the option. Changed in version 3.2: Arguments *raw*, *vars* and *fallback* are keyword only to protect users from trying to use the third argument as the *fallback* fallback (especially when using the mapping protocol). `getint(section, option, *, raw=False, vars=None[, fallback])` A convenience method which coerces the *option* in the specified *section* to an integer. See [`get()`](#configparser.ConfigParser.get "configparser.ConfigParser.get") for explanation of *raw*, *vars* and *fallback*. `getfloat(section, option, *, raw=False, vars=None[, fallback])` A convenience method which coerces the *option* in the specified *section* to a floating point number. See [`get()`](#configparser.ConfigParser.get "configparser.ConfigParser.get") for explanation of *raw*, *vars* and *fallback*. `getboolean(section, option, *, raw=False, vars=None[, fallback])` A convenience method which coerces the *option* in the specified *section* to a Boolean value. Note that the accepted values for the option are `'1'`, `'yes'`, `'true'`, and `'on'`, which cause this method to return `True`, and `'0'`, `'no'`, `'false'`, and `'off'`, which cause it to return `False`. These string values are checked in a case-insensitive manner. Any other value will cause it to raise [`ValueError`](exceptions#ValueError "ValueError"). See [`get()`](#configparser.ConfigParser.get "configparser.ConfigParser.get") for explanation of *raw*, *vars* and *fallback*. `items(raw=False, vars=None)` `items(section, raw=False, vars=None)` When *section* is not given, return a list of *section\_name*, *section\_proxy* pairs, including DEFAULTSECT. Otherwise, return a list of *name*, *value* pairs for the options in the given *section*. Optional arguments have the same meaning as for the [`get()`](#configparser.ConfigParser.get "configparser.ConfigParser.get") method. Changed in version 3.8: Items present in *vars* no longer appear in the result. The previous behaviour mixed actual parser options with variables provided for interpolation. `set(section, option, value)` If the given section exists, set the given option to the specified value; otherwise raise [`NoSectionError`](#configparser.NoSectionError "configparser.NoSectionError"). *option* and *value* must be strings; if not, [`TypeError`](exceptions#TypeError "TypeError") is raised. `write(fileobject, space_around_delimiters=True)` Write a representation of the configuration to the specified [file object](../glossary#term-file-object), which must be opened in text mode (accepting strings). This representation can be parsed by a future [`read()`](#configparser.ConfigParser.read "configparser.ConfigParser.read") call. If *space\_around\_delimiters* is true, delimiters between keys and values are surrounded by spaces. Note Comments in the original configuration file are not preserved when writing the configuration back. What is considered a comment, depends on the given values for *comment\_prefix* and *inline\_comment\_prefix*. `remove_option(section, option)` Remove the specified *option* from the specified *section*. If the section does not exist, raise [`NoSectionError`](#configparser.NoSectionError "configparser.NoSectionError"). If the option existed to be removed, return [`True`](constants#True "True"); otherwise return [`False`](constants#False "False"). `remove_section(section)` Remove the specified *section* from the configuration. If the section in fact existed, return `True`. Otherwise return `False`. `optionxform(option)` Transforms the option name *option* as found in an input file or as passed in by client code to the form that should be used in the internal structures. The default implementation returns a lower-case version of *option*; subclasses may override this or client code can set an attribute of this name on instances to affect this behavior. You don’t need to subclass the parser to use this method, you can also set it on an instance, to a function that takes a string argument and returns a string. Setting it to `str`, for example, would make option names case sensitive: ``` cfgparser = ConfigParser() cfgparser.optionxform = str ``` Note that when reading configuration files, whitespace around the option names is stripped before [`optionxform()`](#configparser.ConfigParser.optionxform "configparser.ConfigParser.optionxform") is called. `readfp(fp, filename=None)` Deprecated since version 3.2: Use [`read_file()`](#configparser.ConfigParser.read_file "configparser.ConfigParser.read_file") instead. Changed in version 3.2: [`readfp()`](#configparser.ConfigParser.readfp "configparser.ConfigParser.readfp") now iterates on *fp* instead of calling `fp.readline()`. For existing code calling [`readfp()`](#configparser.ConfigParser.readfp "configparser.ConfigParser.readfp") with arguments which don’t support iteration, the following generator may be used as a wrapper around the file-like object: ``` def readline_generator(fp): line = fp.readline() while line: yield line line = fp.readline() ``` Instead of `parser.readfp(fp)` use `parser.read_file(readline_generator(fp))`. `configparser.MAX_INTERPOLATION_DEPTH` The maximum depth for recursive interpolation for `get()` when the *raw* parameter is false. This is relevant only when the default *interpolation* is used. RawConfigParser Objects ----------------------- `class configparser.RawConfigParser(defaults=None, dict_type=dict, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT[, interpolation])` Legacy variant of the [`ConfigParser`](#configparser.ConfigParser "configparser.ConfigParser"). It has interpolation disabled by default and allows for non-string section names, option names, and values via its unsafe `add_section` and `set` methods, as well as the legacy `defaults=` keyword argument handling. Changed in version 3.8: The default *dict\_type* is [`dict`](stdtypes#dict "dict"), since it now preserves insertion order. Note Consider using [`ConfigParser`](#configparser.ConfigParser "configparser.ConfigParser") instead which checks types of the values to be stored internally. If you don’t want interpolation, you can use `ConfigParser(interpolation=None)`. `add_section(section)` Add a section named *section* to the instance. If a section by the given name already exists, [`DuplicateSectionError`](#configparser.DuplicateSectionError "configparser.DuplicateSectionError") is raised. If the *default section* name is passed, [`ValueError`](exceptions#ValueError "ValueError") is raised. Type of *section* is not checked which lets users create non-string named sections. This behaviour is unsupported and may cause internal errors. `set(section, option, value)` If the given section exists, set the given option to the specified value; otherwise raise [`NoSectionError`](#configparser.NoSectionError "configparser.NoSectionError"). While it is possible to use [`RawConfigParser`](#configparser.RawConfigParser "configparser.RawConfigParser") (or [`ConfigParser`](#configparser.ConfigParser "configparser.ConfigParser") with *raw* parameters set to true) for *internal* storage of non-string values, full functionality (including interpolation and output to files) can only be achieved using string values. This method lets users assign non-string values to keys internally. This behaviour is unsupported and will cause errors when attempting to write to a file or get it in non-raw mode. **Use the mapping protocol API** which does not allow such assignments to take place. Exceptions ---------- `exception configparser.Error` Base class for all other [`configparser`](#module-configparser "configparser: Configuration file parser.") exceptions. `exception configparser.NoSectionError` Exception raised when a specified section is not found. `exception configparser.DuplicateSectionError` Exception raised if `add_section()` is called with the name of a section that is already present or in strict parsers when a section if found more than once in a single input file, string or dictionary. New in version 3.2: Optional `source` and `lineno` attributes and arguments to [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") were added. `exception configparser.DuplicateOptionError` Exception raised by strict parsers if a single option appears twice during reading from a single file, string or dictionary. This catches misspellings and case sensitivity-related errors, e.g. a dictionary may have two keys representing the same case-insensitive configuration key. `exception configparser.NoOptionError` Exception raised when a specified option is not found in the specified section. `exception configparser.InterpolationError` Base class for exceptions raised when problems occur performing string interpolation. `exception configparser.InterpolationDepthError` Exception raised when string interpolation cannot be completed because the number of iterations exceeds [`MAX_INTERPOLATION_DEPTH`](#configparser.MAX_INTERPOLATION_DEPTH "configparser.MAX_INTERPOLATION_DEPTH"). Subclass of [`InterpolationError`](#configparser.InterpolationError "configparser.InterpolationError"). `exception configparser.InterpolationMissingOptionError` Exception raised when an option referenced from a value does not exist. Subclass of [`InterpolationError`](#configparser.InterpolationError "configparser.InterpolationError"). `exception configparser.InterpolationSyntaxError` Exception raised when the source text into which substitutions are made does not conform to the required syntax. Subclass of [`InterpolationError`](#configparser.InterpolationError "configparser.InterpolationError"). `exception configparser.MissingSectionHeaderError` Exception raised when attempting to parse a file which has no section headers. `exception configparser.ParsingError` Exception raised when errors occur attempting to parse a file. Changed in version 3.2: The `filename` attribute and [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") argument were renamed to `source` for consistency. #### Footnotes `1(1,2,3,4,5,6,7,8,9,10,11)` Config parsers allow for heavy customization. If you are interested in changing the behaviour outlined by the footnote reference, consult the [Customizing Parser Behaviour](#customizing-parser-behaviour) section.
programming_docs
python Software Packaging and Distribution Software Packaging and Distribution =================================== These libraries help you with publishing and installing Python software. While these modules are designed to work in conjunction with the [Python Package Index](https://pypi.org), they can also be used with a local index server, or without any index server at all. * [`distutils` — Building and installing Python modules](distutils) * [`ensurepip` — Bootstrapping the `pip` installer](ensurepip) + [Command line interface](ensurepip#command-line-interface) + [Module API](ensurepip#module-api) * [`venv` — Creation of virtual environments](venv) + [Creating virtual environments](venv#creating-virtual-environments) + [API](venv#api) + [An example of extending `EnvBuilder`](venv#an-example-of-extending-envbuilder) * [`zipapp` — Manage executable Python zip archives](zipapp) + [Basic Example](zipapp#basic-example) + [Command-Line Interface](zipapp#command-line-interface) + [Python API](zipapp#python-api) + [Examples](zipapp#examples) + [Specifying the Interpreter](zipapp#specifying-the-interpreter) + [Creating Standalone Applications with zipapp](zipapp#creating-standalone-applications-with-zipapp) - [Making a Windows executable](zipapp#making-a-windows-executable) - [Caveats](zipapp#caveats) + [The Python Zip Application Archive Format](zipapp#the-python-zip-application-archive-format) python heapq — Heap queue algorithm heapq — Heap queue algorithm ============================ **Source code:** [Lib/heapq.py](https://github.com/python/cpython/tree/3.9/Lib/heapq.py) This module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm. Heaps are binary trees for which every parent node has a value less than or equal to any of its children. This implementation uses arrays for which `heap[k] <= heap[2*k+1]` and `heap[k] <= heap[2*k+2]` for all *k*, counting elements from zero. For the sake of comparison, non-existing elements are considered to be infinite. The interesting property of a heap is that its smallest element is always the root, `heap[0]`. The API below differs from textbook heap algorithms in two aspects: (a) We use zero-based indexing. This makes the relationship between the index for a node and the indexes for its children slightly less obvious, but is more suitable since Python uses zero-based indexing. (b) Our pop method returns the smallest item, not the largest (called a “min heap” in textbooks; a “max heap” is more common in texts because of its suitability for in-place sorting). These two make it possible to view the heap as a regular Python list without surprises: `heap[0]` is the smallest item, and `heap.sort()` maintains the heap invariant! To create a heap, use a list initialized to `[]`, or you can transform a populated list into a heap via function [`heapify()`](#heapq.heapify "heapq.heapify"). The following functions are provided: `heapq.heappush(heap, item)` Push the value *item* onto the *heap*, maintaining the heap invariant. `heapq.heappop(heap)` Pop and return the smallest item from the *heap*, maintaining the heap invariant. If the heap is empty, [`IndexError`](exceptions#IndexError "IndexError") is raised. To access the smallest item without popping it, use `heap[0]`. `heapq.heappushpop(heap, item)` Push *item* on the heap, then pop and return the smallest item from the *heap*. The combined action runs more efficiently than [`heappush()`](#heapq.heappush "heapq.heappush") followed by a separate call to [`heappop()`](#heapq.heappop "heapq.heappop"). `heapq.heapify(x)` Transform list *x* into a heap, in-place, in linear time. `heapq.heapreplace(heap, item)` Pop and return the smallest item from the *heap*, and also push the new *item*. The heap size doesn’t change. If the heap is empty, [`IndexError`](exceptions#IndexError "IndexError") is raised. This one step operation is more efficient than a [`heappop()`](#heapq.heappop "heapq.heappop") followed by [`heappush()`](#heapq.heappush "heapq.heappush") and can be more appropriate when using a fixed-size heap. The pop/push combination always returns an element from the heap and replaces it with *item*. The value returned may be larger than the *item* added. If that isn’t desired, consider using [`heappushpop()`](#heapq.heappushpop "heapq.heappushpop") instead. Its push/pop combination returns the smaller of the two values, leaving the larger value on the heap. The module also offers three general purpose functions based on heaps. `heapq.merge(*iterables, key=None, reverse=False)` Merge multiple sorted inputs into a single sorted output (for example, merge timestamped entries from multiple log files). Returns an [iterator](../glossary#term-iterator) over the sorted values. Similar to `sorted(itertools.chain(*iterables))` but returns an iterable, does not pull the data into memory all at once, and assumes that each of the input streams is already sorted (smallest to largest). Has two optional arguments which must be specified as keyword arguments. *key* specifies a [key function](../glossary#term-key-function) of one argument that is used to extract a comparison key from each input element. The default value is `None` (compare the elements directly). *reverse* is a boolean value. If set to `True`, then the input elements are merged as if each comparison were reversed. To achieve behavior similar to `sorted(itertools.chain(*iterables), reverse=True)`, all iterables must be sorted from largest to smallest. Changed in version 3.5: Added the optional *key* and *reverse* parameters. `heapq.nlargest(n, iterable, key=None)` Return a list with the *n* largest elements from the dataset defined by *iterable*. *key*, if provided, specifies a function of one argument that is used to extract a comparison key from each element in *iterable* (for example, `key=str.lower`). Equivalent to: `sorted(iterable, key=key, reverse=True)[:n]`. `heapq.nsmallest(n, iterable, key=None)` Return a list with the *n* smallest elements from the dataset defined by *iterable*. *key*, if provided, specifies a function of one argument that is used to extract a comparison key from each element in *iterable* (for example, `key=str.lower`). Equivalent to: `sorted(iterable, key=key)[:n]`. The latter two functions perform best for smaller values of *n*. For larger values, it is more efficient to use the [`sorted()`](functions#sorted "sorted") function. Also, when `n==1`, it is more efficient to use the built-in [`min()`](functions#min "min") and [`max()`](functions#max "max") functions. If repeated usage of these functions is required, consider turning the iterable into an actual heap. Basic Examples -------------- A [heapsort](https://en.wikipedia.org/wiki/Heapsort) can be implemented by pushing all values onto a heap and then popping off the smallest values one at a time: ``` >>> def heapsort(iterable): ... h = [] ... for value in iterable: ... heappush(h, value) ... return [heappop(h) for i in range(len(h))] ... >>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0]) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ``` This is similar to `sorted(iterable)`, but unlike [`sorted()`](functions#sorted "sorted"), this implementation is not stable. Heap elements can be tuples. This is useful for assigning comparison values (such as task priorities) alongside the main record being tracked: ``` >>> h = [] >>> heappush(h, (5, 'write code')) >>> heappush(h, (7, 'release product')) >>> heappush(h, (1, 'write spec')) >>> heappush(h, (3, 'create tests')) >>> heappop(h) (1, 'write spec') ``` Priority Queue Implementation Notes ----------------------------------- A [priority queue](https://en.wikipedia.org/wiki/Priority_queue) is common use for a heap, and it presents several implementation challenges: * Sort stability: how do you get two tasks with equal priorities to be returned in the order they were originally added? * Tuple comparison breaks for (priority, task) pairs if the priorities are equal and the tasks do not have a default comparison order. * If the priority of a task changes, how do you move it to a new position in the heap? * Or if a pending task needs to be deleted, how do you find it and remove it from the queue? A solution to the first two challenges is to store entries as 3-element list including the priority, an entry count, and the task. The entry count serves as a tie-breaker so that two tasks with the same priority are returned in the order they were added. And since no two entry counts are the same, the tuple comparison will never attempt to directly compare two tasks. Another solution to the problem of non-comparable tasks is to create a wrapper class that ignores the task item and only compares the priority field: ``` from dataclasses import dataclass, field from typing import Any @dataclass(order=True) class PrioritizedItem: priority: int item: Any=field(compare=False) ``` The remaining challenges revolve around finding a pending task and making changes to its priority or removing it entirely. Finding a task can be done with a dictionary pointing to an entry in the queue. Removing the entry or changing its priority is more difficult because it would break the heap structure invariants. So, a possible solution is to mark the entry as removed and add a new entry with the revised priority: ``` pq = [] # list of entries arranged in a heap entry_finder = {} # mapping of tasks to entries REMOVED = '<removed-task>' # placeholder for a removed task counter = itertools.count() # unique sequence count def add_task(task, priority=0): 'Add a new task or update the priority of an existing task' if task in entry_finder: remove_task(task) count = next(counter) entry = [priority, count, task] entry_finder[task] = entry heappush(pq, entry) def remove_task(task): 'Mark an existing task as REMOVED. Raise KeyError if not found.' entry = entry_finder.pop(task) entry[-1] = REMOVED def pop_task(): 'Remove and return the lowest priority task. Raise KeyError if empty.' while pq: priority, count, task = heappop(pq) if task is not REMOVED: del entry_finder[task] return task raise KeyError('pop from an empty priority queue') ``` Theory ------ Heaps are arrays for which `a[k] <= a[2*k+1]` and `a[k] <= a[2*k+2]` for all *k*, counting elements from 0. For the sake of comparison, non-existing elements are considered to be infinite. The interesting property of a heap is that `a[0]` is always its smallest element. The strange invariant above is meant to be an efficient memory representation for a tournament. The numbers below are *k*, not `a[k]`: ``` 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ``` In the tree above, each cell *k* is topping `2*k+1` and `2*k+2`. In a usual binary tournament we see in sports, each cell is the winner over the two cells it tops, and we can trace the winner down the tree to see all opponents s/he had. However, in many computer applications of such tournaments, we do not need to trace the history of a winner. To be more memory efficient, when a winner is promoted, we try to replace it by something else at a lower level, and the rule becomes that a cell and the two cells it tops contain three different items, but the top cell “wins” over the two topped cells. If this heap invariant is protected at all time, index 0 is clearly the overall winner. The simplest algorithmic way to remove it and find the “next” winner is to move some loser (let’s say cell 30 in the diagram above) into the 0 position, and then percolate this new 0 down the tree, exchanging values, until the invariant is re-established. This is clearly logarithmic on the total number of items in the tree. By iterating over all items, you get an O(n log n) sort. A nice feature of this sort is that you can efficiently insert new items while the sort is going on, provided that the inserted items are not “better” than the last 0’th element you extracted. This is especially useful in simulation contexts, where the tree holds all incoming events, and the “win” condition means the smallest scheduled time. When an event schedules other events for execution, they are scheduled into the future, so they can easily go into the heap. So, a heap is a good structure for implementing schedulers (this is what I used for my MIDI sequencer :-). Various structures for implementing schedulers have been extensively studied, and heaps are good for this, as they are reasonably speedy, the speed is almost constant, and the worst case is not much different than the average case. However, there are other representations which are more efficient overall, yet the worst cases might be terrible. Heaps are also very useful in big disk sorts. You most probably all know that a big sort implies producing “runs” (which are pre-sorted sequences, whose size is usually related to the amount of CPU memory), followed by a merging passes for these runs, which merging is often very cleverly organised [1](#id2). It is very important that the initial sort produces the longest runs possible. Tournaments are a good way to achieve that. If, using all the memory available to hold a tournament, you replace and percolate items that happen to fit the current run, you’ll produce runs which are twice the size of the memory for random input, and much better for input fuzzily ordered. Moreover, if you output the 0’th item on disk and get an input which may not fit in the current tournament (because the value “wins” over the last output value), it cannot fit in the heap, so the size of the heap decreases. The freed memory could be cleverly reused immediately for progressively building a second heap, which grows at exactly the same rate the first heap is melting. When the first heap completely vanishes, you switch heaps and start a new run. Clever and quite effective! In a word, heaps are useful memory structures to know. I use them in a few applications, and I think it is good to keep a ‘heap’ module around. :-) #### Footnotes `1` The disk balancing algorithms which are current, nowadays, are more annoying than clever, and this is a consequence of the seeking capabilities of the disks. On devices which cannot seek, like big tape drives, the story was quite different, and one had to be very clever to ensure (far in advance) that each tape movement will be the most effective possible (that is, will best participate at “progressing” the merge). Some tapes were even able to read backwards, and this was also used to avoid the rewinding time. Believe me, real good tape sorts were quite spectacular to watch! From all times, sorting has always been a Great Art! :-) python subprocess — Subprocess management subprocess — Subprocess management ================================== **Source code:** [Lib/subprocess.py](https://github.com/python/cpython/tree/3.9/Lib/subprocess.py) The [`subprocess`](#module-subprocess "subprocess: Subprocess management.") module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions: ``` os.system os.spawn* ``` Information about how the [`subprocess`](#module-subprocess "subprocess: Subprocess management.") module can be used to replace these modules and functions can be found in the following sections. See also [**PEP 324**](https://www.python.org/dev/peps/pep-0324) – PEP proposing the subprocess module Using the subprocess Module --------------------------- The recommended approach to invoking subprocesses is to use the [`run()`](#subprocess.run "subprocess.run") function for all use cases it can handle. For more advanced use cases, the underlying [`Popen`](#subprocess.Popen "subprocess.Popen") interface can be used directly. The [`run()`](#subprocess.run "subprocess.run") function was added in Python 3.5; if you need to retain compatibility with older versions, see the [Older high-level API](#call-function-trio) section. `subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None, **other_popen_kwargs)` Run the command described by *args*. Wait for command to complete, then return a [`CompletedProcess`](#subprocess.CompletedProcess "subprocess.CompletedProcess") instance. The arguments shown above are merely the most common ones, described below in [Frequently Used Arguments](#frequently-used-arguments) (hence the use of keyword-only notation in the abbreviated signature). The full function signature is largely the same as that of the [`Popen`](#subprocess.Popen "subprocess.Popen") constructor - most of the arguments to this function are passed through to that interface. (*timeout*, *input*, *check*, and *capture\_output* are not.) If *capture\_output* is true, stdout and stderr will be captured. When used, the internal [`Popen`](#subprocess.Popen "subprocess.Popen") object is automatically created with `stdout=PIPE` and `stderr=PIPE`. The *stdout* and *stderr* arguments may not be supplied at the same time as *capture\_output*. If you wish to capture and combine both streams into one, use `stdout=PIPE` and `stderr=STDOUT` instead of *capture\_output*. The *timeout* argument is passed to [`Popen.communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate"). If the timeout expires, the child process will be killed and waited for. The [`TimeoutExpired`](#subprocess.TimeoutExpired "subprocess.TimeoutExpired") exception will be re-raised after the child process has terminated. The *input* argument is passed to [`Popen.communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate") and thus to the subprocess’s stdin. If used it must be a byte sequence, or a string if *encoding* or *errors* is specified or *text* is true. When used, the internal [`Popen`](#subprocess.Popen "subprocess.Popen") object is automatically created with `stdin=PIPE`, and the *stdin* argument may not be used as well. If *check* is true, and the process exits with a non-zero exit code, a [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError") exception will be raised. Attributes of that exception hold the arguments, the exit code, and stdout and stderr if they were captured. If *encoding* or *errors* are specified, or *text* is true, file objects for stdin, stdout and stderr are opened in text mode using the specified *encoding* and *errors* or the [`io.TextIOWrapper`](io#io.TextIOWrapper "io.TextIOWrapper") default. The *universal\_newlines* argument is equivalent to *text* and is provided for backwards compatibility. By default, file objects are opened in binary mode. If *env* is not `None`, it must be a mapping that defines the environment variables for the new process; these are used instead of the default behavior of inheriting the current process’ environment. It is passed directly to [`Popen`](#subprocess.Popen "subprocess.Popen"). Examples: ``` >>> subprocess.run(["ls", "-l"]) # doesn't capture output CompletedProcess(args=['ls', '-l'], returncode=0) >>> subprocess.run("exit 1", shell=True, check=True) Traceback (most recent call last): ... subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1 >>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True) CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0, stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'') ``` New in version 3.5. Changed in version 3.6: Added *encoding* and *errors* parameters Changed in version 3.7: Added the *text* parameter, as a more understandable alias of *universal\_newlines*. Added the *capture\_output* parameter. `class subprocess.CompletedProcess` The return value from [`run()`](#subprocess.run "subprocess.run"), representing a process that has finished. `args` The arguments used to launch the process. This may be a list or a string. `returncode` Exit status of the child process. Typically, an exit status of 0 indicates that it ran successfully. A negative value `-N` indicates that the child was terminated by signal `N` (POSIX only). `stdout` Captured stdout from the child process. A bytes sequence, or a string if [`run()`](#subprocess.run "subprocess.run") was called with an encoding, errors, or text=True. `None` if stdout was not captured. If you ran the process with `stderr=subprocess.STDOUT`, stdout and stderr will be combined in this attribute, and [`stderr`](#subprocess.CompletedProcess.stderr "subprocess.CompletedProcess.stderr") will be `None`. `stderr` Captured stderr from the child process. A bytes sequence, or a string if [`run()`](#subprocess.run "subprocess.run") was called with an encoding, errors, or text=True. `None` if stderr was not captured. `check_returncode()` If [`returncode`](#subprocess.CompletedProcess.returncode "subprocess.CompletedProcess.returncode") is non-zero, raise a [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError"). New in version 3.5. `subprocess.DEVNULL` Special value that can be used as the *stdin*, *stdout* or *stderr* argument to [`Popen`](#subprocess.Popen "subprocess.Popen") and indicates that the special file [`os.devnull`](os#os.devnull "os.devnull") will be used. New in version 3.3. `subprocess.PIPE` Special value that can be used as the *stdin*, *stdout* or *stderr* argument to [`Popen`](#subprocess.Popen "subprocess.Popen") and indicates that a pipe to the standard stream should be opened. Most useful with [`Popen.communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate"). `subprocess.STDOUT` Special value that can be used as the *stderr* argument to [`Popen`](#subprocess.Popen "subprocess.Popen") and indicates that standard error should go into the same handle as standard output. `exception subprocess.SubprocessError` Base class for all other exceptions from this module. New in version 3.3. `exception subprocess.TimeoutExpired` Subclass of [`SubprocessError`](#subprocess.SubprocessError "subprocess.SubprocessError"), raised when a timeout expires while waiting for a child process. `cmd` Command that was used to spawn the child process. `timeout` Timeout in seconds. `output` Output of the child process if it was captured by [`run()`](#subprocess.run "subprocess.run") or [`check_output()`](#subprocess.check_output "subprocess.check_output"). Otherwise, `None`. `stdout` Alias for output, for symmetry with [`stderr`](#subprocess.TimeoutExpired.stderr "subprocess.TimeoutExpired.stderr"). `stderr` Stderr output of the child process if it was captured by [`run()`](#subprocess.run "subprocess.run"). Otherwise, `None`. New in version 3.3. Changed in version 3.5: *stdout* and *stderr* attributes added `exception subprocess.CalledProcessError` Subclass of [`SubprocessError`](#subprocess.SubprocessError "subprocess.SubprocessError"), raised when a process run by [`check_call()`](#subprocess.check_call "subprocess.check_call"), [`check_output()`](#subprocess.check_output "subprocess.check_output"), or [`run()`](#subprocess.run "subprocess.run") (with `check=True`) returns a non-zero exit status. `returncode` Exit status of the child process. If the process exited due to a signal, this will be the negative signal number. `cmd` Command that was used to spawn the child process. `output` Output of the child process if it was captured by [`run()`](#subprocess.run "subprocess.run") or [`check_output()`](#subprocess.check_output "subprocess.check_output"). Otherwise, `None`. `stdout` Alias for output, for symmetry with [`stderr`](#subprocess.CalledProcessError.stderr "subprocess.CalledProcessError.stderr"). `stderr` Stderr output of the child process if it was captured by [`run()`](#subprocess.run "subprocess.run"). Otherwise, `None`. Changed in version 3.5: *stdout* and *stderr* attributes added ### Frequently Used Arguments To support a wide variety of use cases, the [`Popen`](#subprocess.Popen "subprocess.Popen") constructor (and the convenience functions) accept a large number of optional arguments. For most typical use cases, many of these arguments can be safely left at their default values. The arguments that are most commonly needed are: *args* is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either *shell* must be [`True`](constants#True "True") (see below) or else the string must simply name the program to be executed without specifying any arguments. *stdin*, *stdout* and *stderr* specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are [`PIPE`](#subprocess.PIPE "subprocess.PIPE"), [`DEVNULL`](#subprocess.DEVNULL "subprocess.DEVNULL"), an existing file descriptor (a positive integer), an existing file object with a valid file descriptor, and `None`. [`PIPE`](#subprocess.PIPE "subprocess.PIPE") indicates that a new pipe to the child should be created. [`DEVNULL`](#subprocess.DEVNULL "subprocess.DEVNULL") indicates that the special file [`os.devnull`](os#os.devnull "os.devnull") will be used. With the default settings of `None`, no redirection will occur; the child’s file handles will be inherited from the parent. Additionally, *stderr* can be [`STDOUT`](#subprocess.STDOUT "subprocess.STDOUT"), which indicates that the stderr data from the child process should be captured into the same file handle as for *stdout*. If *encoding* or *errors* are specified, or *text* (also known as *universal\_newlines*) is true, the file objects *stdin*, *stdout* and *stderr* will be opened in text mode using the *encoding* and *errors* specified in the call or the defaults for [`io.TextIOWrapper`](io#io.TextIOWrapper "io.TextIOWrapper"). For *stdin*, line ending characters `'\n'` in the input will be converted to the default line separator [`os.linesep`](os#os.linesep "os.linesep"). For *stdout* and *stderr*, all line endings in the output will be converted to `'\n'`. For more information see the documentation of the [`io.TextIOWrapper`](io#io.TextIOWrapper "io.TextIOWrapper") class when the *newline* argument to its constructor is `None`. If text mode is not used, *stdin*, *stdout* and *stderr* will be opened as binary streams. No encoding or line ending conversion is performed. New in version 3.6: Added *encoding* and *errors* parameters. New in version 3.7: Added the *text* parameter as an alias for *universal\_newlines*. Note The newlines attribute of the file objects [`Popen.stdin`](#subprocess.Popen.stdin "subprocess.Popen.stdin"), [`Popen.stdout`](#subprocess.Popen.stdout "subprocess.Popen.stdout") and [`Popen.stderr`](#subprocess.Popen.stderr "subprocess.Popen.stderr") are not updated by the [`Popen.communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate") method. If *shell* is `True`, the specified command will be executed through the shell. This can be useful if you are using Python primarily for the enhanced control flow it offers over most system shells and still want convenient access to other shell features such as shell pipes, filename wildcards, environment variable expansion, and expansion of `~` to a user’s home directory. However, note that Python itself offers implementations of many shell-like features (in particular, [`glob`](glob#module-glob "glob: Unix shell style pathname pattern expansion."), [`fnmatch`](fnmatch#module-fnmatch "fnmatch: Unix shell style filename pattern matching."), [`os.walk()`](os#os.walk "os.walk"), [`os.path.expandvars()`](os.path#os.path.expandvars "os.path.expandvars"), [`os.path.expanduser()`](os.path#os.path.expanduser "os.path.expanduser"), and [`shutil`](shutil#module-shutil "shutil: High-level file operations, including copying.")). Changed in version 3.3: When *universal\_newlines* is `True`, the class uses the encoding [`locale.getpreferredencoding(False)`](locale#locale.getpreferredencoding "locale.getpreferredencoding") instead of `locale.getpreferredencoding()`. See the [`io.TextIOWrapper`](io#io.TextIOWrapper "io.TextIOWrapper") class for more information on this change. Note Read the [Security Considerations](#security-considerations) section before using `shell=True`. These options, along with all of the other options, are described in more detail in the [`Popen`](#subprocess.Popen "subprocess.Popen") constructor documentation. ### Popen Constructor The underlying process creation and management in this module is handled by the [`Popen`](#subprocess.Popen "subprocess.Popen") class. It offers a lot of flexibility so that developers are able to handle the less common cases not covered by the convenience functions. `class subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=None, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, group=None, extra_groups=None, user=None, umask=-1, encoding=None, errors=None, text=None)` Execute a child program in a new process. On POSIX, the class uses [`os.execvp()`](os#os.execvp "os.execvp")-like behavior to execute the child program. On Windows, the class uses the Windows `CreateProcess()` function. The arguments to [`Popen`](#subprocess.Popen "subprocess.Popen") are as follows. *args* should be a sequence of program arguments or else a single string or [path-like object](../glossary#term-path-like-object). By default, the program to execute is the first item in *args* if *args* is a sequence. If *args* is a string, the interpretation is platform-dependent and described below. See the *shell* and *executable* arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass *args* as a sequence. An example of passing some arguments to an external program as a sequence is: ``` Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."]) ``` On POSIX, if *args* is a string, the string is interpreted as the name or path of the program to execute. However, this can only be done if not passing arguments to the program. Note It may not be obvious how to break a shell command into a sequence of arguments, especially in complex cases. [`shlex.split()`](shlex#shlex.split "shlex.split") can illustrate how to determine the correct tokenization for *args*: ``` >>> import shlex, subprocess >>> command_line = input() /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'" >>> args = shlex.split(command_line) >>> print(args) ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"] >>> p = subprocess.Popen(args) # Success! ``` Note in particular that options (such as *-input*) and arguments (such as *eggs.txt*) that are separated by whitespace in the shell go in separate list elements, while arguments that need quoting or backslash escaping when used in the shell (such as filenames containing spaces or the *echo* command shown above) are single list elements. On Windows, if *args* is a sequence, it will be converted to a string in a manner described in [Converting an argument sequence to a string on Windows](#converting-argument-sequence). This is because the underlying `CreateProcess()` operates on strings. Changed in version 3.6: *args* parameter accepts a [path-like object](../glossary#term-path-like-object) if *shell* is `False` and a sequence containing path-like objects on POSIX. Changed in version 3.8: *args* parameter accepts a [path-like object](../glossary#term-path-like-object) if *shell* is `False` and a sequence containing bytes and path-like objects on Windows. The *shell* argument (which defaults to `False`) specifies whether to use the shell as the program to execute. If *shell* is `True`, it is recommended to pass *args* as a string rather than as a sequence. On POSIX with `shell=True`, the shell defaults to `/bin/sh`. If *args* is a string, the string specifies the command to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If *args* is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself. That is to say, [`Popen`](#subprocess.Popen "subprocess.Popen") does the equivalent of: ``` Popen(['/bin/sh', '-c', args[0], args[1], ...]) ``` On Windows with `shell=True`, the `COMSPEC` environment variable specifies the default shell. The only time you need to specify `shell=True` on Windows is when the command you wish to execute is built into the shell (e.g. **dir** or **copy**). You do not need `shell=True` to run a batch file or console-based executable. Note Read the [Security Considerations](#security-considerations) section before using `shell=True`. *bufsize* will be supplied as the corresponding argument to the [`open()`](functions#open "open") function when creating the stdin/stdout/stderr pipe file objects: * `0` means unbuffered (read and write are one system call and can return short) * `1` means line buffered (only usable if `universal_newlines=True` i.e., in a text mode) * any other positive value means use a buffer of approximately that size * negative bufsize (the default) means the system default of io.DEFAULT\_BUFFER\_SIZE will be used. Changed in version 3.3.1: *bufsize* now defaults to -1 to enable buffering by default to match the behavior that most code expects. In versions prior to Python 3.2.4 and 3.3.1 it incorrectly defaulted to `0` which was unbuffered and allowed short reads. This was unintentional and did not match the behavior of Python 2 as most code expected. The *executable* argument specifies a replacement program to execute. It is very seldom needed. When `shell=False`, *executable* replaces the program to execute specified by *args*. However, the original *args* is still passed to the program. Most programs treat the program specified by *args* as the command name, which can then be different from the program actually executed. On POSIX, the *args* name becomes the display name for the executable in utilities such as **ps**. If `shell=True`, on POSIX the *executable* argument specifies a replacement shell for the default `/bin/sh`. Changed in version 3.6: *executable* parameter accepts a [path-like object](../glossary#term-path-like-object) on POSIX. Changed in version 3.8: *executable* parameter accepts a bytes and [path-like object](../glossary#term-path-like-object) on Windows. *stdin*, *stdout* and *stderr* specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are [`PIPE`](#subprocess.PIPE "subprocess.PIPE"), [`DEVNULL`](#subprocess.DEVNULL "subprocess.DEVNULL"), an existing file descriptor (a positive integer), an existing [file object](../glossary#term-file-object) with a valid file descriptor, and `None`. [`PIPE`](#subprocess.PIPE "subprocess.PIPE") indicates that a new pipe to the child should be created. [`DEVNULL`](#subprocess.DEVNULL "subprocess.DEVNULL") indicates that the special file [`os.devnull`](os#os.devnull "os.devnull") will be used. With the default settings of `None`, no redirection will occur; the child’s file handles will be inherited from the parent. Additionally, *stderr* can be [`STDOUT`](#subprocess.STDOUT "subprocess.STDOUT"), which indicates that the stderr data from the applications should be captured into the same file handle as for stdout. If *preexec\_fn* is set to a callable object, this object will be called in the child process just before the child is executed. (POSIX only) Warning The *preexec\_fn* parameter is not safe to use in the presence of threads in your application. The child process could deadlock before exec is called. If you must use it, keep it trivial! Minimize the number of libraries you call into. Note If you need to modify the environment for the child use the *env* parameter rather than doing it in a *preexec\_fn*. The *start\_new\_session* parameter can take the place of a previously common use of *preexec\_fn* to call os.setsid() in the child. Changed in version 3.8: The *preexec\_fn* parameter is no longer supported in subinterpreters. The use of the parameter in a subinterpreter raises [`RuntimeError`](exceptions#RuntimeError "RuntimeError"). The new restriction may affect applications that are deployed in mod\_wsgi, uWSGI, and other embedded environments. If *close\_fds* is true, all file descriptors except `0`, `1` and `2` will be closed before the child process is executed. Otherwise when *close\_fds* is false, file descriptors obey their inheritable flag as described in [Inheritance of File Descriptors](os#fd-inheritance). On Windows, if *close\_fds* is true then no handles will be inherited by the child process unless explicitly passed in the `handle_list` element of [`STARTUPINFO.lpAttributeList`](#subprocess.STARTUPINFO.lpAttributeList "subprocess.STARTUPINFO.lpAttributeList"), or by standard handle redirection. Changed in version 3.2: The default for *close\_fds* was changed from [`False`](constants#False "False") to what is described above. Changed in version 3.7: On Windows the default for *close\_fds* was changed from [`False`](constants#False "False") to [`True`](constants#True "True") when redirecting the standard handles. It’s now possible to set *close\_fds* to [`True`](constants#True "True") when redirecting the standard handles. *pass\_fds* is an optional sequence of file descriptors to keep open between the parent and child. Providing any *pass\_fds* forces *close\_fds* to be [`True`](constants#True "True"). (POSIX only) Changed in version 3.2: The *pass\_fds* parameter was added. If *cwd* is not `None`, the function changes the working directory to *cwd* before executing the child. *cwd* can be a string, bytes or [path-like](../glossary#term-path-like-object) object. In particular, the function looks for *executable* (or for the first item in *args*) relative to *cwd* if the executable path is a relative path. Changed in version 3.6: *cwd* parameter accepts a [path-like object](../glossary#term-path-like-object) on POSIX. Changed in version 3.7: *cwd* parameter accepts a [path-like object](../glossary#term-path-like-object) on Windows. Changed in version 3.8: *cwd* parameter accepts a bytes object on Windows. If *restore\_signals* is true (the default) all signals that Python has set to SIG\_IGN are restored to SIG\_DFL in the child process before the exec. Currently this includes the SIGPIPE, SIGXFZ and SIGXFSZ signals. (POSIX only) Changed in version 3.2: *restore\_signals* was added. If *start\_new\_session* is true the setsid() system call will be made in the child process prior to the execution of the subprocess. (POSIX only) Changed in version 3.2: *start\_new\_session* was added. If *group* is not `None`, the setregid() system call will be made in the child process prior to the execution of the subprocess. If the provided value is a string, it will be looked up via [`grp.getgrnam()`](grp#grp.getgrnam "grp.getgrnam") and the value in `gr_gid` will be used. If the value is an integer, it will be passed verbatim. (POSIX only) [Availability](https://docs.python.org/3.9/library/intro.html#availability): POSIX New in version 3.9. If *extra\_groups* is not `None`, the setgroups() system call will be made in the child process prior to the execution of the subprocess. Strings provided in *extra\_groups* will be looked up via [`grp.getgrnam()`](grp#grp.getgrnam "grp.getgrnam") and the values in `gr_gid` will be used. Integer values will be passed verbatim. (POSIX only) [Availability](https://docs.python.org/3.9/library/intro.html#availability): POSIX New in version 3.9. If *user* is not `None`, the setreuid() system call will be made in the child process prior to the execution of the subprocess. If the provided value is a string, it will be looked up via [`pwd.getpwnam()`](pwd#pwd.getpwnam "pwd.getpwnam") and the value in `pw_uid` will be used. If the value is an integer, it will be passed verbatim. (POSIX only) [Availability](https://docs.python.org/3.9/library/intro.html#availability): POSIX New in version 3.9. If *umask* is not negative, the umask() system call will be made in the child process prior to the execution of the subprocess. [Availability](https://docs.python.org/3.9/library/intro.html#availability): POSIX New in version 3.9. If *env* is not `None`, it must be a mapping that defines the environment variables for the new process; these are used instead of the default behavior of inheriting the current process’ environment. Note If specified, *env* must provide any variables required for the program to execute. On Windows, in order to run a [side-by-side assembly](https://en.wikipedia.org/wiki/Side-by-Side_Assembly) the specified *env* **must** include a valid `SystemRoot`. If *encoding* or *errors* are specified, or *text* is true, the file objects *stdin*, *stdout* and *stderr* are opened in text mode with the specified encoding and *errors*, as described above in [Frequently Used Arguments](#frequently-used-arguments). The *universal\_newlines* argument is equivalent to *text* and is provided for backwards compatibility. By default, file objects are opened in binary mode. New in version 3.6: *encoding* and *errors* were added. New in version 3.7: *text* was added as a more readable alias for *universal\_newlines*. If given, *startupinfo* will be a [`STARTUPINFO`](#subprocess.STARTUPINFO "subprocess.STARTUPINFO") object, which is passed to the underlying `CreateProcess` function. *creationflags*, if given, can be one or more of the following flags: * [`CREATE_NEW_CONSOLE`](#subprocess.CREATE_NEW_CONSOLE "subprocess.CREATE_NEW_CONSOLE") * [`CREATE_NEW_PROCESS_GROUP`](#subprocess.CREATE_NEW_PROCESS_GROUP "subprocess.CREATE_NEW_PROCESS_GROUP") * [`ABOVE_NORMAL_PRIORITY_CLASS`](#subprocess.ABOVE_NORMAL_PRIORITY_CLASS "subprocess.ABOVE_NORMAL_PRIORITY_CLASS") * [`BELOW_NORMAL_PRIORITY_CLASS`](#subprocess.BELOW_NORMAL_PRIORITY_CLASS "subprocess.BELOW_NORMAL_PRIORITY_CLASS") * [`HIGH_PRIORITY_CLASS`](#subprocess.HIGH_PRIORITY_CLASS "subprocess.HIGH_PRIORITY_CLASS") * [`IDLE_PRIORITY_CLASS`](#subprocess.IDLE_PRIORITY_CLASS "subprocess.IDLE_PRIORITY_CLASS") * [`NORMAL_PRIORITY_CLASS`](#subprocess.NORMAL_PRIORITY_CLASS "subprocess.NORMAL_PRIORITY_CLASS") * [`REALTIME_PRIORITY_CLASS`](#subprocess.REALTIME_PRIORITY_CLASS "subprocess.REALTIME_PRIORITY_CLASS") * [`CREATE_NO_WINDOW`](#subprocess.CREATE_NO_WINDOW "subprocess.CREATE_NO_WINDOW") * [`DETACHED_PROCESS`](#subprocess.DETACHED_PROCESS "subprocess.DETACHED_PROCESS") * [`CREATE_DEFAULT_ERROR_MODE`](#subprocess.CREATE_DEFAULT_ERROR_MODE "subprocess.CREATE_DEFAULT_ERROR_MODE") * [`CREATE_BREAKAWAY_FROM_JOB`](#subprocess.CREATE_BREAKAWAY_FROM_JOB "subprocess.CREATE_BREAKAWAY_FROM_JOB") Popen objects are supported as context managers via the [`with`](../reference/compound_stmts#with) statement: on exit, standard file descriptors are closed, and the process is waited for. ``` with Popen(["ifconfig"], stdout=PIPE) as proc: log.write(proc.stdout.read()) ``` Popen and the other functions in this module that use it raise an [auditing event](sys#auditing) `subprocess.Popen` with arguments `executable`, `args`, `cwd`, and `env`. The value for `args` may be a single string or a list of strings, depending on platform. Changed in version 3.2: Added context manager support. Changed in version 3.6: Popen destructor now emits a [`ResourceWarning`](exceptions#ResourceWarning "ResourceWarning") warning if the child process is still running. Changed in version 3.8: Popen can use [`os.posix_spawn()`](os#os.posix_spawn "os.posix_spawn") in some cases for better performance. On Windows Subsystem for Linux and QEMU User Emulation, Popen constructor using [`os.posix_spawn()`](os#os.posix_spawn "os.posix_spawn") no longer raise an exception on errors like missing program, but the child process fails with a non-zero [`returncode`](#subprocess.Popen.returncode "subprocess.Popen.returncode"). ### Exceptions Exceptions raised in the child process, before the new program has started to execute, will be re-raised in the parent. The most common exception raised is [`OSError`](exceptions#OSError "OSError"). This occurs, for example, when trying to execute a non-existent file. Applications should prepare for [`OSError`](exceptions#OSError "OSError") exceptions. Note that, when `shell=True`, [`OSError`](exceptions#OSError "OSError") will be raised by the child only if the selected shell itself was not found. To determine if the shell failed to find the requested application, it is necessary to check the return code or output from the subprocess. A [`ValueError`](exceptions#ValueError "ValueError") will be raised if [`Popen`](#subprocess.Popen "subprocess.Popen") is called with invalid arguments. [`check_call()`](#subprocess.check_call "subprocess.check_call") and [`check_output()`](#subprocess.check_output "subprocess.check_output") will raise [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError") if the called process returns a non-zero return code. All of the functions and methods that accept a *timeout* parameter, such as [`call()`](#subprocess.call "subprocess.call") and [`Popen.communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate") will raise [`TimeoutExpired`](#subprocess.TimeoutExpired "subprocess.TimeoutExpired") if the timeout expires before the process exits. Exceptions defined in this module all inherit from [`SubprocessError`](#subprocess.SubprocessError "subprocess.SubprocessError"). New in version 3.3: The [`SubprocessError`](#subprocess.SubprocessError "subprocess.SubprocessError") base class was added. Security Considerations ----------------------- Unlike some other popen functions, this implementation will never implicitly call a system shell. This means that all characters, including shell metacharacters, can safely be passed to child processes. If the shell is invoked explicitly, via `shell=True`, it is the application’s responsibility to ensure that all whitespace and metacharacters are quoted appropriately to avoid [shell injection](https://en.wikipedia.org/wiki/Shell_injection#Shell_injection) vulnerabilities. When using `shell=True`, the [`shlex.quote()`](shlex#shlex.quote "shlex.quote") function can be used to properly escape whitespace and shell metacharacters in strings that are going to be used to construct shell commands. Popen Objects ------------- Instances of the [`Popen`](#subprocess.Popen "subprocess.Popen") class have the following methods: `Popen.poll()` Check if child process has terminated. Set and return [`returncode`](#subprocess.Popen.returncode "subprocess.Popen.returncode") attribute. Otherwise, returns `None`. `Popen.wait(timeout=None)` Wait for child process to terminate. Set and return [`returncode`](#subprocess.Popen.returncode "subprocess.Popen.returncode") attribute. If the process does not terminate after *timeout* seconds, raise a [`TimeoutExpired`](#subprocess.TimeoutExpired "subprocess.TimeoutExpired") exception. It is safe to catch this exception and retry the wait. Note This will deadlock when using `stdout=PIPE` or `stderr=PIPE` and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use [`Popen.communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate") when using pipes to avoid that. Note The function is implemented using a busy loop (non-blocking call and short sleeps). Use the [`asyncio`](asyncio#module-asyncio "asyncio: Asynchronous I/O.") module for an asynchronous wait: see [`asyncio.create_subprocess_exec`](asyncio-subprocess#asyncio.create_subprocess_exec "asyncio.create_subprocess_exec"). Changed in version 3.3: *timeout* was added. `Popen.communicate(input=None, timeout=None)` Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate and set the [`returncode`](#subprocess.Popen.returncode "subprocess.Popen.returncode") attribute. The optional *input* argument should be data to be sent to the child process, or `None`, if no data should be sent to the child. If streams were opened in text mode, *input* must be a string. Otherwise, it must be bytes. [`communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate") returns a tuple `(stdout_data, stderr_data)`. The data will be strings if streams were opened in text mode; otherwise, bytes. Note that if you want to send data to the process’s stdin, you need to create the Popen object with `stdin=PIPE`. Similarly, to get anything other than `None` in the result tuple, you need to give `stdout=PIPE` and/or `stderr=PIPE` too. If the process does not terminate after *timeout* seconds, a [`TimeoutExpired`](#subprocess.TimeoutExpired "subprocess.TimeoutExpired") exception will be raised. Catching this exception and retrying communication will not lose any output. The child process is not killed if the timeout expires, so in order to cleanup properly a well-behaved application should kill the child process and finish communication: ``` proc = subprocess.Popen(...) try: outs, errs = proc.communicate(timeout=15) except TimeoutExpired: proc.kill() outs, errs = proc.communicate() ``` Note The data read is buffered in memory, so do not use this method if the data size is large or unlimited. Changed in version 3.3: *timeout* was added. `Popen.send_signal(signal)` Sends the signal *signal* to the child. Do nothing if the process completed. Note On Windows, SIGTERM is an alias for [`terminate()`](#subprocess.Popen.terminate "subprocess.Popen.terminate"). CTRL\_C\_EVENT and CTRL\_BREAK\_EVENT can be sent to processes started with a *creationflags* parameter which includes `CREATE_NEW_PROCESS_GROUP`. `Popen.terminate()` Stop the child. On POSIX OSs the method sends SIGTERM to the child. On Windows the Win32 API function `TerminateProcess()` is called to stop the child. `Popen.kill()` Kills the child. On POSIX OSs the function sends SIGKILL to the child. On Windows [`kill()`](#subprocess.Popen.kill "subprocess.Popen.kill") is an alias for [`terminate()`](#subprocess.Popen.terminate "subprocess.Popen.terminate"). The following attributes are also available: `Popen.args` The *args* argument as it was passed to [`Popen`](#subprocess.Popen "subprocess.Popen") – a sequence of program arguments or else a single string. New in version 3.3. `Popen.stdin` If the *stdin* argument was [`PIPE`](#subprocess.PIPE "subprocess.PIPE"), this attribute is a writeable stream object as returned by [`open()`](functions#open "open"). If the *encoding* or *errors* arguments were specified or the *universal\_newlines* argument was `True`, the stream is a text stream, otherwise it is a byte stream. If the *stdin* argument was not [`PIPE`](#subprocess.PIPE "subprocess.PIPE"), this attribute is `None`. `Popen.stdout` If the *stdout* argument was [`PIPE`](#subprocess.PIPE "subprocess.PIPE"), this attribute is a readable stream object as returned by [`open()`](functions#open "open"). Reading from the stream provides output from the child process. If the *encoding* or *errors* arguments were specified or the *universal\_newlines* argument was `True`, the stream is a text stream, otherwise it is a byte stream. If the *stdout* argument was not [`PIPE`](#subprocess.PIPE "subprocess.PIPE"), this attribute is `None`. `Popen.stderr` If the *stderr* argument was [`PIPE`](#subprocess.PIPE "subprocess.PIPE"), this attribute is a readable stream object as returned by [`open()`](functions#open "open"). Reading from the stream provides error output from the child process. If the *encoding* or *errors* arguments were specified or the *universal\_newlines* argument was `True`, the stream is a text stream, otherwise it is a byte stream. If the *stderr* argument was not [`PIPE`](#subprocess.PIPE "subprocess.PIPE"), this attribute is `None`. Warning Use [`communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate") rather than [`.stdin.write`](#subprocess.Popen.stdin "subprocess.Popen.stdin"), [`.stdout.read`](#subprocess.Popen.stdout "subprocess.Popen.stdout") or [`.stderr.read`](#subprocess.Popen.stderr "subprocess.Popen.stderr") to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process. `Popen.pid` The process ID of the child process. Note that if you set the *shell* argument to `True`, this is the process ID of the spawned shell. `Popen.returncode` The child return code, set by [`poll()`](#subprocess.Popen.poll "subprocess.Popen.poll") and [`wait()`](#subprocess.Popen.wait "subprocess.Popen.wait") (and indirectly by [`communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate")). A `None` value indicates that the process hasn’t terminated yet. A negative value `-N` indicates that the child was terminated by signal `N` (POSIX only). Windows Popen Helpers --------------------- The [`STARTUPINFO`](#subprocess.STARTUPINFO "subprocess.STARTUPINFO") class and following constants are only available on Windows. `class subprocess.STARTUPINFO(*, dwFlags=0, hStdInput=None, hStdOutput=None, hStdError=None, wShowWindow=0, lpAttributeList=None)` Partial support of the Windows [STARTUPINFO](https://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx) structure is used for [`Popen`](#subprocess.Popen "subprocess.Popen") creation. The following attributes can be set by passing them as keyword-only arguments. Changed in version 3.7: Keyword-only argument support was added. `dwFlags` A bit field that determines whether certain [`STARTUPINFO`](#subprocess.STARTUPINFO "subprocess.STARTUPINFO") attributes are used when the process creates a window. ``` si = subprocess.STARTUPINFO() si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW ``` `hStdInput` If [`dwFlags`](#subprocess.STARTUPINFO.dwFlags "subprocess.STARTUPINFO.dwFlags") specifies [`STARTF_USESTDHANDLES`](#subprocess.STARTF_USESTDHANDLES "subprocess.STARTF_USESTDHANDLES"), this attribute is the standard input handle for the process. If [`STARTF_USESTDHANDLES`](#subprocess.STARTF_USESTDHANDLES "subprocess.STARTF_USESTDHANDLES") is not specified, the default for standard input is the keyboard buffer. `hStdOutput` If [`dwFlags`](#subprocess.STARTUPINFO.dwFlags "subprocess.STARTUPINFO.dwFlags") specifies [`STARTF_USESTDHANDLES`](#subprocess.STARTF_USESTDHANDLES "subprocess.STARTF_USESTDHANDLES"), this attribute is the standard output handle for the process. Otherwise, this attribute is ignored and the default for standard output is the console window’s buffer. `hStdError` If [`dwFlags`](#subprocess.STARTUPINFO.dwFlags "subprocess.STARTUPINFO.dwFlags") specifies [`STARTF_USESTDHANDLES`](#subprocess.STARTF_USESTDHANDLES "subprocess.STARTF_USESTDHANDLES"), this attribute is the standard error handle for the process. Otherwise, this attribute is ignored and the default for standard error is the console window’s buffer. `wShowWindow` If [`dwFlags`](#subprocess.STARTUPINFO.dwFlags "subprocess.STARTUPINFO.dwFlags") specifies [`STARTF_USESHOWWINDOW`](#subprocess.STARTF_USESHOWWINDOW "subprocess.STARTF_USESHOWWINDOW"), this attribute can be any of the values that can be specified in the `nCmdShow` parameter for the [ShowWindow](https://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx) function, except for `SW_SHOWDEFAULT`. Otherwise, this attribute is ignored. [`SW_HIDE`](#subprocess.SW_HIDE "subprocess.SW_HIDE") is provided for this attribute. It is used when [`Popen`](#subprocess.Popen "subprocess.Popen") is called with `shell=True`. `lpAttributeList` A dictionary of additional attributes for process creation as given in `STARTUPINFOEX`, see [UpdateProcThreadAttribute](https://msdn.microsoft.com/en-us/library/windows/desktop/ms686880(v=vs.85).aspx). Supported attributes: **handle\_list** Sequence of handles that will be inherited. *close\_fds* must be true if non-empty. The handles must be temporarily made inheritable by [`os.set_handle_inheritable()`](os#os.set_handle_inheritable "os.set_handle_inheritable") when passed to the [`Popen`](#subprocess.Popen "subprocess.Popen") constructor, else [`OSError`](exceptions#OSError "OSError") will be raised with Windows error `ERROR_INVALID_PARAMETER` (87). Warning In a multithreaded process, use caution to avoid leaking handles that are marked inheritable when combining this feature with concurrent calls to other process creation functions that inherit all handles such as [`os.system()`](os#os.system "os.system"). This also applies to standard handle redirection, which temporarily creates inheritable handles. New in version 3.7. ### Windows Constants The [`subprocess`](#module-subprocess "subprocess: Subprocess management.") module exposes the following constants. `subprocess.STD_INPUT_HANDLE` The standard input device. Initially, this is the console input buffer, `CONIN$`. `subprocess.STD_OUTPUT_HANDLE` The standard output device. Initially, this is the active console screen buffer, `CONOUT$`. `subprocess.STD_ERROR_HANDLE` The standard error device. Initially, this is the active console screen buffer, `CONOUT$`. `subprocess.SW_HIDE` Hides the window. Another window will be activated. `subprocess.STARTF_USESTDHANDLES` Specifies that the [`STARTUPINFO.hStdInput`](#subprocess.STARTUPINFO.hStdInput "subprocess.STARTUPINFO.hStdInput"), [`STARTUPINFO.hStdOutput`](#subprocess.STARTUPINFO.hStdOutput "subprocess.STARTUPINFO.hStdOutput"), and [`STARTUPINFO.hStdError`](#subprocess.STARTUPINFO.hStdError "subprocess.STARTUPINFO.hStdError") attributes contain additional information. `subprocess.STARTF_USESHOWWINDOW` Specifies that the [`STARTUPINFO.wShowWindow`](#subprocess.STARTUPINFO.wShowWindow "subprocess.STARTUPINFO.wShowWindow") attribute contains additional information. `subprocess.CREATE_NEW_CONSOLE` The new process has a new console, instead of inheriting its parent’s console (the default). `subprocess.CREATE_NEW_PROCESS_GROUP` A [`Popen`](#subprocess.Popen "subprocess.Popen") `creationflags` parameter to specify that a new process group will be created. This flag is necessary for using [`os.kill()`](os#os.kill "os.kill") on the subprocess. This flag is ignored if [`CREATE_NEW_CONSOLE`](#subprocess.CREATE_NEW_CONSOLE "subprocess.CREATE_NEW_CONSOLE") is specified. `subprocess.ABOVE_NORMAL_PRIORITY_CLASS` A [`Popen`](#subprocess.Popen "subprocess.Popen") `creationflags` parameter to specify that a new process will have an above average priority. New in version 3.7. `subprocess.BELOW_NORMAL_PRIORITY_CLASS` A [`Popen`](#subprocess.Popen "subprocess.Popen") `creationflags` parameter to specify that a new process will have a below average priority. New in version 3.7. `subprocess.HIGH_PRIORITY_CLASS` A [`Popen`](#subprocess.Popen "subprocess.Popen") `creationflags` parameter to specify that a new process will have a high priority. New in version 3.7. `subprocess.IDLE_PRIORITY_CLASS` A [`Popen`](#subprocess.Popen "subprocess.Popen") `creationflags` parameter to specify that a new process will have an idle (lowest) priority. New in version 3.7. `subprocess.NORMAL_PRIORITY_CLASS` A [`Popen`](#subprocess.Popen "subprocess.Popen") `creationflags` parameter to specify that a new process will have an normal priority. (default) New in version 3.7. `subprocess.REALTIME_PRIORITY_CLASS` A [`Popen`](#subprocess.Popen "subprocess.Popen") `creationflags` parameter to specify that a new process will have realtime priority. You should almost never use REALTIME\_PRIORITY\_CLASS, because this interrupts system threads that manage mouse input, keyboard input, and background disk flushing. This class can be appropriate for applications that “talk” directly to hardware or that perform brief tasks that should have limited interruptions. New in version 3.7. `subprocess.CREATE_NO_WINDOW` A [`Popen`](#subprocess.Popen "subprocess.Popen") `creationflags` parameter to specify that a new process will not create a window. New in version 3.7. `subprocess.DETACHED_PROCESS` A [`Popen`](#subprocess.Popen "subprocess.Popen") `creationflags` parameter to specify that a new process will not inherit its parent’s console. This value cannot be used with CREATE\_NEW\_CONSOLE. New in version 3.7. `subprocess.CREATE_DEFAULT_ERROR_MODE` A [`Popen`](#subprocess.Popen "subprocess.Popen") `creationflags` parameter to specify that a new process does not inherit the error mode of the calling process. Instead, the new process gets the default error mode. This feature is particularly useful for multithreaded shell applications that run with hard errors disabled. New in version 3.7. `subprocess.CREATE_BREAKAWAY_FROM_JOB` A [`Popen`](#subprocess.Popen "subprocess.Popen") `creationflags` parameter to specify that a new process is not associated with the job. New in version 3.7. Older high-level API -------------------- Prior to Python 3.5, these three functions comprised the high level API to subprocess. You can now use [`run()`](#subprocess.run "subprocess.run") in many cases, but lots of existing code calls these functions. `subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs)` Run the command described by *args*. Wait for command to complete, then return the [`returncode`](#subprocess.Popen.returncode "subprocess.Popen.returncode") attribute. Code needing to capture stdout or stderr should use [`run()`](#subprocess.run "subprocess.run") instead: ``` run(...).returncode ``` To suppress stdout or stderr, supply a value of [`DEVNULL`](#subprocess.DEVNULL "subprocess.DEVNULL"). The arguments shown above are merely some common ones. The full function signature is the same as that of the [`Popen`](#subprocess.Popen "subprocess.Popen") constructor - this function passes all supplied arguments other than *timeout* directly through to that interface. Note Do not use `stdout=PIPE` or `stderr=PIPE` with this function. The child process will block if it generates enough output to a pipe to fill up the OS pipe buffer as the pipes are not being read from. Changed in version 3.3: *timeout* was added. `subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs)` Run command with arguments. Wait for command to complete. If the return code was zero then return, otherwise raise [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError"). The [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError") object will have the return code in the [`returncode`](#subprocess.CalledProcessError.returncode "subprocess.CalledProcessError.returncode") attribute. If [`check_call()`](#subprocess.check_call "subprocess.check_call") was unable to start the process it will propagate the exception that was raised. Code needing to capture stdout or stderr should use [`run()`](#subprocess.run "subprocess.run") instead: ``` run(..., check=True) ``` To suppress stdout or stderr, supply a value of [`DEVNULL`](#subprocess.DEVNULL "subprocess.DEVNULL"). The arguments shown above are merely some common ones. The full function signature is the same as that of the [`Popen`](#subprocess.Popen "subprocess.Popen") constructor - this function passes all supplied arguments other than *timeout* directly through to that interface. Note Do not use `stdout=PIPE` or `stderr=PIPE` with this function. The child process will block if it generates enough output to a pipe to fill up the OS pipe buffer as the pipes are not being read from. Changed in version 3.3: *timeout* was added. `subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, cwd=None, encoding=None, errors=None, universal_newlines=None, timeout=None, text=None, **other_popen_kwargs)` Run command with arguments and return its output. If the return code was non-zero it raises a [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError"). The [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError") object will have the return code in the [`returncode`](#subprocess.CalledProcessError.returncode "subprocess.CalledProcessError.returncode") attribute and any output in the [`output`](#subprocess.CalledProcessError.output "subprocess.CalledProcessError.output") attribute. This is equivalent to: ``` run(..., check=True, stdout=PIPE).stdout ``` The arguments shown above are merely some common ones. The full function signature is largely the same as that of [`run()`](#subprocess.run "subprocess.run") - most arguments are passed directly through to that interface. One API deviation from [`run()`](#subprocess.run "subprocess.run") behavior exists: passing `input=None` will behave the same as `input=b''` (or `input=''`, depending on other arguments) rather than using the parent’s standard input file handle. By default, this function will return the data as encoded bytes. The actual encoding of the output data may depend on the command being invoked, so the decoding to text will often need to be handled at the application level. This behaviour may be overridden by setting *text*, *encoding*, *errors*, or *universal\_newlines* to `True` as described in [Frequently Used Arguments](#frequently-used-arguments) and [`run()`](#subprocess.run "subprocess.run"). To also capture standard error in the result, use `stderr=subprocess.STDOUT`: ``` >>> subprocess.check_output( ... "ls non_existent_file; exit 0", ... stderr=subprocess.STDOUT, ... shell=True) 'ls: non_existent_file: No such file or directory\n' ``` New in version 3.1. Changed in version 3.3: *timeout* was added. Changed in version 3.4: Support for the *input* keyword argument was added. Changed in version 3.6: *encoding* and *errors* were added. See [`run()`](#subprocess.run "subprocess.run") for details. New in version 3.7: *text* was added as a more readable alias for *universal\_newlines*. Replacing Older Functions with the subprocess Module ---------------------------------------------------- In this section, “a becomes b” means that b can be used as a replacement for a. Note All “a” functions in this section fail (more or less) silently if the executed program cannot be found; the “b” replacements raise [`OSError`](exceptions#OSError "OSError") instead. In addition, the replacements using [`check_output()`](#subprocess.check_output "subprocess.check_output") will fail with a [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError") if the requested operation produces a non-zero return code. The output is still available as the [`output`](#subprocess.CalledProcessError.output "subprocess.CalledProcessError.output") attribute of the raised exception. In the following examples, we assume that the relevant functions have already been imported from the [`subprocess`](#module-subprocess "subprocess: Subprocess management.") module. ### Replacing **/bin/sh** shell command substitution ``` output=$(mycmd myarg) ``` becomes: ``` output = check_output(["mycmd", "myarg"]) ``` ### Replacing shell pipeline ``` output=$(dmesg | grep hda) ``` becomes: ``` p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. output = p2.communicate()[0] ``` The `p1.stdout.close()` call after starting the p2 is important in order for p1 to receive a SIGPIPE if p2 exits before p1. Alternatively, for trusted input, the shell’s own pipeline support may still be used directly: ``` output=$(dmesg | grep hda) ``` becomes: ``` output=check_output("dmesg | grep hda", shell=True) ``` ### Replacing [`os.system()`](os#os.system "os.system") ``` sts = os.system("mycmd" + " myarg") # becomes retcode = call("mycmd" + " myarg", shell=True) ``` Notes: * Calling the program through the shell is usually not required. * The [`call()`](#subprocess.call "subprocess.call") return value is encoded differently to that of [`os.system()`](os#os.system "os.system"). * The [`os.system()`](os#os.system "os.system") function ignores SIGINT and SIGQUIT signals while the command is running, but the caller must do this separately when using the [`subprocess`](#module-subprocess "subprocess: Subprocess management.") module. A more realistic example would look like this: ``` try: retcode = call("mycmd" + " myarg", shell=True) if retcode < 0: print("Child was terminated by signal", -retcode, file=sys.stderr) else: print("Child returned", retcode, file=sys.stderr) except OSError as e: print("Execution failed:", e, file=sys.stderr) ``` ### Replacing the [`os.spawn`](os#os.spawnl "os.spawnl") family P\_NOWAIT example: ``` pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") ==> pid = Popen(["/bin/mycmd", "myarg"]).pid ``` P\_WAIT example: ``` retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg") ==> retcode = call(["/bin/mycmd", "myarg"]) ``` Vector example: ``` os.spawnvp(os.P_NOWAIT, path, args) ==> Popen([path] + args[1:]) ``` Environment example: ``` os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) ==> Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) ``` ### Replacing [`os.popen()`](os#os.popen "os.popen"), `os.popen2()`, `os.popen3()` ``` (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdin, child_stdout) = (p.stdin, p.stdout) ``` ``` (child_stdin, child_stdout, child_stderr) = os.popen3(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) (child_stdin, child_stdout, child_stderr) = (p.stdin, p.stdout, p.stderr) ``` ``` (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout) ``` Return code handling translates as follows: ``` pipe = os.popen(cmd, 'w') ... rc = pipe.close() if rc is not None and rc >> 8: print("There were some errors") ==> process = Popen(cmd, stdin=PIPE) ... process.stdin.close() if process.wait() != 0: print("There were some errors") ``` ### Replacing functions from the `popen2` module Note If the cmd argument to popen2 functions is a string, the command is executed through /bin/sh. If it is a list, the command is directly executed. ``` (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode) ==> p = Popen("somestring", shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdout, child_stdin) = (p.stdout, p.stdin) ``` ``` (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode) ==> p = Popen(["mycmd", "myarg"], bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdout, child_stdin) = (p.stdout, p.stdin) ``` `popen2.Popen3` and `popen2.Popen4` basically work as [`subprocess.Popen`](#subprocess.Popen "subprocess.Popen"), except that: * [`Popen`](#subprocess.Popen "subprocess.Popen") raises an exception if the execution fails. * The *capturestderr* argument is replaced with the *stderr* argument. * `stdin=PIPE` and `stdout=PIPE` must be specified. * popen2 closes all file descriptors by default, but you have to specify `close_fds=True` with [`Popen`](#subprocess.Popen "subprocess.Popen") to guarantee this behavior on all platforms or past Python versions. Legacy Shell Invocation Functions --------------------------------- This module also provides the following legacy functions from the 2.x `commands` module. These operations implicitly invoke the system shell and none of the guarantees described above regarding security and exception handling consistency are valid for these functions. `subprocess.getstatusoutput(cmd)` Return `(exitcode, output)` of executing *cmd* in a shell. Execute the string *cmd* in a shell with `Popen.check_output()` and return a 2-tuple `(exitcode, output)`. The locale encoding is used; see the notes on [Frequently Used Arguments](#frequently-used-arguments) for more details. A trailing newline is stripped from the output. The exit code for the command can be interpreted as the return code of subprocess. Example: ``` >>> subprocess.getstatusoutput('ls /bin/ls') (0, '/bin/ls') >>> subprocess.getstatusoutput('cat /bin/junk') (1, 'cat: /bin/junk: No such file or directory') >>> subprocess.getstatusoutput('/bin/junk') (127, 'sh: /bin/junk: not found') >>> subprocess.getstatusoutput('/bin/kill $$') (-15, '') ``` [Availability](https://docs.python.org/3.9/library/intro.html#availability): POSIX & Windows. Changed in version 3.3.4: Windows support was added. The function now returns (exitcode, output) instead of (status, output) as it did in Python 3.3.3 and earlier. exitcode has the same value as [`returncode`](#subprocess.Popen.returncode "subprocess.Popen.returncode"). `subprocess.getoutput(cmd)` Return output (stdout and stderr) of executing *cmd* in a shell. Like [`getstatusoutput()`](#subprocess.getstatusoutput "subprocess.getstatusoutput"), except the exit code is ignored and the return value is a string containing the command’s output. Example: ``` >>> subprocess.getoutput('ls /bin/ls') '/bin/ls' ``` [Availability](https://docs.python.org/3.9/library/intro.html#availability): POSIX & Windows. Changed in version 3.3.4: Windows support added Notes ----- ### Converting an argument sequence to a string on Windows On Windows, an *args* sequence is converted to a string that can be parsed using the following rules (which correspond to the rules used by the MS C runtime): 1. Arguments are delimited by white space, which is either a space or a tab. 2. A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument. 3. A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark. 4. Backslashes are interpreted literally, unless they immediately precede a double quotation mark. 5. If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as described in rule 3. See also [`shlex`](shlex#module-shlex "shlex: Simple lexical analysis for Unix shell-like languages.") Module which provides function to parse and escape command lines.
programming_docs
python timeit — Measure execution time of small code snippets timeit — Measure execution time of small code snippets ====================================================== **Source code:** [Lib/timeit.py](https://github.com/python/cpython/tree/3.9/Lib/timeit.py) This module provides a simple way to time small bits of Python code. It has both a [Command-Line Interface](#timeit-command-line-interface) as well as a [callable](#python-interface) one. It avoids a number of common traps for measuring execution times. See also Tim Peters’ introduction to the “Algorithms” chapter in the second edition of *Python Cookbook*, published by O’Reilly. Basic Examples -------------- The following example shows how the [Command-Line Interface](#timeit-command-line-interface) can be used to compare three different expressions: ``` $ python3 -m timeit '"-".join(str(n) for n in range(100))' 10000 loops, best of 5: 30.2 usec per loop $ python3 -m timeit '"-".join([str(n) for n in range(100)])' 10000 loops, best of 5: 27.5 usec per loop $ python3 -m timeit '"-".join(map(str, range(100)))' 10000 loops, best of 5: 23.2 usec per loop ``` This can be achieved from the [Python Interface](#python-interface) with: ``` >>> import timeit >>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000) 0.3018611848820001 >>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000) 0.2727368790656328 >>> timeit.timeit('"-".join(map(str, range(100)))', number=10000) 0.23702679807320237 ``` A callable can also be passed from the [Python Interface](#python-interface): ``` >>> timeit.timeit(lambda: "-".join(map(str, range(100))), number=10000) 0.19665591977536678 ``` Note however that [`timeit()`](#timeit.timeit "timeit.timeit") will automatically determine the number of repetitions only when the command-line interface is used. In the [Examples](#timeit-examples) section you can find more advanced examples. Python Interface ---------------- The module defines three convenience functions and a public class: `timeit.timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000, globals=None)` Create a [`Timer`](#timeit.Timer "timeit.Timer") instance with the given statement, *setup* code and *timer* function and run its [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit") method with *number* executions. The optional *globals* argument specifies a namespace in which to execute the code. Changed in version 3.5: The optional *globals* parameter was added. `timeit.repeat(stmt='pass', setup='pass', timer=<default timer>, repeat=5, number=1000000, globals=None)` Create a [`Timer`](#timeit.Timer "timeit.Timer") instance with the given statement, *setup* code and *timer* function and run its [`repeat()`](#timeit.Timer.repeat "timeit.Timer.repeat") method with the given *repeat* count and *number* executions. The optional *globals* argument specifies a namespace in which to execute the code. Changed in version 3.5: The optional *globals* parameter was added. Changed in version 3.7: Default value of *repeat* changed from 3 to 5. `timeit.default_timer()` The default timer, which is always [`time.perf_counter()`](time#time.perf_counter "time.perf_counter"). Changed in version 3.3: [`time.perf_counter()`](time#time.perf_counter "time.perf_counter") is now the default timer. `class timeit.Timer(stmt='pass', setup='pass', timer=<timer function>, globals=None)` Class for timing execution speed of small code snippets. The constructor takes a statement to be timed, an additional statement used for setup, and a timer function. Both statements default to `'pass'`; the timer function is platform-dependent (see the module doc string). *stmt* and *setup* may also contain multiple statements separated by `;` or newlines, as long as they don’t contain multi-line string literals. The statement will by default be executed within timeit’s namespace; this behavior can be controlled by passing a namespace to *globals*. To measure the execution time of the first statement, use the [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit") method. The [`repeat()`](#timeit.Timer.repeat "timeit.Timer.repeat") and [`autorange()`](#timeit.Timer.autorange "timeit.Timer.autorange") methods are convenience methods to call [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit") multiple times. The execution time of *setup* is excluded from the overall timed execution run. The *stmt* and *setup* parameters can also take objects that are callable without arguments. This will embed calls to them in a timer function that will then be executed by [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit"). Note that the timing overhead is a little larger in this case because of the extra function calls. Changed in version 3.5: The optional *globals* parameter was added. `timeit(number=1000000)` Time *number* executions of the main statement. This executes the setup statement once, and then returns the time it takes to execute the main statement a number of times, measured in seconds as a float. The argument is the number of times through the loop, defaulting to one million. The main statement, the setup statement and the timer function to be used are passed to the constructor. Note By default, [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit") temporarily turns off [garbage collection](../glossary#term-garbage-collection) during the timing. The advantage of this approach is that it makes independent timings more comparable. The disadvantage is that GC may be an important component of the performance of the function being measured. If so, GC can be re-enabled as the first statement in the *setup* string. For example: ``` timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit() ``` `autorange(callback=None)` Automatically determine how many times to call [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit"). This is a convenience function that calls [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit") repeatedly so that the total time >= 0.2 second, returning the eventual (number of loops, time taken for that number of loops). It calls [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit") with increasing numbers from the sequence 1, 2, 5, 10, 20, 50, … until the time taken is at least 0.2 second. If *callback* is given and is not `None`, it will be called after each trial with two arguments: `callback(number, time_taken)`. New in version 3.6. `repeat(repeat=5, number=1000000)` Call [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit") a few times. This is a convenience function that calls the [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit") repeatedly, returning a list of results. The first argument specifies how many times to call [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit"). The second argument specifies the *number* argument for [`timeit()`](#timeit.Timer.timeit "timeit.Timer.timeit"). Note It’s tempting to calculate mean and standard deviation from the result vector and report these. However, this is not very useful. In a typical case, the lowest value gives a lower bound for how fast your machine can run the given code snippet; higher values in the result vector are typically not caused by variability in Python’s speed, but by other processes interfering with your timing accuracy. So the [`min()`](functions#min "min") of the result is probably the only number you should be interested in. After that, you should look at the entire vector and apply common sense rather than statistics. Changed in version 3.7: Default value of *repeat* changed from 3 to 5. `print_exc(file=None)` Helper to print a traceback from the timed code. Typical use: ``` t = Timer(...) # outside the try/except try: t.timeit(...) # or t.repeat(...) except Exception: t.print_exc() ``` The advantage over the standard traceback is that source lines in the compiled template will be displayed. The optional *file* argument directs where the traceback is sent; it defaults to [`sys.stderr`](sys#sys.stderr "sys.stderr"). Command-Line Interface ---------------------- When called as a program from the command line, the following form is used: ``` python -m timeit [-n N] [-r N] [-u U] [-s S] [-h] [statement ...] ``` Where the following options are understood: `-n N, --number=N` how many times to execute ‘statement’ `-r N, --repeat=N` how many times to repeat the timer (default 5) `-s S, --setup=S` statement to be executed once initially (default `pass`) `-p, --process` measure process time, not wallclock time, using [`time.process_time()`](time#time.process_time "time.process_time") instead of [`time.perf_counter()`](time#time.perf_counter "time.perf_counter"), which is the default New in version 3.3. `-u, --unit=U` specify a time unit for timer output; can select nsec, usec, msec, or sec New in version 3.5. `-v, --verbose` print raw timing results; repeat for more digits precision `-h, --help` print a short usage message and exit A multi-line statement may be given by specifying each line as a separate statement argument; indented lines are possible by enclosing an argument in quotes and using leading spaces. Multiple [`-s`](#cmdoption-timeit-s) options are treated similarly. If [`-n`](#cmdoption-timeit-n) is not given, a suitable number of loops is calculated by trying increasing numbers from the sequence 1, 2, 5, 10, 20, 50, … until the total time is at least 0.2 seconds. [`default_timer()`](#timeit.default_timer "timeit.default_timer") measurements can be affected by other programs running on the same machine, so the best thing to do when accurate timing is necessary is to repeat the timing a few times and use the best time. The [`-r`](#cmdoption-timeit-r) option is good for this; the default of 5 repetitions is probably enough in most cases. You can use [`time.process_time()`](time#time.process_time "time.process_time") to measure CPU time. Note There is a certain baseline overhead associated with executing a pass statement. The code here doesn’t try to hide it, but you should be aware of it. The baseline overhead can be measured by invoking the program without arguments, and it might differ between Python versions. Examples -------- It is possible to provide a setup statement that is executed only once at the beginning: ``` $ python -m timeit -s 'text = "sample string"; char = "g"' 'char in text' 5000000 loops, best of 5: 0.0877 usec per loop $ python -m timeit -s 'text = "sample string"; char = "g"' 'text.find(char)' 1000000 loops, best of 5: 0.342 usec per loop ``` In the output, there are three fields. The loop count, which tells you how many times the statement body was run per timing loop repetition. The repetition count (‘best of 5’) which tells you how many times the timing loop was repeated, and finally the time the statement body took on average within the best repetition of the timing loop. That is, the time the fastest repetition took divided by the loop count. ``` >>> import timeit >>> timeit.timeit('char in text', setup='text = "sample string"; char = "g"') 0.41440500499993504 >>> timeit.timeit('text.find(char)', setup='text = "sample string"; char = "g"') 1.7246671520006203 ``` The same can be done using the [`Timer`](#timeit.Timer "timeit.Timer") class and its methods: ``` >>> import timeit >>> t = timeit.Timer('char in text', setup='text = "sample string"; char = "g"') >>> t.timeit() 0.3955516149999312 >>> t.repeat() [0.40183617287970225, 0.37027556854118704, 0.38344867356679524, 0.3712595970846668, 0.37866875250654886] ``` The following examples show how to time expressions that contain multiple lines. Here we compare the cost of using [`hasattr()`](functions#hasattr "hasattr") vs. [`try`](../reference/compound_stmts#try)/[`except`](../reference/compound_stmts#except) to test for missing and present object attributes: ``` $ python -m timeit 'try:' ' str.__bool__' 'except AttributeError:' ' pass' 20000 loops, best of 5: 15.7 usec per loop $ python -m timeit 'if hasattr(str, "__bool__"): pass' 50000 loops, best of 5: 4.26 usec per loop $ python -m timeit 'try:' ' int.__bool__' 'except AttributeError:' ' pass' 200000 loops, best of 5: 1.43 usec per loop $ python -m timeit 'if hasattr(int, "__bool__"): pass' 100000 loops, best of 5: 2.23 usec per loop ``` ``` >>> import timeit >>> # attribute is missing >>> s = """\ ... try: ... str.__bool__ ... except AttributeError: ... pass ... """ >>> timeit.timeit(stmt=s, number=100000) 0.9138244460009446 >>> s = "if hasattr(str, '__bool__'): pass" >>> timeit.timeit(stmt=s, number=100000) 0.5829014980008651 >>> >>> # attribute is present >>> s = """\ ... try: ... int.__bool__ ... except AttributeError: ... pass ... """ >>> timeit.timeit(stmt=s, number=100000) 0.04215312199994514 >>> s = "if hasattr(int, '__bool__'): pass" >>> timeit.timeit(stmt=s, number=100000) 0.08588060699912603 ``` To give the [`timeit`](#module-timeit "timeit: Measure the execution time of small code snippets.") module access to functions you define, you can pass a *setup* parameter which contains an import statement: ``` def test(): """Stupid test function""" L = [i for i in range(100)] if __name__ == '__main__': import timeit print(timeit.timeit("test()", setup="from __main__ import test")) ``` Another option is to pass [`globals()`](functions#globals "globals") to the *globals* parameter, which will cause the code to be executed within your current global namespace. This can be more convenient than individually specifying imports: ``` def f(x): return x**2 def g(x): return x**4 def h(x): return x**8 import timeit print(timeit.timeit('[func(42) for func in (f,g,h)]', globals=globals())) ``` python logging — Logging facility for Python logging — Logging facility for Python ===================================== **Source code:** [Lib/logging/\_\_init\_\_.py](https://github.com/python/cpython/tree/3.9/Lib/logging/__init__.py) This module defines functions and classes which implement a flexible event logging system for applications and libraries. The key benefit of having the logging API provided by a standard library module is that all Python modules can participate in logging, so your application log can include your own messages integrated with messages from third-party modules. The module provides a lot of functionality and flexibility. If you are unfamiliar with logging, the best way to get to grips with it is to see the tutorials (see the links on the right). The basic classes defined by the module, together with their functions, are listed below. * Loggers expose the interface that application code directly uses. * Handlers send the log records (created by loggers) to the appropriate destination. * Filters provide a finer grained facility for determining which log records to output. * Formatters specify the layout of log records in the final output. Logger Objects -------------- Loggers have the following attributes and methods. Note that Loggers should *NEVER* be instantiated directly, but always through the module-level function `logging.getLogger(name)`. Multiple calls to [`getLogger()`](#logging.getLogger "logging.getLogger") with the same name will always return a reference to the same Logger object. The `name` is potentially a period-separated hierarchical value, like `foo.bar.baz` (though it could also be just plain `foo`, for example). Loggers that are further down in the hierarchical list are children of loggers higher up in the list. For example, given a logger with a name of `foo`, loggers with names of `foo.bar`, `foo.bar.baz`, and `foo.bam` are all descendants of `foo`. The logger name hierarchy is analogous to the Python package hierarchy, and identical to it if you organise your loggers on a per-module basis using the recommended construction `logging.getLogger(__name__)`. That’s because in a module, `__name__` is the module’s name in the Python package namespace. `class logging.Logger` `propagate` If this attribute evaluates to true, events logged to this logger will be passed to the handlers of higher level (ancestor) loggers, in addition to any handlers attached to this logger. Messages are passed directly to the ancestor loggers’ handlers - neither the level nor filters of the ancestor loggers in question are considered. If this evaluates to false, logging messages are not passed to the handlers of ancestor loggers. Spelling it out with an example: If the propagate attribute of the logger named `A.B.C` evaluates to true, any event logged to `A.B.C` via a method call such as `logging.getLogger('A.B.C').error(...)` will [subject to passing that logger’s level and filter settings] be passed in turn to any handlers attached to loggers named `A.B`, `A` and the root logger, after first being passed to any handlers attached to `A.B.C`. If any logger in the chain `A.B.C`, `A.B`, `A` has its `propagate` attribute set to false, then that is the last logger whose handlers are offered the event to handle, and propagation stops at that point. The constructor sets this attribute to `True`. Note If you attach a handler to a logger *and* one or more of its ancestors, it may emit the same record multiple times. In general, you should not need to attach a handler to more than one logger - if you just attach it to the appropriate logger which is highest in the logger hierarchy, then it will see all events logged by all descendant loggers, provided that their propagate setting is left set to `True`. A common scenario is to attach handlers only to the root logger, and to let propagation take care of the rest. `setLevel(level)` Sets the threshold for this logger to *level*. Logging messages which are less severe than *level* will be ignored; logging messages which have severity *level* or higher will be emitted by whichever handler or handlers service this logger, unless a handler’s level has been set to a higher severity level than *level*. When a logger is created, the level is set to `NOTSET` (which causes all messages to be processed when the logger is the root logger, or delegation to the parent when the logger is a non-root logger). Note that the root logger is created with level `WARNING`. The term ‘delegation to the parent’ means that if a logger has a level of NOTSET, its chain of ancestor loggers is traversed until either an ancestor with a level other than NOTSET is found, or the root is reached. If an ancestor is found with a level other than NOTSET, then that ancestor’s level is treated as the effective level of the logger where the ancestor search began, and is used to determine how a logging event is handled. If the root is reached, and it has a level of NOTSET, then all messages will be processed. Otherwise, the root’s level will be used as the effective level. See [Logging Levels](#levels) for a list of levels. Changed in version 3.2: The *level* parameter now accepts a string representation of the level such as ‘INFO’ as an alternative to the integer constants such as `INFO`. Note, however, that levels are internally stored as integers, and methods such as e.g. [`getEffectiveLevel()`](#logging.Logger.getEffectiveLevel "logging.Logger.getEffectiveLevel") and [`isEnabledFor()`](#logging.Logger.isEnabledFor "logging.Logger.isEnabledFor") will return/expect to be passed integers. `isEnabledFor(level)` Indicates if a message of severity *level* would be processed by this logger. This method checks first the module-level level set by `logging.disable(level)` and then the logger’s effective level as determined by [`getEffectiveLevel()`](#logging.Logger.getEffectiveLevel "logging.Logger.getEffectiveLevel"). `getEffectiveLevel()` Indicates the effective level for this logger. If a value other than `NOTSET` has been set using [`setLevel()`](#logging.Logger.setLevel "logging.Logger.setLevel"), it is returned. Otherwise, the hierarchy is traversed towards the root until a value other than `NOTSET` is found, and that value is returned. The value returned is an integer, typically one of `logging.DEBUG`, `logging.INFO` etc. `getChild(suffix)` Returns a logger which is a descendant to this logger, as determined by the suffix. Thus, `logging.getLogger('abc').getChild('def.ghi')` would return the same logger as would be returned by `logging.getLogger('abc.def.ghi')`. This is a convenience method, useful when the parent logger is named using e.g. `__name__` rather than a literal string. New in version 3.2. `debug(msg, *args, **kwargs)` Logs a message with level `DEBUG` on this logger. The *msg* is the message format string, and the *args* are the arguments which are merged into *msg* using the string formatting operator. (Note that this means that you can use keywords in the format string, together with a single dictionary argument.) No % formatting operation is performed on *msg* when no *args* are supplied. There are four keyword arguments in *kwargs* which are inspected: *exc\_info*, *stack\_info*, *stacklevel* and *extra*. If *exc\_info* does not evaluate as false, it causes exception information to be added to the logging message. If an exception tuple (in the format returned by [`sys.exc_info()`](sys#sys.exc_info "sys.exc_info")) or an exception instance is provided, it is used; otherwise, [`sys.exc_info()`](sys#sys.exc_info "sys.exc_info") is called to get the exception information. The second optional keyword argument is *stack\_info*, which defaults to `False`. If true, stack information is added to the logging message, including the actual logging call. Note that this is not the same stack information as that displayed through specifying *exc\_info*: The former is stack frames from the bottom of the stack up to the logging call in the current thread, whereas the latter is information about stack frames which have been unwound, following an exception, while searching for exception handlers. You can specify *stack\_info* independently of *exc\_info*, e.g. to just show how you got to a certain point in your code, even when no exceptions were raised. The stack frames are printed following a header line which says: ``` Stack (most recent call last): ``` This mimics the `Traceback (most recent call last):` which is used when displaying exception frames. The third optional keyword argument is *stacklevel*, which defaults to `1`. If greater than 1, the corresponding number of stack frames are skipped when computing the line number and function name set in the [`LogRecord`](#logging.LogRecord "logging.LogRecord") created for the logging event. This can be used in logging helpers so that the function name, filename and line number recorded are not the information for the helper function/method, but rather its caller. The name of this parameter mirrors the equivalent one in the [`warnings`](warnings#module-warnings "warnings: Issue warning messages and control their disposition.") module. The fourth keyword argument is *extra* which can be used to pass a dictionary which is used to populate the \_\_dict\_\_ of the [`LogRecord`](#logging.LogRecord "logging.LogRecord") created for the logging event with user-defined attributes. These custom attributes can then be used as you like. For example, they could be incorporated into logged messages. For example: ``` FORMAT = '%(asctime)s %(clientip)-15s %(user)-8s %(message)s' logging.basicConfig(format=FORMAT) d = {'clientip': '192.168.0.1', 'user': 'fbloggs'} logger = logging.getLogger('tcpserver') logger.warning('Protocol problem: %s', 'connection reset', extra=d) ``` would print something like ``` 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset ``` The keys in the dictionary passed in *extra* should not clash with the keys used by the logging system. (See the [`Formatter`](#logging.Formatter "logging.Formatter") documentation for more information on which keys are used by the logging system.) If you choose to use these attributes in logged messages, you need to exercise some care. In the above example, for instance, the [`Formatter`](#logging.Formatter "logging.Formatter") has been set up with a format string which expects ‘clientip’ and ‘user’ in the attribute dictionary of the [`LogRecord`](#logging.LogRecord "logging.LogRecord"). If these are missing, the message will not be logged because a string formatting exception will occur. So in this case, you always need to pass the *extra* dictionary with these keys. While this might be annoying, this feature is intended for use in specialized circumstances, such as multi-threaded servers where the same code executes in many contexts, and interesting conditions which arise are dependent on this context (such as remote client IP address and authenticated user name, in the above example). In such circumstances, it is likely that specialized [`Formatter`](#logging.Formatter "logging.Formatter")s would be used with particular [`Handler`](#logging.Handler "logging.Handler")s. Changed in version 3.2: The *stack\_info* parameter was added. Changed in version 3.5: The *exc\_info* parameter can now accept exception instances. Changed in version 3.8: The *stacklevel* parameter was added. `info(msg, *args, **kwargs)` Logs a message with level `INFO` on this logger. The arguments are interpreted as for [`debug()`](#logging.debug "logging.debug"). `warning(msg, *args, **kwargs)` Logs a message with level `WARNING` on this logger. The arguments are interpreted as for [`debug()`](#logging.debug "logging.debug"). Note There is an obsolete method `warn` which is functionally identical to `warning`. As `warn` is deprecated, please do not use it - use `warning` instead. `error(msg, *args, **kwargs)` Logs a message with level `ERROR` on this logger. The arguments are interpreted as for [`debug()`](#logging.debug "logging.debug"). `critical(msg, *args, **kwargs)` Logs a message with level `CRITICAL` on this logger. The arguments are interpreted as for [`debug()`](#logging.debug "logging.debug"). `log(level, msg, *args, **kwargs)` Logs a message with integer level *level* on this logger. The other arguments are interpreted as for [`debug()`](#logging.debug "logging.debug"). `exception(msg, *args, **kwargs)` Logs a message with level `ERROR` on this logger. The arguments are interpreted as for [`debug()`](#logging.debug "logging.debug"). Exception info is added to the logging message. This method should only be called from an exception handler. `addFilter(filter)` Adds the specified filter *filter* to this logger. `removeFilter(filter)` Removes the specified filter *filter* from this logger. `filter(record)` Apply this logger’s filters to the record and return `True` if the record is to be processed. The filters are consulted in turn, until one of them returns a false value. If none of them return a false value, the record will be processed (passed to handlers). If one returns a false value, no further processing of the record occurs. `addHandler(hdlr)` Adds the specified handler *hdlr* to this logger. `removeHandler(hdlr)` Removes the specified handler *hdlr* from this logger. `findCaller(stack_info=False, stacklevel=1)` Finds the caller’s source filename and line number. Returns the filename, line number, function name and stack information as a 4-element tuple. The stack information is returned as `None` unless *stack\_info* is `True`. The *stacklevel* parameter is passed from code calling the [`debug()`](#logging.debug "logging.debug") and other APIs. If greater than 1, the excess is used to skip stack frames before determining the values to be returned. This will generally be useful when calling logging APIs from helper/wrapper code, so that the information in the event log refers not to the helper/wrapper code, but to the code that calls it. `handle(record)` Handles a record by passing it to all handlers associated with this logger and its ancestors (until a false value of *propagate* is found). This method is used for unpickled records received from a socket, as well as those created locally. Logger-level filtering is applied using [`filter()`](#logging.Logger.filter "logging.Logger.filter"). `makeRecord(name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None)` This is a factory method which can be overridden in subclasses to create specialized [`LogRecord`](#logging.LogRecord "logging.LogRecord") instances. `hasHandlers()` Checks to see if this logger has any handlers configured. This is done by looking for handlers in this logger and its parents in the logger hierarchy. Returns `True` if a handler was found, else `False`. The method stops searching up the hierarchy whenever a logger with the ‘propagate’ attribute set to false is found - that will be the last logger which is checked for the existence of handlers. New in version 3.2. Changed in version 3.7: Loggers can now be pickled and unpickled. Logging Levels -------------- The numeric values of logging levels are given in the following table. These are primarily of interest if you want to define your own levels, and need them to have specific values relative to the predefined levels. If you define a level with the same numeric value, it overwrites the predefined value; the predefined name is lost. | Level | Numeric value | | --- | --- | | `CRITICAL` | 50 | | `ERROR` | 40 | | `WARNING` | 30 | | `INFO` | 20 | | `DEBUG` | 10 | | `NOTSET` | 0 | Handler Objects --------------- Handlers have the following attributes and methods. Note that [`Handler`](#logging.Handler "logging.Handler") is never instantiated directly; this class acts as a base for more useful subclasses. However, the [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") method in subclasses needs to call [`Handler.__init__()`](#logging.Handler.__init__ "logging.Handler.__init__"). `class logging.Handler` `__init__(level=NOTSET)` Initializes the [`Handler`](#logging.Handler "logging.Handler") instance by setting its level, setting the list of filters to the empty list and creating a lock (using [`createLock()`](#logging.Handler.createLock "logging.Handler.createLock")) for serializing access to an I/O mechanism. `createLock()` Initializes a thread lock which can be used to serialize access to underlying I/O functionality which may not be threadsafe. `acquire()` Acquires the thread lock created with [`createLock()`](#logging.Handler.createLock "logging.Handler.createLock"). `release()` Releases the thread lock acquired with [`acquire()`](#logging.Handler.acquire "logging.Handler.acquire"). `setLevel(level)` Sets the threshold for this handler to *level*. Logging messages which are less severe than *level* will be ignored. When a handler is created, the level is set to `NOTSET` (which causes all messages to be processed). See [Logging Levels](#levels) for a list of levels. Changed in version 3.2: The *level* parameter now accepts a string representation of the level such as ‘INFO’ as an alternative to the integer constants such as `INFO`. `setFormatter(fmt)` Sets the [`Formatter`](#logging.Formatter "logging.Formatter") for this handler to *fmt*. `addFilter(filter)` Adds the specified filter *filter* to this handler. `removeFilter(filter)` Removes the specified filter *filter* from this handler. `filter(record)` Apply this handler’s filters to the record and return `True` if the record is to be processed. The filters are consulted in turn, until one of them returns a false value. If none of them return a false value, the record will be emitted. If one returns a false value, the handler will not emit the record. `flush()` Ensure all logging output has been flushed. This version does nothing and is intended to be implemented by subclasses. `close()` Tidy up any resources used by the handler. This version does no output but removes the handler from an internal list of handlers which is closed when [`shutdown()`](#logging.shutdown "logging.shutdown") is called. Subclasses should ensure that this gets called from overridden [`close()`](#logging.Handler.close "logging.Handler.close") methods. `handle(record)` Conditionally emits the specified logging record, depending on filters which may have been added to the handler. Wraps the actual emission of the record with acquisition/release of the I/O thread lock. `handleError(record)` This method should be called from handlers when an exception is encountered during an [`emit()`](#logging.Handler.emit "logging.Handler.emit") call. If the module-level attribute `raiseExceptions` is `False`, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom handler if you wish. The specified record is the one which was being processed when the exception occurred. (The default value of `raiseExceptions` is `True`, as that is more useful during development). `format(record)` Do formatting for a record - if a formatter is set, use it. Otherwise, use the default formatter for the module. `emit(record)` Do whatever it takes to actually log the specified logging record. This version is intended to be implemented by subclasses and so raises a [`NotImplementedError`](exceptions#NotImplementedError "NotImplementedError"). For a list of handlers included as standard, see [`logging.handlers`](logging.handlers#module-logging.handlers "logging.handlers: Handlers for the logging module."). Formatter Objects ----------------- [`Formatter`](#logging.Formatter "logging.Formatter") objects have the following attributes and methods. They are responsible for converting a [`LogRecord`](#logging.LogRecord "logging.LogRecord") to (usually) a string which can be interpreted by either a human or an external system. The base [`Formatter`](#logging.Formatter "logging.Formatter") allows a formatting string to be specified. If none is supplied, the default value of `'%(message)s'` is used, which just includes the message in the logging call. To have additional items of information in the formatted output (such as a timestamp), keep reading. A Formatter can be initialized with a format string which makes use of knowledge of the [`LogRecord`](#logging.LogRecord "logging.LogRecord") attributes - such as the default value mentioned above making use of the fact that the user’s message and arguments are pre-formatted into a [`LogRecord`](#logging.LogRecord "logging.LogRecord")’s *message* attribute. This format string contains standard Python %-style mapping keys. See section [printf-style String Formatting](stdtypes#old-string-formatting) for more information on string formatting. The useful mapping keys in a [`LogRecord`](#logging.LogRecord "logging.LogRecord") are given in the section on [LogRecord attributes](#logrecord-attributes). `class logging.Formatter(fmt=None, datefmt=None, style='%', validate=True)` Returns a new instance of the [`Formatter`](#logging.Formatter "logging.Formatter") class. The instance is initialized with a format string for the message as a whole, as well as a format string for the date/time portion of a message. If no *fmt* is specified, `'%(message)s'` is used. If no *datefmt* is specified, a format is used which is described in the [`formatTime()`](#logging.Formatter.formatTime "logging.Formatter.formatTime") documentation. The *style* parameter can be one of ‘%’, ‘{’ or ‘$’ and determines how the format string will be merged with its data: using one of %-formatting, [`str.format()`](stdtypes#str.format "str.format") or [`string.Template`](string#string.Template "string.Template"). This only applies to the format string *fmt* (e.g. `'%(message)s'` or `{message}`), not to the actual log messages passed to `Logger.debug` etc; see [Using particular formatting styles throughout your application](../howto/logging-cookbook#formatting-styles) for more information on using {- and $-formatting for log messages. Changed in version 3.2: The *style* parameter was added. Changed in version 3.8: The *validate* parameter was added. Incorrect or mismatched style and fmt will raise a `ValueError`. For example: `logging.Formatter('%(asctime)s - %(message)s', style='{')`. `format(record)` The record’s attribute dictionary is used as the operand to a string formatting operation. Returns the resulting string. Before formatting the dictionary, a couple of preparatory steps are carried out. The *message* attribute of the record is computed using *msg* % *args*. If the formatting string contains `'(asctime)'`, [`formatTime()`](#logging.Formatter.formatTime "logging.Formatter.formatTime") is called to format the event time. If there is exception information, it is formatted using [`formatException()`](#logging.Formatter.formatException "logging.Formatter.formatException") and appended to the message. Note that the formatted exception information is cached in attribute *exc\_text*. This is useful because the exception information can be pickled and sent across the wire, but you should be careful if you have more than one [`Formatter`](#logging.Formatter "logging.Formatter") subclass which customizes the formatting of exception information. In this case, you will have to clear the cached value after a formatter has done its formatting, so that the next formatter to handle the event doesn’t use the cached value but recalculates it afresh. If stack information is available, it’s appended after the exception information, using [`formatStack()`](#logging.Formatter.formatStack "logging.Formatter.formatStack") to transform it if necessary. `formatTime(record, datefmt=None)` This method should be called from [`format()`](functions#format "format") by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behavior is as follows: if *datefmt* (a string) is specified, it is used with [`time.strftime()`](time#time.strftime "time.strftime") to format the creation time of the record. Otherwise, the format ‘%Y-%m-%d %H:%M:%S,uuu’ is used, where the uuu part is a millisecond value and the other letters are as per the [`time.strftime()`](time#time.strftime "time.strftime") documentation. An example time in this format is `2003-01-23 00:29:50,411`. The resulting string is returned. This function uses a user-configurable function to convert the creation time to a tuple. By default, [`time.localtime()`](time#time.localtime "time.localtime") is used; to change this for a particular formatter instance, set the `converter` attribute to a function with the same signature as [`time.localtime()`](time#time.localtime "time.localtime") or [`time.gmtime()`](time#time.gmtime "time.gmtime"). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the `converter` attribute in the `Formatter` class. Changed in version 3.3: Previously, the default format was hard-coded as in this example: `2010-09-06 22:38:15,292` where the part before the comma is handled by a strptime format string (`'%Y-%m-%d %H:%M:%S'`), and the part after the comma is a millisecond value. Because strptime does not have a format placeholder for milliseconds, the millisecond value is appended using another format string, `'%s,%03d'` — and both of these format strings have been hardcoded into this method. With the change, these strings are defined as class-level attributes which can be overridden at the instance level when desired. The names of the attributes are `default_time_format` (for the strptime format string) and `default_msec_format` (for appending the millisecond value). Changed in version 3.9: The `default_msec_format` can be `None`. `formatException(exc_info)` Formats the specified exception information (a standard exception tuple as returned by [`sys.exc_info()`](sys#sys.exc_info "sys.exc_info")) as a string. This default implementation just uses [`traceback.print_exception()`](traceback#traceback.print_exception "traceback.print_exception"). The resulting string is returned. `formatStack(stack_info)` Formats the specified stack information (a string as returned by [`traceback.print_stack()`](traceback#traceback.print_stack "traceback.print_stack"), but with the last newline removed) as a string. This default implementation just returns the input value. Filter Objects -------------- `Filters` can be used by `Handlers` and `Loggers` for more sophisticated filtering than is provided by levels. The base filter class only allows events which are below a certain point in the logger hierarchy. For example, a filter initialized with ‘A.B’ will allow events logged by loggers ‘A.B’, ‘A.B.C’, ‘A.B.C.D’, ‘A.B.D’ etc. but not ‘A.BB’, ‘B.A.B’ etc. If initialized with the empty string, all events are passed. `class logging.Filter(name='')` Returns an instance of the [`Filter`](#logging.Filter "logging.Filter") class. If *name* is specified, it names a logger which, together with its children, will have its events allowed through the filter. If *name* is the empty string, allows every event. `filter(record)` Is the specified record to be logged? Returns zero for no, nonzero for yes. If deemed appropriate, the record may be modified in-place by this method. Note that filters attached to handlers are consulted before an event is emitted by the handler, whereas filters attached to loggers are consulted whenever an event is logged (using [`debug()`](#logging.debug "logging.debug"), [`info()`](#logging.info "logging.info"), etc.), before sending an event to handlers. This means that events which have been generated by descendant loggers will not be filtered by a logger’s filter setting, unless the filter has also been applied to those descendant loggers. You don’t actually need to subclass `Filter`: you can pass any instance which has a `filter` method with the same semantics. Changed in version 3.2: You don’t need to create specialized `Filter` classes, or use other classes with a `filter` method: you can use a function (or other callable) as a filter. The filtering logic will check to see if the filter object has a `filter` attribute: if it does, it’s assumed to be a `Filter` and its [`filter()`](#logging.Filter.filter "logging.Filter.filter") method is called. Otherwise, it’s assumed to be a callable and called with the record as the single parameter. The returned value should conform to that returned by [`filter()`](#logging.Filter.filter "logging.Filter.filter"). Although filters are used primarily to filter records based on more sophisticated criteria than levels, they get to see every record which is processed by the handler or logger they’re attached to: this can be useful if you want to do things like counting how many records were processed by a particular logger or handler, or adding, changing or removing attributes in the [`LogRecord`](#logging.LogRecord "logging.LogRecord") being processed. Obviously changing the LogRecord needs to be done with some care, but it does allow the injection of contextual information into logs (see [Using Filters to impart contextual information](../howto/logging-cookbook#filters-contextual)). LogRecord Objects ----------------- [`LogRecord`](#logging.LogRecord "logging.LogRecord") instances are created automatically by the [`Logger`](#logging.Logger "logging.Logger") every time something is logged, and can be created manually via [`makeLogRecord()`](#logging.makeLogRecord "logging.makeLogRecord") (for example, from a pickled event received over the wire). `class logging.LogRecord(name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None)` Contains all the information pertinent to the event being logged. The primary information is passed in `msg` and `args`, which are combined using `msg % args` to create the `message` field of the record. Parameters * **name** – The name of the logger used to log the event represented by this LogRecord. Note that this name will always have this value, even though it may be emitted by a handler attached to a different (ancestor) logger. * **level** – The numeric level of the logging event (one of DEBUG, INFO etc.) Note that this is converted to *two* attributes of the LogRecord: `levelno` for the numeric value and `levelname` for the corresponding level name. * **pathname** – The full pathname of the source file where the logging call was made. * **lineno** – The line number in the source file where the logging call was made. * **msg** – The event description message, possibly a format string with placeholders for variable data. * **args** – Variable data to merge into the *msg* argument to obtain the event description. * **exc\_info** – An exception tuple with the current exception information, or `None` if no exception information is available. * **func** – The name of the function or method from which the logging call was invoked. * **sinfo** – A text string representing stack information from the base of the stack in the current thread, up to the logging call. `getMessage()` Returns the message for this [`LogRecord`](#logging.LogRecord "logging.LogRecord") instance after merging any user-supplied arguments with the message. If the user-supplied message argument to the logging call is not a string, [`str()`](stdtypes#str "str") is called on it to convert it to a string. This allows use of user-defined classes as messages, whose `__str__` method can return the actual format string to be used. Changed in version 3.2: The creation of a [`LogRecord`](#logging.LogRecord "logging.LogRecord") has been made more configurable by providing a factory which is used to create the record. The factory can be set using [`getLogRecordFactory()`](#logging.getLogRecordFactory "logging.getLogRecordFactory") and [`setLogRecordFactory()`](#logging.setLogRecordFactory "logging.setLogRecordFactory") (see this for the factory’s signature). This functionality can be used to inject your own values into a [`LogRecord`](#logging.LogRecord "logging.LogRecord") at creation time. You can use the following pattern: ``` old_factory = logging.getLogRecordFactory() def record_factory(*args, **kwargs): record = old_factory(*args, **kwargs) record.custom_attribute = 0xdecafbad return record logging.setLogRecordFactory(record_factory) ``` With this pattern, multiple factories could be chained, and as long as they don’t overwrite each other’s attributes or unintentionally overwrite the standard attributes listed above, there should be no surprises. LogRecord attributes -------------------- The LogRecord has a number of attributes, most of which are derived from the parameters to the constructor. (Note that the names do not always correspond exactly between the LogRecord constructor parameters and the LogRecord attributes.) These attributes can be used to merge data from the record into the format string. The following table lists (in alphabetical order) the attribute names, their meanings and the corresponding placeholder in a %-style format string. If you are using {}-formatting ([`str.format()`](stdtypes#str.format "str.format")), you can use `{attrname}` as the placeholder in the format string. If you are using $-formatting ([`string.Template`](string#string.Template "string.Template")), use the form `${attrname}`. In both cases, of course, replace `attrname` with the actual attribute name you want to use. In the case of {}-formatting, you can specify formatting flags by placing them after the attribute name, separated from it with a colon. For example: a placeholder of `{msecs:03d}` would format a millisecond value of `4` as `004`. Refer to the [`str.format()`](stdtypes#str.format "str.format") documentation for full details on the options available to you. | Attribute name | Format | Description | | --- | --- | --- | | args | You shouldn’t need to format this yourself. | The tuple of arguments merged into `msg` to produce `message`, or a dict whose values are used for the merge (when there is only one argument, and it is a dictionary). | | asctime | `%(asctime)s` | Human-readable time when the [`LogRecord`](#logging.LogRecord "logging.LogRecord") was created. By default this is of the form ‘2003-07-08 16:49:45,896’ (the numbers after the comma are millisecond portion of the time). | | created | `%(created)f` | Time when the [`LogRecord`](#logging.LogRecord "logging.LogRecord") was created (as returned by [`time.time()`](time#time.time "time.time")). | | exc\_info | You shouldn’t need to format this yourself. | Exception tuple (à la `sys.exc_info`) or, if no exception has occurred, `None`. | | filename | `%(filename)s` | Filename portion of `pathname`. | | funcName | `%(funcName)s` | Name of function containing the logging call. | | levelname | `%(levelname)s` | Text logging level for the message (`'DEBUG'`, `'INFO'`, `'WARNING'`, `'ERROR'`, `'CRITICAL'`). | | levelno | `%(levelno)s` | Numeric logging level for the message (`DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`). | | lineno | `%(lineno)d` | Source line number where the logging call was issued (if available). | | message | `%(message)s` | The logged message, computed as `msg % args`. This is set when [`Formatter.format()`](#logging.Formatter.format "logging.Formatter.format") is invoked. | | module | `%(module)s` | Module (name portion of `filename`). | | msecs | `%(msecs)d` | Millisecond portion of the time when the [`LogRecord`](#logging.LogRecord "logging.LogRecord") was created. | | msg | You shouldn’t need to format this yourself. | The format string passed in the original logging call. Merged with `args` to produce `message`, or an arbitrary object (see [Using arbitrary objects as messages](../howto/logging#arbitrary-object-messages)). | | name | `%(name)s` | Name of the logger used to log the call. | | pathname | `%(pathname)s` | Full pathname of the source file where the logging call was issued (if available). | | process | `%(process)d` | Process ID (if available). | | processName | `%(processName)s` | Process name (if available). | | relativeCreated | `%(relativeCreated)d` | Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded. | | stack\_info | You shouldn’t need to format this yourself. | Stack frame information (where available) from the bottom of the stack in the current thread, up to and including the stack frame of the logging call which resulted in the creation of this record. | | thread | `%(thread)d` | Thread ID (if available). | | threadName | `%(threadName)s` | Thread name (if available). | Changed in version 3.1: *processName* was added. LoggerAdapter Objects --------------------- [`LoggerAdapter`](#logging.LoggerAdapter "logging.LoggerAdapter") instances are used to conveniently pass contextual information into logging calls. For a usage example, see the section on [adding contextual information to your logging output](../howto/logging-cookbook#context-info). `class logging.LoggerAdapter(logger, extra)` Returns an instance of [`LoggerAdapter`](#logging.LoggerAdapter "logging.LoggerAdapter") initialized with an underlying [`Logger`](#logging.Logger "logging.Logger") instance and a dict-like object. `process(msg, kwargs)` Modifies the message and/or keyword arguments passed to a logging call in order to insert contextual information. This implementation takes the object passed as *extra* to the constructor and adds it to *kwargs* using key ‘extra’. The return value is a (*msg*, *kwargs*) tuple which has the (possibly modified) versions of the arguments passed in. In addition to the above, [`LoggerAdapter`](#logging.LoggerAdapter "logging.LoggerAdapter") supports the following methods of [`Logger`](#logging.Logger "logging.Logger"): [`debug()`](#logging.Logger.debug "logging.Logger.debug"), [`info()`](#logging.Logger.info "logging.Logger.info"), [`warning()`](#logging.Logger.warning "logging.Logger.warning"), [`error()`](#logging.Logger.error "logging.Logger.error"), [`exception()`](#logging.Logger.exception "logging.Logger.exception"), [`critical()`](#logging.Logger.critical "logging.Logger.critical"), [`log()`](#logging.Logger.log "logging.Logger.log"), [`isEnabledFor()`](#logging.Logger.isEnabledFor "logging.Logger.isEnabledFor"), [`getEffectiveLevel()`](#logging.Logger.getEffectiveLevel "logging.Logger.getEffectiveLevel"), [`setLevel()`](#logging.Logger.setLevel "logging.Logger.setLevel") and [`hasHandlers()`](#logging.Logger.hasHandlers "logging.Logger.hasHandlers"). These methods have the same signatures as their counterparts in [`Logger`](#logging.Logger "logging.Logger"), so you can use the two types of instances interchangeably. Changed in version 3.2: The [`isEnabledFor()`](#logging.Logger.isEnabledFor "logging.Logger.isEnabledFor"), [`getEffectiveLevel()`](#logging.Logger.getEffectiveLevel "logging.Logger.getEffectiveLevel"), [`setLevel()`](#logging.Logger.setLevel "logging.Logger.setLevel") and [`hasHandlers()`](#logging.Logger.hasHandlers "logging.Logger.hasHandlers") methods were added to [`LoggerAdapter`](#logging.LoggerAdapter "logging.LoggerAdapter"). These methods delegate to the underlying logger. Changed in version 3.6: Attribute `manager` and method `_log()` were added, which delegate to the underlying logger and allow adapters to be nested. Thread Safety ------------- The logging module is intended to be thread-safe without any special work needing to be done by its clients. It achieves this though using threading locks; there is one lock to serialize access to the module’s shared data, and each handler also creates a lock to serialize access to its underlying I/O. If you are implementing asynchronous signal handlers using the [`signal`](signal#module-signal "signal: Set handlers for asynchronous events.") module, you may not be able to use logging from within such handlers. This is because lock implementations in the [`threading`](threading#module-threading "threading: Thread-based parallelism.") module are not always re-entrant, and so cannot be invoked from such signal handlers. Module-Level Functions ---------------------- In addition to the classes described above, there are a number of module-level functions. `logging.getLogger(name=None)` Return a logger with the specified name or, if name is `None`, return a logger which is the root logger of the hierarchy. If specified, the name is typically a dot-separated hierarchical name like *‘a’*, *‘a.b’* or *‘a.b.c.d’*. Choice of these names is entirely up to the developer who is using logging. All calls to this function with a given name return the same logger instance. This means that logger instances never need to be passed between different parts of an application. `logging.getLoggerClass()` Return either the standard [`Logger`](#logging.Logger "logging.Logger") class, or the last class passed to [`setLoggerClass()`](#logging.setLoggerClass "logging.setLoggerClass"). This function may be called from within a new class definition, to ensure that installing a customized [`Logger`](#logging.Logger "logging.Logger") class will not undo customizations already applied by other code. For example: ``` class MyLogger(logging.getLoggerClass()): # ... override behaviour here ``` `logging.getLogRecordFactory()` Return a callable which is used to create a [`LogRecord`](#logging.LogRecord "logging.LogRecord"). New in version 3.2: This function has been provided, along with [`setLogRecordFactory()`](#logging.setLogRecordFactory "logging.setLogRecordFactory"), to allow developers more control over how the [`LogRecord`](#logging.LogRecord "logging.LogRecord") representing a logging event is constructed. See [`setLogRecordFactory()`](#logging.setLogRecordFactory "logging.setLogRecordFactory") for more information about the how the factory is called. `logging.debug(msg, *args, **kwargs)` Logs a message with level `DEBUG` on the root logger. The *msg* is the message format string, and the *args* are the arguments which are merged into *msg* using the string formatting operator. (Note that this means that you can use keywords in the format string, together with a single dictionary argument.) There are three keyword arguments in *kwargs* which are inspected: *exc\_info* which, if it does not evaluate as false, causes exception information to be added to the logging message. If an exception tuple (in the format returned by [`sys.exc_info()`](sys#sys.exc_info "sys.exc_info")) or an exception instance is provided, it is used; otherwise, [`sys.exc_info()`](sys#sys.exc_info "sys.exc_info") is called to get the exception information. The second optional keyword argument is *stack\_info*, which defaults to `False`. If true, stack information is added to the logging message, including the actual logging call. Note that this is not the same stack information as that displayed through specifying *exc\_info*: The former is stack frames from the bottom of the stack up to the logging call in the current thread, whereas the latter is information about stack frames which have been unwound, following an exception, while searching for exception handlers. You can specify *stack\_info* independently of *exc\_info*, e.g. to just show how you got to a certain point in your code, even when no exceptions were raised. The stack frames are printed following a header line which says: ``` Stack (most recent call last): ``` This mimics the `Traceback (most recent call last):` which is used when displaying exception frames. The third optional keyword argument is *extra* which can be used to pass a dictionary which is used to populate the \_\_dict\_\_ of the LogRecord created for the logging event with user-defined attributes. These custom attributes can then be used as you like. For example, they could be incorporated into logged messages. For example: ``` FORMAT = '%(asctime)s %(clientip)-15s %(user)-8s %(message)s' logging.basicConfig(format=FORMAT) d = {'clientip': '192.168.0.1', 'user': 'fbloggs'} logging.warning('Protocol problem: %s', 'connection reset', extra=d) ``` would print something like: ``` 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset ``` The keys in the dictionary passed in *extra* should not clash with the keys used by the logging system. (See the [`Formatter`](#logging.Formatter "logging.Formatter") documentation for more information on which keys are used by the logging system.) If you choose to use these attributes in logged messages, you need to exercise some care. In the above example, for instance, the [`Formatter`](#logging.Formatter "logging.Formatter") has been set up with a format string which expects ‘clientip’ and ‘user’ in the attribute dictionary of the LogRecord. If these are missing, the message will not be logged because a string formatting exception will occur. So in this case, you always need to pass the *extra* dictionary with these keys. While this might be annoying, this feature is intended for use in specialized circumstances, such as multi-threaded servers where the same code executes in many contexts, and interesting conditions which arise are dependent on this context (such as remote client IP address and authenticated user name, in the above example). In such circumstances, it is likely that specialized [`Formatter`](#logging.Formatter "logging.Formatter")s would be used with particular [`Handler`](#logging.Handler "logging.Handler")s. Changed in version 3.2: The *stack\_info* parameter was added. `logging.info(msg, *args, **kwargs)` Logs a message with level `INFO` on the root logger. The arguments are interpreted as for [`debug()`](#logging.debug "logging.debug"). `logging.warning(msg, *args, **kwargs)` Logs a message with level `WARNING` on the root logger. The arguments are interpreted as for [`debug()`](#logging.debug "logging.debug"). Note There is an obsolete function `warn` which is functionally identical to `warning`. As `warn` is deprecated, please do not use it - use `warning` instead. `logging.error(msg, *args, **kwargs)` Logs a message with level `ERROR` on the root logger. The arguments are interpreted as for [`debug()`](#logging.debug "logging.debug"). `logging.critical(msg, *args, **kwargs)` Logs a message with level `CRITICAL` on the root logger. The arguments are interpreted as for [`debug()`](#logging.debug "logging.debug"). `logging.exception(msg, *args, **kwargs)` Logs a message with level `ERROR` on the root logger. The arguments are interpreted as for [`debug()`](#logging.debug "logging.debug"). Exception info is added to the logging message. This function should only be called from an exception handler. `logging.log(level, msg, *args, **kwargs)` Logs a message with level *level* on the root logger. The other arguments are interpreted as for [`debug()`](#logging.debug "logging.debug"). `logging.disable(level=CRITICAL)` Provides an overriding level *level* for all loggers which takes precedence over the logger’s own level. When the need arises to temporarily throttle logging output down across the whole application, this function can be useful. Its effect is to disable all logging calls of severity *level* and below, so that if you call it with a value of INFO, then all INFO and DEBUG events would be discarded, whereas those of severity WARNING and above would be processed according to the logger’s effective level. If `logging.disable(logging.NOTSET)` is called, it effectively removes this overriding level, so that logging output again depends on the effective levels of individual loggers. Note that if you have defined any custom logging level higher than `CRITICAL` (this is not recommended), you won’t be able to rely on the default value for the *level* parameter, but will have to explicitly supply a suitable value. Changed in version 3.7: The *level* parameter was defaulted to level `CRITICAL`. See [bpo-28524](https://bugs.python.org/issue?@action=redirect&bpo=28524) for more information about this change. `logging.addLevelName(level, levelName)` Associates level *level* with text *levelName* in an internal dictionary, which is used to map numeric levels to a textual representation, for example when a [`Formatter`](#logging.Formatter "logging.Formatter") formats a message. This function can also be used to define your own levels. The only constraints are that all levels used must be registered using this function, levels should be positive integers and they should increase in increasing order of severity. Note If you are thinking of defining your own levels, please see the section on [Custom Levels](../howto/logging#custom-levels). `logging.getLevelName(level)` Returns the textual or numeric representation of logging level *level*. If *level* is one of the predefined levels `CRITICAL`, `ERROR`, `WARNING`, `INFO` or `DEBUG` then you get the corresponding string. If you have associated levels with names using [`addLevelName()`](#logging.addLevelName "logging.addLevelName") then the name you have associated with *level* is returned. If a numeric value corresponding to one of the defined levels is passed in, the corresponding string representation is returned. The *level* parameter also accepts a string representation of the level such as ‘INFO’. In such cases, this functions returns the corresponding numeric value of the level. If no matching numeric or string value is passed in, the string ‘Level %s’ % level is returned. Note Levels are internally integers (as they need to be compared in the logging logic). This function is used to convert between an integer level and the level name displayed in the formatted log output by means of the `%(levelname)s` format specifier (see [LogRecord attributes](#logrecord-attributes)), and vice versa. Changed in version 3.4: In Python versions earlier than 3.4, this function could also be passed a text level, and would return the corresponding numeric value of the level. This undocumented behaviour was considered a mistake, and was removed in Python 3.4, but reinstated in 3.4.2 due to retain backward compatibility. `logging.makeLogRecord(attrdict)` Creates and returns a new [`LogRecord`](#logging.LogRecord "logging.LogRecord") instance whose attributes are defined by *attrdict*. This function is useful for taking a pickled [`LogRecord`](#logging.LogRecord "logging.LogRecord") attribute dictionary, sent over a socket, and reconstituting it as a [`LogRecord`](#logging.LogRecord "logging.LogRecord") instance at the receiving end. `logging.basicConfig(**kwargs)` Does basic configuration for the logging system by creating a [`StreamHandler`](logging.handlers#logging.StreamHandler "logging.StreamHandler") with a default [`Formatter`](#logging.Formatter "logging.Formatter") and adding it to the root logger. The functions [`debug()`](#logging.debug "logging.debug"), [`info()`](#logging.info "logging.info"), [`warning()`](#logging.warning "logging.warning"), [`error()`](#logging.error "logging.error") and [`critical()`](#logging.critical "logging.critical") will call [`basicConfig()`](#logging.basicConfig "logging.basicConfig") automatically if no handlers are defined for the root logger. This function does nothing if the root logger already has handlers configured, unless the keyword argument *force* is set to `True`. Note This function should be called from the main thread before other threads are started. In versions of Python prior to 2.7.1 and 3.2, if this function is called from multiple threads, it is possible (in rare circumstances) that a handler will be added to the root logger more than once, leading to unexpected results such as messages being duplicated in the log. The following keyword arguments are supported. | Format | Description | | --- | --- | | *filename* | Specifies that a FileHandler be created, using the specified filename, rather than a StreamHandler. | | *filemode* | If *filename* is specified, open the file in this [mode](functions#filemodes). Defaults to `'a'`. | | *format* | Use the specified format string for the handler. Defaults to attributes `levelname`, `name` and `message` separated by colons. | | *datefmt* | Use the specified date/time format, as accepted by [`time.strftime()`](time#time.strftime "time.strftime"). | | *style* | If *format* is specified, use this style for the format string. One of `'%'`, `'{'` or `'$'` for [printf-style](stdtypes#old-string-formatting), [`str.format()`](stdtypes#str.format "str.format") or [`string.Template`](string#string.Template "string.Template") respectively. Defaults to `'%'`. | | *level* | Set the root logger level to the specified [level](#levels). | | *stream* | Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with *filename* - if both are present, a `ValueError` is raised. | | *handlers* | If specified, this should be an iterable of already created handlers to add to the root logger. Any handlers which don’t already have a formatter set will be assigned the default formatter created in this function. Note that this argument is incompatible with *filename* or *stream* - if both are present, a `ValueError` is raised. | | *force* | If this keyword argument is specified as true, any existing handlers attached to the root logger are removed and closed, before carrying out the configuration as specified by the other arguments. | | *encoding* | If this keyword argument is specified along with *filename*, its value is used when the FileHandler is created, and thus used when opening the output file. | | *errors* | If this keyword argument is specified along with *filename*, its value is used when the FileHandler is created, and thus used when opening the output file. If not specified, the value ‘backslashreplace’ is used. Note that if `None` is specified, it will be passed as such to func:`open`, which means that it will be treated the same as passing ‘errors’. | Changed in version 3.2: The *style* argument was added. Changed in version 3.3: The *handlers* argument was added. Additional checks were added to catch situations where incompatible arguments are specified (e.g. *handlers* together with *stream* or *filename*, or *stream* together with *filename*). Changed in version 3.8: The *force* argument was added. Changed in version 3.9: The *encoding* and *errors* arguments were added. `logging.shutdown()` Informs the logging system to perform an orderly shutdown by flushing and closing all handlers. This should be called at application exit and no further use of the logging system should be made after this call. When the logging module is imported, it registers this function as an exit handler (see [`atexit`](atexit#module-atexit "atexit: Register and execute cleanup functions.")), so normally there’s no need to do that manually. `logging.setLoggerClass(klass)` Tells the logging system to use the class *klass* when instantiating a logger. The class should define [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") such that only a name argument is required, and the [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") should call `Logger.__init__()`. This function is typically called before any loggers are instantiated by applications which need to use custom logger behavior. After this call, as at any other time, do not instantiate loggers directly using the subclass: continue to use the [`logging.getLogger()`](#logging.getLogger "logging.getLogger") API to get your loggers. `logging.setLogRecordFactory(factory)` Set a callable which is used to create a [`LogRecord`](#logging.LogRecord "logging.LogRecord"). Parameters **factory** – The factory callable to be used to instantiate a log record. New in version 3.2: This function has been provided, along with [`getLogRecordFactory()`](#logging.getLogRecordFactory "logging.getLogRecordFactory"), to allow developers more control over how the [`LogRecord`](#logging.LogRecord "logging.LogRecord") representing a logging event is constructed. The factory has the following signature: `factory(name, level, fn, lno, msg, args, exc_info, func=None, sinfo=None, **kwargs)` name The logger name. level The logging level (numeric). fn The full pathname of the file where the logging call was made. lno The line number in the file where the logging call was made. msg The logging message. args The arguments for the logging message. exc\_info An exception tuple, or `None`. func The name of the function or method which invoked the logging call. sinfo A stack traceback such as is provided by [`traceback.print_stack()`](traceback#traceback.print_stack "traceback.print_stack"), showing the call hierarchy. kwargs Additional keyword arguments. Module-Level Attributes ----------------------- `logging.lastResort` A “handler of last resort” is available through this attribute. This is a [`StreamHandler`](logging.handlers#logging.StreamHandler "logging.StreamHandler") writing to `sys.stderr` with a level of `WARNING`, and is used to handle logging events in the absence of any logging configuration. The end result is to just print the message to `sys.stderr`. This replaces the earlier error message saying that “no handlers could be found for logger XYZ”. If you need the earlier behaviour for some reason, `lastResort` can be set to `None`. New in version 3.2. Integration with the warnings module ------------------------------------ The [`captureWarnings()`](#logging.captureWarnings "logging.captureWarnings") function can be used to integrate [`logging`](#module-logging "logging: Flexible event logging system for applications.") with the [`warnings`](warnings#module-warnings "warnings: Issue warning messages and control their disposition.") module. `logging.captureWarnings(capture)` This function is used to turn the capture of warnings by logging on and off. If *capture* is `True`, warnings issued by the [`warnings`](warnings#module-warnings "warnings: Issue warning messages and control their disposition.") module will be redirected to the logging system. Specifically, a warning will be formatted using [`warnings.formatwarning()`](warnings#warnings.formatwarning "warnings.formatwarning") and the resulting string logged to a logger named `'py.warnings'` with a severity of `WARNING`. If *capture* is `False`, the redirection of warnings to the logging system will stop, and warnings will be redirected to their original destinations (i.e. those in effect before `captureWarnings(True)` was called). See also `Module` [`logging.config`](logging.config#module-logging.config "logging.config: Configuration of the logging module.") Configuration API for the logging module. `Module` [`logging.handlers`](logging.handlers#module-logging.handlers "logging.handlers: Handlers for the logging module.") Useful handlers included with the logging module. [**PEP 282**](https://www.python.org/dev/peps/pep-0282) - A Logging System The proposal which described this feature for inclusion in the Python standard library. [Original Python logging package](https://old.red-dove.com/python_logging.html) This is the original source for the [`logging`](#module-logging "logging: Flexible event logging system for applications.") package. The version of the package available from this site is suitable for use with Python 1.5.2, 2.1.x and 2.2.x, which do not include the [`logging`](#module-logging "logging: Flexible event logging system for applications.") package in the standard library.
programming_docs
python High-level API Index High-level API Index ==================== This page lists all high-level async/await enabled asyncio APIs. Tasks ----- Utilities to run asyncio programs, create Tasks, and await on multiple things with timeouts. | | | | --- | --- | | [`run()`](asyncio-task#asyncio.run "asyncio.run") | Create event loop, run a coroutine, close the loop. | | [`create_task()`](asyncio-task#asyncio.create_task "asyncio.create_task") | Start an asyncio Task. | | `await` [`sleep()`](asyncio-task#asyncio.sleep "asyncio.sleep") | Sleep for a number of seconds. | | `await` [`gather()`](asyncio-task#asyncio.gather "asyncio.gather") | Schedule and wait for things concurrently. | | `await` [`wait_for()`](asyncio-task#asyncio.wait_for "asyncio.wait_for") | Run with a timeout. | | `await` [`shield()`](asyncio-task#asyncio.shield "asyncio.shield") | Shield from cancellation. | | `await` [`wait()`](asyncio-task#asyncio.wait "asyncio.wait") | Monitor for completion. | | [`current_task()`](asyncio-task#asyncio.current_task "asyncio.current_task") | Return the current Task. | | [`all_tasks()`](asyncio-task#asyncio.all_tasks "asyncio.all_tasks") | Return all tasks for an event loop. | | [`Task`](asyncio-task#asyncio.Task "asyncio.Task") | Task object. | | [`to_thread()`](asyncio-task#asyncio.to_thread "asyncio.to_thread") | Asychronously run a function in a separate OS thread. | | [`run_coroutine_threadsafe()`](asyncio-task#asyncio.run_coroutine_threadsafe "asyncio.run_coroutine_threadsafe") | Schedule a coroutine from another OS thread. | | `for in` [`as_completed()`](asyncio-task#asyncio.as_completed "asyncio.as_completed") | Monitor for completion with a `for` loop. | #### Examples * [Using asyncio.gather() to run things in parallel](asyncio-task#asyncio-example-gather). * [Using asyncio.wait\_for() to enforce a timeout](asyncio-task#asyncio-example-waitfor). * [Cancellation](asyncio-task#asyncio-example-task-cancel). * [Using asyncio.sleep()](asyncio-task#asyncio-example-sleep). * See also the main [Tasks documentation page](asyncio-task#coroutine). Queues ------ Queues should be used to distribute work amongst multiple asyncio Tasks, implement connection pools, and pub/sub patterns. | | | | --- | --- | | [`Queue`](asyncio-queue#asyncio.Queue "asyncio.Queue") | A FIFO queue. | | [`PriorityQueue`](asyncio-queue#asyncio.PriorityQueue "asyncio.PriorityQueue") | A priority queue. | | [`LifoQueue`](asyncio-queue#asyncio.LifoQueue "asyncio.LifoQueue") | A LIFO queue. | #### Examples * [Using asyncio.Queue to distribute workload between several Tasks](asyncio-queue#asyncio-example-queue-dist). * See also the [Queues documentation page](asyncio-queue#asyncio-queues). Subprocesses ------------ Utilities to spawn subprocesses and run shell commands. | | | | --- | --- | | `await` [`create_subprocess_exec()`](asyncio-subprocess#asyncio.create_subprocess_exec "asyncio.create_subprocess_exec") | Create a subprocess. | | `await` [`create_subprocess_shell()`](asyncio-subprocess#asyncio.create_subprocess_shell "asyncio.create_subprocess_shell") | Run a shell command. | #### Examples * [Executing a shell command](asyncio-subprocess#asyncio-example-subprocess-shell). * See also the [subprocess APIs](asyncio-subprocess#asyncio-subprocess) documentation. Streams ------- High-level APIs to work with network IO. | | | | --- | --- | | `await` [`open_connection()`](asyncio-stream#asyncio.open_connection "asyncio.open_connection") | Establish a TCP connection. | | `await` [`open_unix_connection()`](asyncio-stream#asyncio.open_unix_connection "asyncio.open_unix_connection") | Establish a Unix socket connection. | | `await` [`start_server()`](asyncio-stream#asyncio.start_server "asyncio.start_server") | Start a TCP server. | | `await` [`start_unix_server()`](asyncio-stream#asyncio.start_unix_server "asyncio.start_unix_server") | Start a Unix socket server. | | [`StreamReader`](asyncio-stream#asyncio.StreamReader "asyncio.StreamReader") | High-level async/await object to receive network data. | | [`StreamWriter`](asyncio-stream#asyncio.StreamWriter "asyncio.StreamWriter") | High-level async/await object to send network data. | #### Examples * [Example TCP client](asyncio-stream#asyncio-example-stream). * See also the [streams APIs](asyncio-stream#asyncio-streams) documentation. Synchronization --------------- Threading-like synchronization primitives that can be used in Tasks. | | | | --- | --- | | [`Lock`](asyncio-sync#asyncio.Lock "asyncio.Lock") | A mutex lock. | | [`Event`](asyncio-sync#asyncio.Event "asyncio.Event") | An event object. | | [`Condition`](asyncio-sync#asyncio.Condition "asyncio.Condition") | A condition object. | | [`Semaphore`](asyncio-sync#asyncio.Semaphore "asyncio.Semaphore") | A semaphore. | | [`BoundedSemaphore`](asyncio-sync#asyncio.BoundedSemaphore "asyncio.BoundedSemaphore") | A bounded semaphore. | #### Examples * [Using asyncio.Event](asyncio-sync#asyncio-example-sync-event). * See also the documentation of asyncio [synchronization primitives](asyncio-sync#asyncio-sync). Exceptions ---------- | | | | --- | --- | | [`asyncio.TimeoutError`](asyncio-exceptions#asyncio.TimeoutError "asyncio.TimeoutError") | Raised on timeout by functions like [`wait_for()`](asyncio-task#asyncio.wait_for "asyncio.wait_for"). Keep in mind that `asyncio.TimeoutError` is **unrelated** to the built-in [`TimeoutError`](exceptions#TimeoutError "TimeoutError") exception. | | [`asyncio.CancelledError`](asyncio-exceptions#asyncio.CancelledError "asyncio.CancelledError") | Raised when a Task is cancelled. See also [`Task.cancel()`](asyncio-task#asyncio.Task.cancel "asyncio.Task.cancel"). | #### Examples * [Handling CancelledError to run code on cancellation request](asyncio-task#asyncio-example-task-cancel). * See also the full list of [asyncio-specific exceptions](asyncio-exceptions#asyncio-exceptions). python Built-in Constants Built-in Constants ================== A small number of constants live in the built-in namespace. They are: `False` The false value of the [`bool`](functions#bool "bool") type. Assignments to `False` are illegal and raise a [`SyntaxError`](exceptions#SyntaxError "SyntaxError"). `True` The true value of the [`bool`](functions#bool "bool") type. Assignments to `True` are illegal and raise a [`SyntaxError`](exceptions#SyntaxError "SyntaxError"). `None` The sole value of the type `NoneType`. `None` is frequently used to represent the absence of a value, as when default arguments are not passed to a function. Assignments to `None` are illegal and raise a [`SyntaxError`](exceptions#SyntaxError "SyntaxError"). `NotImplemented` Special value which should be returned by the binary special methods (e.g. [`__eq__()`](../reference/datamodel#object.__eq__ "object.__eq__"), [`__lt__()`](../reference/datamodel#object.__lt__ "object.__lt__"), [`__add__()`](../reference/datamodel#object.__add__ "object.__add__"), [`__rsub__()`](../reference/datamodel#object.__rsub__ "object.__rsub__"), etc.) to indicate that the operation is not implemented with respect to the other type; may be returned by the in-place binary special methods (e.g. [`__imul__()`](../reference/datamodel#object.__imul__ "object.__imul__"), [`__iand__()`](../reference/datamodel#object.__iand__ "object.__iand__"), etc.) for the same purpose. It should not be evaluated in a boolean context. Note When a binary (or in-place) method returns `NotImplemented` the interpreter will try the reflected operation on the other type (or some other fallback, depending on the operator). If all attempts return `NotImplemented`, the interpreter will raise an appropriate exception. Incorrectly returning `NotImplemented` will result in a misleading error message or the `NotImplemented` value being returned to Python code. See [Implementing the arithmetic operations](numbers#implementing-the-arithmetic-operations) for examples. Note `NotImplementedError` and `NotImplemented` are not interchangeable, even though they have similar names and purposes. See [`NotImplementedError`](exceptions#NotImplementedError "NotImplementedError") for details on when to use it. Changed in version 3.9: Evaluating `NotImplemented` in a boolean context is deprecated. While it currently evaluates as true, it will emit a [`DeprecationWarning`](exceptions#DeprecationWarning "DeprecationWarning"). It will raise a [`TypeError`](exceptions#TypeError "TypeError") in a future version of Python. `Ellipsis` The same as the ellipsis literal “`...`”. Special value used mostly in conjunction with extended slicing syntax for user-defined container data types. `__debug__` This constant is true if Python was not started with an [`-O`](../using/cmdline#cmdoption-o) option. See also the [`assert`](../reference/simple_stmts#assert) statement. Note The names [`None`](#None "None"), [`False`](#False "False"), [`True`](#True "True") and [`__debug__`](#__debug__ "__debug__") cannot be reassigned (assignments to them, even as an attribute name, raise [`SyntaxError`](exceptions#SyntaxError "SyntaxError")), so they can be considered “true” constants. Constants added by the site module ---------------------------------- The [`site`](site#module-site "site: Module responsible for site-specific configuration.") module (which is imported automatically during startup, except if the [`-S`](../using/cmdline#id3) command-line option is given) adds several constants to the built-in namespace. They are useful for the interactive interpreter shell and should not be used in programs. `quit(code=None)` `exit(code=None)` Objects that when printed, print a message like “Use quit() or Ctrl-D (i.e. EOF) to exit”, and when called, raise [`SystemExit`](exceptions#SystemExit "SystemExit") with the specified exit code. `copyright` `credits` Objects that when printed or called, print the text of copyright or credits, respectively. `license` Object that when printed, prints the message “Type license() to see the full license text”, and when called, displays the full license text in a pager-like fashion (one screen at a time). python signal — Set handlers for asynchronous events signal — Set handlers for asynchronous events ============================================= This module provides mechanisms to use signal handlers in Python. General rules ------------- The [`signal.signal()`](#signal.signal "signal.signal") function allows defining custom handlers to be executed when a signal is received. A small number of default handlers are installed: [`SIGPIPE`](#signal.SIGPIPE "signal.SIGPIPE") is ignored (so write errors on pipes and sockets can be reported as ordinary Python exceptions) and [`SIGINT`](#signal.SIGINT "signal.SIGINT") is translated into a [`KeyboardInterrupt`](exceptions#KeyboardInterrupt "KeyboardInterrupt") exception if the parent process has not changed it. A handler for a particular signal, once set, remains installed until it is explicitly reset (Python emulates the BSD style interface regardless of the underlying implementation), with the exception of the handler for [`SIGCHLD`](#signal.SIGCHLD "signal.SIGCHLD"), which follows the underlying implementation. ### Execution of Python signal handlers A Python signal handler does not get executed inside the low-level (C) signal handler. Instead, the low-level signal handler sets a flag which tells the [virtual machine](../glossary#term-virtual-machine) to execute the corresponding Python signal handler at a later point(for example at the next [bytecode](../glossary#term-bytecode) instruction). This has consequences: * It makes little sense to catch synchronous errors like [`SIGFPE`](#signal.SIGFPE "signal.SIGFPE") or [`SIGSEGV`](#signal.SIGSEGV "signal.SIGSEGV") that are caused by an invalid operation in C code. Python will return from the signal handler to the C code, which is likely to raise the same signal again, causing Python to apparently hang. From Python 3.3 onwards, you can use the [`faulthandler`](faulthandler#module-faulthandler "faulthandler: Dump the Python traceback.") module to report on synchronous errors. * A long-running calculation implemented purely in C (such as regular expression matching on a large body of text) may run uninterrupted for an arbitrary amount of time, regardless of any signals received. The Python signal handlers will be called when the calculation finishes. * If the handler raises an exception, it will be raised “out of thin air” in the main thread. See the [note below](#handlers-and-exceptions) for a discussion. ### Signals and threads Python signal handlers are always executed in the main Python thread of the main interpreter, even if the signal was received in another thread. This means that signals can’t be used as a means of inter-thread communication. You can use the synchronization primitives from the [`threading`](threading#module-threading "threading: Thread-based parallelism.") module instead. Besides, only the main thread of the main interpreter is allowed to set a new signal handler. Module contents --------------- Changed in version 3.5: signal (SIG\*), handler ([`SIG_DFL`](#signal.SIG_DFL "signal.SIG_DFL"), [`SIG_IGN`](#signal.SIG_IGN "signal.SIG_IGN")) and sigmask ([`SIG_BLOCK`](#signal.SIG_BLOCK "signal.SIG_BLOCK"), [`SIG_UNBLOCK`](#signal.SIG_UNBLOCK "signal.SIG_UNBLOCK"), [`SIG_SETMASK`](#signal.SIG_SETMASK "signal.SIG_SETMASK")) related constants listed below were turned into [`enums`](enum#enum.IntEnum "enum.IntEnum"). [`getsignal()`](#signal.getsignal "signal.getsignal"), [`pthread_sigmask()`](#signal.pthread_sigmask "signal.pthread_sigmask"), [`sigpending()`](#signal.sigpending "signal.sigpending") and [`sigwait()`](#signal.sigwait "signal.sigwait") functions return human-readable [`enums`](enum#enum.IntEnum "enum.IntEnum"). The variables defined in the [`signal`](#module-signal "signal: Set handlers for asynchronous events.") module are: `signal.SIG_DFL` This is one of two standard signal handling options; it will simply perform the default function for the signal. For example, on most systems the default action for `SIGQUIT` is to dump core and exit, while the default action for [`SIGCHLD`](#signal.SIGCHLD "signal.SIGCHLD") is to simply ignore it. `signal.SIG_IGN` This is another standard signal handler, which will simply ignore the given signal. `signal.SIGABRT` Abort signal from *[abort(3)](https://manpages.debian.org/abort(3))*. `signal.SIGALRM` Timer signal from *[alarm(2)](https://manpages.debian.org/alarm(2))*. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix. `signal.SIGBREAK` Interrupt from keyboard (CTRL + BREAK). [Availability](https://docs.python.org/3.9/library/intro.html#availability): Windows. `signal.SIGBUS` Bus error (bad memory access). [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix. `signal.SIGCHLD` Child process stopped or terminated. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix. `signal.SIGCLD` Alias to [`SIGCHLD`](#signal.SIGCHLD "signal.SIGCHLD"). `signal.SIGCONT` Continue the process if it is currently stopped [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix. `signal.SIGFPE` Floating-point exception. For example, division by zero. See also [`ZeroDivisionError`](exceptions#ZeroDivisionError "ZeroDivisionError") is raised when the second argument of a division or modulo operation is zero. `signal.SIGHUP` Hangup detected on controlling terminal or death of controlling process. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix. `signal.SIGILL` Illegal instruction. `signal.SIGINT` Interrupt from keyboard (CTRL + C). Default action is to raise [`KeyboardInterrupt`](exceptions#KeyboardInterrupt "KeyboardInterrupt"). `signal.SIGKILL` Kill signal. It cannot be caught, blocked, or ignored. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix. `signal.SIGPIPE` Broken pipe: write to pipe with no readers. Default action is to ignore the signal. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix. `signal.SIGSEGV` Segmentation fault: invalid memory reference. `signal.SIGTERM` Termination signal. `signal.SIGUSR1` User-defined signal 1. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix. `signal.SIGUSR2` User-defined signal 2. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix. `signal.SIGWINCH` Window resize signal. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix. `SIG*` All the signal numbers are defined symbolically. For example, the hangup signal is defined as [`signal.SIGHUP`](#signal.SIGHUP "signal.SIGHUP"); the variable names are identical to the names used in C programs, as found in `<signal.h>`. The Unix man page for ‘`signal()`’ lists the existing signals (on some systems this is *[signal(2)](https://manpages.debian.org/signal(2))*, on others the list is in *[signal(7)](https://manpages.debian.org/signal(7))*). Note that not all systems define the same set of signal names; only those names defined by the system are defined by this module. `signal.CTRL_C_EVENT` The signal corresponding to the `Ctrl+C` keystroke event. This signal can only be used with [`os.kill()`](os#os.kill "os.kill"). [Availability](https://docs.python.org/3.9/library/intro.html#availability): Windows. New in version 3.2. `signal.CTRL_BREAK_EVENT` The signal corresponding to the `Ctrl+Break` keystroke event. This signal can only be used with [`os.kill()`](os#os.kill "os.kill"). [Availability](https://docs.python.org/3.9/library/intro.html#availability): Windows. New in version 3.2. `signal.NSIG` One more than the number of the highest signal number. `signal.ITIMER_REAL` Decrements interval timer in real time, and delivers [`SIGALRM`](#signal.SIGALRM "signal.SIGALRM") upon expiration. `signal.ITIMER_VIRTUAL` Decrements interval timer only when the process is executing, and delivers SIGVTALRM upon expiration. `signal.ITIMER_PROF` Decrements interval timer both when the process executes and when the system is executing on behalf of the process. Coupled with ITIMER\_VIRTUAL, this timer is usually used to profile the time spent by the application in user and kernel space. SIGPROF is delivered upon expiration. `signal.SIG_BLOCK` A possible value for the *how* parameter to [`pthread_sigmask()`](#signal.pthread_sigmask "signal.pthread_sigmask") indicating that signals are to be blocked. New in version 3.3. `signal.SIG_UNBLOCK` A possible value for the *how* parameter to [`pthread_sigmask()`](#signal.pthread_sigmask "signal.pthread_sigmask") indicating that signals are to be unblocked. New in version 3.3. `signal.SIG_SETMASK` A possible value for the *how* parameter to [`pthread_sigmask()`](#signal.pthread_sigmask "signal.pthread_sigmask") indicating that the signal mask is to be replaced. New in version 3.3. The [`signal`](#module-signal "signal: Set handlers for asynchronous events.") module defines one exception: `exception signal.ItimerError` Raised to signal an error from the underlying [`setitimer()`](#signal.setitimer "signal.setitimer") or [`getitimer()`](#signal.getitimer "signal.getitimer") implementation. Expect this error if an invalid interval timer or a negative time is passed to [`setitimer()`](#signal.setitimer "signal.setitimer"). This error is a subtype of [`OSError`](exceptions#OSError "OSError"). New in version 3.3: This error used to be a subtype of [`IOError`](exceptions#IOError "IOError"), which is now an alias of [`OSError`](exceptions#OSError "OSError"). The [`signal`](#module-signal "signal: Set handlers for asynchronous events.") module defines the following functions: `signal.alarm(time)` If *time* is non-zero, this function requests that a [`SIGALRM`](#signal.SIGALRM "signal.SIGALRM") signal be sent to the process in *time* seconds. Any previously scheduled alarm is canceled (only one alarm can be scheduled at any time). The returned value is then the number of seconds before any previously set alarm was to have been delivered. If *time* is zero, no alarm is scheduled, and any scheduled alarm is canceled. If the return value is zero, no alarm is currently scheduled. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix. See the man page *[alarm(2)](https://manpages.debian.org/alarm(2))* for further information. `signal.getsignal(signalnum)` Return the current signal handler for the signal *signalnum*. The returned value may be a callable Python object, or one of the special values [`signal.SIG_IGN`](#signal.SIG_IGN "signal.SIG_IGN"), [`signal.SIG_DFL`](#signal.SIG_DFL "signal.SIG_DFL") or [`None`](constants#None "None"). Here, [`signal.SIG_IGN`](#signal.SIG_IGN "signal.SIG_IGN") means that the signal was previously ignored, [`signal.SIG_DFL`](#signal.SIG_DFL "signal.SIG_DFL") means that the default way of handling the signal was previously in use, and `None` means that the previous signal handler was not installed from Python. `signal.strsignal(signalnum)` Return the system description of the signal *signalnum*, such as “Interrupt”, “Segmentation fault”, etc. Returns [`None`](constants#None "None") if the signal is not recognized. New in version 3.8. `signal.valid_signals()` Return the set of valid signal numbers on this platform. This can be less than `range(1, NSIG)` if some signals are reserved by the system for internal use. New in version 3.8. `signal.pause()` Cause the process to sleep until a signal is received; the appropriate handler will then be called. Returns nothing. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix. See the man page *[signal(2)](https://manpages.debian.org/signal(2))* for further information. See also [`sigwait()`](#signal.sigwait "signal.sigwait"), [`sigwaitinfo()`](#signal.sigwaitinfo "signal.sigwaitinfo"), [`sigtimedwait()`](#signal.sigtimedwait "signal.sigtimedwait") and [`sigpending()`](#signal.sigpending "signal.sigpending"). `signal.raise_signal(signum)` Sends a signal to the calling process. Returns nothing. New in version 3.8. `signal.pidfd_send_signal(pidfd, sig, siginfo=None, flags=0)` Send signal *sig* to the process referred to by file descriptor *pidfd*. Python does not currently support the *siginfo* parameter; it must be `None`. The *flags* argument is provided for future extensions; no flag values are currently defined. See the *[pidfd\_send\_signal(2)](https://manpages.debian.org/pidfd_send_signal(2))* man page for more information. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Linux 5.1+ New in version 3.9. `signal.pthread_kill(thread_id, signalnum)` Send the signal *signalnum* to the thread *thread\_id*, another thread in the same process as the caller. The target thread can be executing any code (Python or not). However, if the target thread is executing the Python interpreter, the Python signal handlers will be [executed by the main thread of the main interpreter](#signals-and-threads). Therefore, the only point of sending a signal to a particular Python thread would be to force a running system call to fail with [`InterruptedError`](exceptions#InterruptedError "InterruptedError"). Use [`threading.get_ident()`](threading#threading.get_ident "threading.get_ident") or the [`ident`](threading#threading.Thread.ident "threading.Thread.ident") attribute of [`threading.Thread`](threading#threading.Thread "threading.Thread") objects to get a suitable value for *thread\_id*. If *signalnum* is 0, then no signal is sent, but error checking is still performed; this can be used to check if the target thread is still running. Raises an [auditing event](sys#auditing) `signal.pthread_kill` with arguments `thread_id`, `signalnum`. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix. See the man page *[pthread\_kill(3)](https://manpages.debian.org/pthread_kill(3))* for further information. See also [`os.kill()`](os#os.kill "os.kill"). New in version 3.3. `signal.pthread_sigmask(how, mask)` Fetch and/or change the signal mask of the calling thread. The signal mask is the set of signals whose delivery is currently blocked for the caller. Return the old signal mask as a set of signals. The behavior of the call is dependent on the value of *how*, as follows. * [`SIG_BLOCK`](#signal.SIG_BLOCK "signal.SIG_BLOCK"): The set of blocked signals is the union of the current set and the *mask* argument. * [`SIG_UNBLOCK`](#signal.SIG_UNBLOCK "signal.SIG_UNBLOCK"): The signals in *mask* are removed from the current set of blocked signals. It is permissible to attempt to unblock a signal which is not blocked. * [`SIG_SETMASK`](#signal.SIG_SETMASK "signal.SIG_SETMASK"): The set of blocked signals is set to the *mask* argument. *mask* is a set of signal numbers (e.g. {[`signal.SIGINT`](#signal.SIGINT "signal.SIGINT"), [`signal.SIGTERM`](#signal.SIGTERM "signal.SIGTERM")}). Use [`valid_signals()`](#signal.valid_signals "signal.valid_signals") for a full mask including all signals. For example, `signal.pthread_sigmask(signal.SIG_BLOCK, [])` reads the signal mask of the calling thread. [`SIGKILL`](#signal.SIGKILL "signal.SIGKILL") and `SIGSTOP` cannot be blocked. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix. See the man page *[sigprocmask(3)](https://manpages.debian.org/sigprocmask(3))* and *[pthread\_sigmask(3)](https://manpages.debian.org/pthread_sigmask(3))* for further information. See also [`pause()`](#signal.pause "signal.pause"), [`sigpending()`](#signal.sigpending "signal.sigpending") and [`sigwait()`](#signal.sigwait "signal.sigwait"). New in version 3.3. `signal.setitimer(which, seconds, interval=0.0)` Sets given interval timer (one of [`signal.ITIMER_REAL`](#signal.ITIMER_REAL "signal.ITIMER_REAL"), [`signal.ITIMER_VIRTUAL`](#signal.ITIMER_VIRTUAL "signal.ITIMER_VIRTUAL") or [`signal.ITIMER_PROF`](#signal.ITIMER_PROF "signal.ITIMER_PROF")) specified by *which* to fire after *seconds* (float is accepted, different from [`alarm()`](#signal.alarm "signal.alarm")) and after that every *interval* seconds (if *interval* is non-zero). The interval timer specified by *which* can be cleared by setting *seconds* to zero. When an interval timer fires, a signal is sent to the process. The signal sent is dependent on the timer being used; [`signal.ITIMER_REAL`](#signal.ITIMER_REAL "signal.ITIMER_REAL") will deliver [`SIGALRM`](#signal.SIGALRM "signal.SIGALRM"), [`signal.ITIMER_VIRTUAL`](#signal.ITIMER_VIRTUAL "signal.ITIMER_VIRTUAL") sends `SIGVTALRM`, and [`signal.ITIMER_PROF`](#signal.ITIMER_PROF "signal.ITIMER_PROF") will deliver `SIGPROF`. The old values are returned as a tuple: (delay, interval). Attempting to pass an invalid interval timer will cause an [`ItimerError`](#signal.ItimerError "signal.ItimerError"). [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix. `signal.getitimer(which)` Returns current value of a given interval timer specified by *which*. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix. `signal.set_wakeup_fd(fd, *, warn_on_full_buffer=True)` Set the wakeup file descriptor to *fd*. When a signal is received, the signal number is written as a single byte into the fd. This can be used by a library to wakeup a poll or select call, allowing the signal to be fully processed. The old wakeup fd is returned (or -1 if file descriptor wakeup was not enabled). If *fd* is -1, file descriptor wakeup is disabled. If not -1, *fd* must be non-blocking. It is up to the library to remove any bytes from *fd* before calling poll or select again. When threads are enabled, this function can only be called from [the main thread of the main interpreter](#signals-and-threads); attempting to call it from other threads will cause a [`ValueError`](exceptions#ValueError "ValueError") exception to be raised. There are two common ways to use this function. In both approaches, you use the fd to wake up when a signal arrives, but then they differ in how they determine *which* signal or signals have arrived. In the first approach, we read the data out of the fd’s buffer, and the byte values give you the signal numbers. This is simple, but in rare cases it can run into a problem: generally the fd will have a limited amount of buffer space, and if too many signals arrive too quickly, then the buffer may become full, and some signals may be lost. If you use this approach, then you should set `warn_on_full_buffer=True`, which will at least cause a warning to be printed to stderr when signals are lost. In the second approach, we use the wakeup fd *only* for wakeups, and ignore the actual byte values. In this case, all we care about is whether the fd’s buffer is empty or non-empty; a full buffer doesn’t indicate a problem at all. If you use this approach, then you should set `warn_on_full_buffer=False`, so that your users are not confused by spurious warning messages. Changed in version 3.5: On Windows, the function now also supports socket handles. Changed in version 3.7: Added `warn_on_full_buffer` parameter. `signal.siginterrupt(signalnum, flag)` Change system call restart behaviour: if *flag* is [`False`](constants#False "False"), system calls will be restarted when interrupted by signal *signalnum*, otherwise system calls will be interrupted. Returns nothing. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix. See the man page *[siginterrupt(3)](https://manpages.debian.org/siginterrupt(3))* for further information. Note that installing a signal handler with [`signal()`](#module-signal "signal: Set handlers for asynchronous events.") will reset the restart behaviour to interruptible by implicitly calling `siginterrupt()` with a true *flag* value for the given signal. `signal.signal(signalnum, handler)` Set the handler for signal *signalnum* to the function *handler*. *handler* can be a callable Python object taking two arguments (see below), or one of the special values [`signal.SIG_IGN`](#signal.SIG_IGN "signal.SIG_IGN") or [`signal.SIG_DFL`](#signal.SIG_DFL "signal.SIG_DFL"). The previous signal handler will be returned (see the description of [`getsignal()`](#signal.getsignal "signal.getsignal") above). (See the Unix man page *[signal(2)](https://manpages.debian.org/signal(2))* for further information.) When threads are enabled, this function can only be called from [the main thread of the main interpreter](#signals-and-threads); attempting to call it from other threads will cause a [`ValueError`](exceptions#ValueError "ValueError") exception to be raised. The *handler* is called with two arguments: the signal number and the current stack frame (`None` or a frame object; for a description of frame objects, see the [description in the type hierarchy](../reference/datamodel#frame-objects) or see the attribute descriptions in the [`inspect`](inspect#module-inspect "inspect: Extract information and source code from live objects.") module). On Windows, [`signal()`](#module-signal "signal: Set handlers for asynchronous events.") can only be called with [`SIGABRT`](#signal.SIGABRT "signal.SIGABRT"), [`SIGFPE`](#signal.SIGFPE "signal.SIGFPE"), [`SIGILL`](#signal.SIGILL "signal.SIGILL"), [`SIGINT`](#signal.SIGINT "signal.SIGINT"), [`SIGSEGV`](#signal.SIGSEGV "signal.SIGSEGV"), [`SIGTERM`](#signal.SIGTERM "signal.SIGTERM"), or [`SIGBREAK`](#signal.SIGBREAK "signal.SIGBREAK"). A [`ValueError`](exceptions#ValueError "ValueError") will be raised in any other case. Note that not all systems define the same set of signal names; an [`AttributeError`](exceptions#AttributeError "AttributeError") will be raised if a signal name is not defined as `SIG*` module level constant. `signal.sigpending()` Examine the set of signals that are pending for delivery to the calling thread (i.e., the signals which have been raised while blocked). Return the set of the pending signals. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix. See the man page *[sigpending(2)](https://manpages.debian.org/sigpending(2))* for further information. See also [`pause()`](#signal.pause "signal.pause"), [`pthread_sigmask()`](#signal.pthread_sigmask "signal.pthread_sigmask") and [`sigwait()`](#signal.sigwait "signal.sigwait"). New in version 3.3. `signal.sigwait(sigset)` Suspend execution of the calling thread until the delivery of one of the signals specified in the signal set *sigset*. The function accepts the signal (removes it from the pending list of signals), and returns the signal number. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix. See the man page *[sigwait(3)](https://manpages.debian.org/sigwait(3))* for further information. See also [`pause()`](#signal.pause "signal.pause"), [`pthread_sigmask()`](#signal.pthread_sigmask "signal.pthread_sigmask"), [`sigpending()`](#signal.sigpending "signal.sigpending"), [`sigwaitinfo()`](#signal.sigwaitinfo "signal.sigwaitinfo") and [`sigtimedwait()`](#signal.sigtimedwait "signal.sigtimedwait"). New in version 3.3. `signal.sigwaitinfo(sigset)` Suspend execution of the calling thread until the delivery of one of the signals specified in the signal set *sigset*. The function accepts the signal and removes it from the pending list of signals. If one of the signals in *sigset* is already pending for the calling thread, the function will return immediately with information about that signal. The signal handler is not called for the delivered signal. The function raises an [`InterruptedError`](exceptions#InterruptedError "InterruptedError") if it is interrupted by a signal that is not in *sigset*. The return value is an object representing the data contained in the `siginfo_t` structure, namely: `si_signo`, `si_code`, `si_errno`, `si_pid`, `si_uid`, `si_status`, `si_band`. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix. See the man page *[sigwaitinfo(2)](https://manpages.debian.org/sigwaitinfo(2))* for further information. See also [`pause()`](#signal.pause "signal.pause"), [`sigwait()`](#signal.sigwait "signal.sigwait") and [`sigtimedwait()`](#signal.sigtimedwait "signal.sigtimedwait"). New in version 3.3. Changed in version 3.5: The function is now retried if interrupted by a signal not in *sigset* and the signal handler does not raise an exception (see [**PEP 475**](https://www.python.org/dev/peps/pep-0475) for the rationale). `signal.sigtimedwait(sigset, timeout)` Like [`sigwaitinfo()`](#signal.sigwaitinfo "signal.sigwaitinfo"), but takes an additional *timeout* argument specifying a timeout. If *timeout* is specified as `0`, a poll is performed. Returns [`None`](constants#None "None") if a timeout occurs. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix. See the man page *[sigtimedwait(2)](https://manpages.debian.org/sigtimedwait(2))* for further information. See also [`pause()`](#signal.pause "signal.pause"), [`sigwait()`](#signal.sigwait "signal.sigwait") and [`sigwaitinfo()`](#signal.sigwaitinfo "signal.sigwaitinfo"). New in version 3.3. Changed in version 3.5: The function is now retried with the recomputed *timeout* if interrupted by a signal not in *sigset* and the signal handler does not raise an exception (see [**PEP 475**](https://www.python.org/dev/peps/pep-0475) for the rationale). Example ------- Here is a minimal example program. It uses the [`alarm()`](#signal.alarm "signal.alarm") function to limit the time spent waiting to open a file; this is useful if the file is for a serial device that may not be turned on, which would normally cause the [`os.open()`](os#os.open "os.open") to hang indefinitely. The solution is to set a 5-second alarm before opening the file; if the operation takes too long, the alarm signal will be sent, and the handler raises an exception. ``` import signal, os def handler(signum, frame): print('Signal handler called with signal', signum) raise OSError("Couldn't open device!") # Set the signal handler and a 5-second alarm signal.signal(signal.SIGALRM, handler) signal.alarm(5) # This open() may hang indefinitely fd = os.open('/dev/ttyS0', os.O_RDWR) signal.alarm(0) # Disable the alarm ``` Note on SIGPIPE --------------- Piping output of your program to tools like *[head(1)](https://manpages.debian.org/head(1))* will cause a [`SIGPIPE`](#signal.SIGPIPE "signal.SIGPIPE") signal to be sent to your process when the receiver of its standard output closes early. This results in an exception like `BrokenPipeError: [Errno 32] Broken pipe`. To handle this case, wrap your entry point to catch this exception as follows: ``` import os import sys def main(): try: # simulate large output (your code replaces this loop) for x in range(10000): print("y") # flush output here to force SIGPIPE to be triggered # while inside this try block. sys.stdout.flush() except BrokenPipeError: # Python flushes standard streams on exit; redirect remaining output # to devnull to avoid another BrokenPipeError at shutdown devnull = os.open(os.devnull, os.O_WRONLY) os.dup2(devnull, sys.stdout.fileno()) sys.exit(1) # Python exits with error code 1 on EPIPE if __name__ == '__main__': main() ``` Do not set [`SIGPIPE`](#signal.SIGPIPE "signal.SIGPIPE")’s disposition to [`SIG_DFL`](#signal.SIG_DFL "signal.SIG_DFL") in order to avoid [`BrokenPipeError`](exceptions#BrokenPipeError "BrokenPipeError"). Doing that would cause your program to exit unexpectedly whenever any socket connection is interrupted while your program is still writing to it. Note on Signal Handlers and Exceptions -------------------------------------- If a signal handler raises an exception, the exception will be propagated to the main thread and may be raised after any [bytecode](../glossary#term-bytecode) instruction. Most notably, a [`KeyboardInterrupt`](exceptions#KeyboardInterrupt "KeyboardInterrupt") may appear at any point during execution. Most Python code, including the standard library, cannot be made robust against this, and so a [`KeyboardInterrupt`](exceptions#KeyboardInterrupt "KeyboardInterrupt") (or any other exception resulting from a signal handler) may on rare occasions put the program in an unexpected state. To illustrate this issue, consider the following code: ``` class SpamContext: def __init__(self): self.lock = threading.Lock() def __enter__(self): # If KeyboardInterrupt occurs here, everything is fine self.lock.acquire() # If KeyboardInterrupt occcurs here, __exit__ will not be called ... # KeyboardInterrupt could occur just before the function returns def __exit__(self, exc_type, exc_val, exc_tb): ... self.lock.release() ``` For many programs, especially those that merely want to exit on [`KeyboardInterrupt`](exceptions#KeyboardInterrupt "KeyboardInterrupt"), this is not a problem, but applications that are complex or require high reliability should avoid raising exceptions from signal handlers. They should also avoid catching [`KeyboardInterrupt`](exceptions#KeyboardInterrupt "KeyboardInterrupt") as a means of gracefully shutting down. Instead, they should install their own [`SIGINT`](#signal.SIGINT "signal.SIGINT") handler. Below is an example of an HTTP server that avoids [`KeyboardInterrupt`](exceptions#KeyboardInterrupt "KeyboardInterrupt"): ``` import signal import socket from selectors import DefaultSelector, EVENT_READ from http.server import HTTPServer, SimpleHTTPRequestHandler interrupt_read, interrupt_write = socket.socketpair() def handler(signum, frame): print('Signal handler called with signal', signum) interrupt_write.send(b'\0') signal.signal(signal.SIGINT, handler) def serve_forever(httpd): sel = DefaultSelector() sel.register(interrupt_read, EVENT_READ) sel.register(httpd, EVENT_READ) while True: for key, _ in sel.select(): if key.fileobj == interrupt_read: interrupt_read.recv(1) return if key.fileobj == httpd: httpd.handle_request() print("Serving on port 8000") httpd = HTTPServer(('', 8000), SimpleHTTPRequestHandler) serve_forever(httpd) print("Shutdown...") ```
programming_docs
python Networking and Interprocess Communication Networking and Interprocess Communication ========================================= The modules described in this chapter provide mechanisms for networking and inter-processes communication. Some modules only work for two processes that are on the same machine, e.g. [`signal`](signal#module-signal "signal: Set handlers for asynchronous events.") and [`mmap`](mmap#module-mmap "mmap: Interface to memory-mapped files for Unix and Windows."). Other modules support networking protocols that two or more processes can use to communicate across machines. The list of modules described in this chapter is: * [`asyncio` — Asynchronous I/O](asyncio) * [`socket` — Low-level networking interface](socket) * [`ssl` — TLS/SSL wrapper for socket objects](ssl) * [`select` — Waiting for I/O completion](select) * [`selectors` — High-level I/O multiplexing](selectors) * [`signal` — Set handlers for asynchronous events](signal) * [`mmap` — Memory-mapped file support](mmap) python xmlrpc.client — XML-RPC client access xmlrpc.client — XML-RPC client access ===================================== **Source code:** [Lib/xmlrpc/client.py](https://github.com/python/cpython/tree/3.9/Lib/xmlrpc/client.py) XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP(S) as a transport. With it, a client can call methods with parameters on a remote server (the server is named by a URI) and get back structured data. This module supports writing XML-RPC client code; it handles all the details of translating between conformable Python objects and XML on the wire. Warning The [`xmlrpc.client`](#module-xmlrpc.client "xmlrpc.client: XML-RPC client access.") module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data see [XML vulnerabilities](xml#xml-vulnerabilities). Changed in version 3.5: For HTTPS URIs, [`xmlrpc.client`](#module-xmlrpc.client "xmlrpc.client: XML-RPC client access.") now performs all the necessary certificate and hostname checks by default. `class xmlrpc.client.ServerProxy(uri, transport=None, encoding=None, verbose=False, allow_none=False, use_datetime=False, use_builtin_types=False, *, headers=(), context=None)` A [`ServerProxy`](#xmlrpc.client.ServerProxy "xmlrpc.client.ServerProxy") instance is an object that manages communication with a remote XML-RPC server. The required first argument is a URI (Uniform Resource Indicator), and will normally be the URL of the server. The optional second argument is a transport factory instance; by default it is an internal `SafeTransport` instance for https: URLs and an internal HTTP `Transport` instance otherwise. The optional third argument is an encoding, by default UTF-8. The optional fourth argument is a debugging flag. The following parameters govern the use of the returned proxy instance. If *allow\_none* is true, the Python constant `None` will be translated into XML; the default behaviour is for `None` to raise a [`TypeError`](exceptions#TypeError "TypeError"). This is a commonly-used extension to the XML-RPC specification, but isn’t supported by all clients and servers; see [http://ontosys.com/xml-rpc/extensions.php](https://web.archive.org/web/20130120074804/http://ontosys.com/xml-rpc/extensions.php) for a description. The *use\_builtin\_types* flag can be used to cause date/time values to be presented as [`datetime.datetime`](datetime#datetime.datetime "datetime.datetime") objects and binary data to be presented as [`bytes`](stdtypes#bytes "bytes") objects; this flag is false by default. [`datetime.datetime`](datetime#datetime.datetime "datetime.datetime"), [`bytes`](stdtypes#bytes "bytes") and [`bytearray`](stdtypes#bytearray "bytearray") objects may be passed to calls. The *headers* parameter is an optional sequence of HTTP headers to send with each request, expressed as a sequence of 2-tuples representing the header name and value. (e.g. `[(‘Header-Name’, ‘value’)]`). The obsolete *use\_datetime* flag is similar to *use\_builtin\_types* but it applies only to date/time values. Changed in version 3.3: The *use\_builtin\_types* flag was added. Changed in version 3.8: The *headers* parameter was added. Both the HTTP and HTTPS transports support the URL syntax extension for HTTP Basic Authentication: `http://user:pass@host:port/path`. The `user:pass` portion will be base64-encoded as an HTTP ‘Authorization’ header, and sent to the remote server as part of the connection process when invoking an XML-RPC method. You only need to use this if the remote server requires a Basic Authentication user and password. If an HTTPS URL is provided, *context* may be [`ssl.SSLContext`](ssl#ssl.SSLContext "ssl.SSLContext") and configures the SSL settings of the underlying HTTPS connection. The returned instance is a proxy object with methods that can be used to invoke corresponding RPC calls on the remote server. If the remote server supports the introspection API, the proxy can also be used to query the remote server for the methods it supports (service discovery) and fetch other server-associated metadata. Types that are conformable (e.g. that can be marshalled through XML), include the following (and except where noted, they are unmarshalled as the same Python type): | XML-RPC type | Python type | | --- | --- | | `boolean` | [`bool`](functions#bool "bool") | | `int`, `i1`, `i2`, `i4`, `i8` or `biginteger` | [`int`](functions#int "int") in range from -2147483648 to 2147483647. Values get the `<int>` tag. | | `double` or `float` | [`float`](functions#float "float"). Values get the `<double>` tag. | | `string` | [`str`](stdtypes#str "str") | | `array` | [`list`](stdtypes#list "list") or [`tuple`](stdtypes#tuple "tuple") containing conformable elements. Arrays are returned as [`lists`](stdtypes#list "list"). | | `struct` | [`dict`](stdtypes#dict "dict"). Keys must be strings, values may be any conformable type. Objects of user-defined classes can be passed in; only their [`__dict__`](stdtypes#object.__dict__ "object.__dict__") attribute is transmitted. | | `dateTime.iso8601` | [`DateTime`](#xmlrpc.client.DateTime "xmlrpc.client.DateTime") or [`datetime.datetime`](datetime#datetime.datetime "datetime.datetime"). Returned type depends on values of *use\_builtin\_types* and *use\_datetime* flags. | | `base64` | [`Binary`](#xmlrpc.client.Binary "xmlrpc.client.Binary"), [`bytes`](stdtypes#bytes "bytes") or [`bytearray`](stdtypes#bytearray "bytearray"). Returned type depends on the value of the *use\_builtin\_types* flag. | | `nil` | The `None` constant. Passing is allowed only if *allow\_none* is true. | | `bigdecimal` | [`decimal.Decimal`](decimal#decimal.Decimal "decimal.Decimal"). Returned type only. | This is the full set of data types supported by XML-RPC. Method calls may also raise a special [`Fault`](#xmlrpc.client.Fault "xmlrpc.client.Fault") instance, used to signal XML-RPC server errors, or [`ProtocolError`](#xmlrpc.client.ProtocolError "xmlrpc.client.ProtocolError") used to signal an error in the HTTP/HTTPS transport layer. Both [`Fault`](#xmlrpc.client.Fault "xmlrpc.client.Fault") and [`ProtocolError`](#xmlrpc.client.ProtocolError "xmlrpc.client.ProtocolError") derive from a base class called `Error`. Note that the xmlrpc client module currently does not marshal instances of subclasses of built-in types. When passing strings, characters special to XML such as `<`, `>`, and `&` will be automatically escaped. However, it’s the caller’s responsibility to ensure that the string is free of characters that aren’t allowed in XML, such as the control characters with ASCII values between 0 and 31 (except, of course, tab, newline and carriage return); failing to do this will result in an XML-RPC request that isn’t well-formed XML. If you have to pass arbitrary bytes via XML-RPC, use [`bytes`](stdtypes#bytes "bytes") or [`bytearray`](stdtypes#bytearray "bytearray") classes or the [`Binary`](#xmlrpc.client.Binary "xmlrpc.client.Binary") wrapper class described below. `Server` is retained as an alias for [`ServerProxy`](#xmlrpc.client.ServerProxy "xmlrpc.client.ServerProxy") for backwards compatibility. New code should use [`ServerProxy`](#xmlrpc.client.ServerProxy "xmlrpc.client.ServerProxy"). Changed in version 3.5: Added the *context* argument. Changed in version 3.6: Added support of type tags with prefixes (e.g. `ex:nil`). Added support of unmarshalling additional types used by Apache XML-RPC implementation for numerics: `i1`, `i2`, `i8`, `biginteger`, `float` and `bigdecimal`. See <http://ws.apache.org/xmlrpc/types.html> for a description. See also [XML-RPC HOWTO](http://www.tldp.org/HOWTO/XML-RPC-HOWTO/index.html) A good description of XML-RPC operation and client software in several languages. Contains pretty much everything an XML-RPC client developer needs to know. [XML-RPC Introspection](http://xmlrpc-c.sourceforge.net/introspection.html) Describes the XML-RPC protocol extension for introspection. [XML-RPC Specification](http://xmlrpc.scripting.com/spec.html) The official specification. ServerProxy Objects ------------------- A [`ServerProxy`](#xmlrpc.client.ServerProxy "xmlrpc.client.ServerProxy") instance has a method corresponding to each remote procedure call accepted by the XML-RPC server. Calling the method performs an RPC, dispatched by both name and argument signature (e.g. the same method name can be overloaded with multiple argument signatures). The RPC finishes by returning a value, which may be either returned data in a conformant type or a [`Fault`](#xmlrpc.client.Fault "xmlrpc.client.Fault") or [`ProtocolError`](#xmlrpc.client.ProtocolError "xmlrpc.client.ProtocolError") object indicating an error. Servers that support the XML introspection API support some common methods grouped under the reserved `system` attribute: `ServerProxy.system.listMethods()` This method returns a list of strings, one for each (non-system) method supported by the XML-RPC server. `ServerProxy.system.methodSignature(name)` This method takes one parameter, the name of a method implemented by the XML-RPC server. It returns an array of possible signatures for this method. A signature is an array of types. The first of these types is the return type of the method, the rest are parameters. Because multiple signatures (ie. overloading) is permitted, this method returns a list of signatures rather than a singleton. Signatures themselves are restricted to the top level parameters expected by a method. For instance if a method expects one array of structs as a parameter, and it returns a string, its signature is simply “string, array”. If it expects three integers and returns a string, its signature is “string, int, int, int”. If no signature is defined for the method, a non-array value is returned. In Python this means that the type of the returned value will be something other than list. `ServerProxy.system.methodHelp(name)` This method takes one parameter, the name of a method implemented by the XML-RPC server. It returns a documentation string describing the use of that method. If no such string is available, an empty string is returned. The documentation string may contain HTML markup. Changed in version 3.5: Instances of [`ServerProxy`](#xmlrpc.client.ServerProxy "xmlrpc.client.ServerProxy") support the [context manager](../glossary#term-context-manager) protocol for closing the underlying transport. A working example follows. The server code: ``` from xmlrpc.server import SimpleXMLRPCServer def is_even(n): return n % 2 == 0 server = SimpleXMLRPCServer(("localhost", 8000)) print("Listening on port 8000...") server.register_function(is_even, "is_even") server.serve_forever() ``` The client code for the preceding server: ``` import xmlrpc.client with xmlrpc.client.ServerProxy("http://localhost:8000/") as proxy: print("3 is even: %s" % str(proxy.is_even(3))) print("100 is even: %s" % str(proxy.is_even(100))) ``` DateTime Objects ---------------- `class xmlrpc.client.DateTime` This class may be initialized with seconds since the epoch, a time tuple, an ISO 8601 time/date string, or a [`datetime.datetime`](datetime#datetime.datetime "datetime.datetime") instance. It has the following methods, supported mainly for internal use by the marshalling/unmarshalling code: `decode(string)` Accept a string as the instance’s new time value. `encode(out)` Write the XML-RPC encoding of this [`DateTime`](#xmlrpc.client.DateTime "xmlrpc.client.DateTime") item to the *out* stream object. It also supports certain of Python’s built-in operators through rich comparison and [`__repr__()`](../reference/datamodel#object.__repr__ "object.__repr__") methods. A working example follows. The server code: ``` import datetime from xmlrpc.server import SimpleXMLRPCServer import xmlrpc.client def today(): today = datetime.datetime.today() return xmlrpc.client.DateTime(today) server = SimpleXMLRPCServer(("localhost", 8000)) print("Listening on port 8000...") server.register_function(today, "today") server.serve_forever() ``` The client code for the preceding server: ``` import xmlrpc.client import datetime proxy = xmlrpc.client.ServerProxy("http://localhost:8000/") today = proxy.today() # convert the ISO8601 string to a datetime object converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S") print("Today: %s" % converted.strftime("%d.%m.%Y, %H:%M")) ``` Binary Objects -------------- `class xmlrpc.client.Binary` This class may be initialized from bytes data (which may include NULs). The primary access to the content of a [`Binary`](#xmlrpc.client.Binary "xmlrpc.client.Binary") object is provided by an attribute: `data` The binary data encapsulated by the [`Binary`](#xmlrpc.client.Binary "xmlrpc.client.Binary") instance. The data is provided as a [`bytes`](stdtypes#bytes "bytes") object. [`Binary`](#xmlrpc.client.Binary "xmlrpc.client.Binary") objects have the following methods, supported mainly for internal use by the marshalling/unmarshalling code: `decode(bytes)` Accept a base64 [`bytes`](stdtypes#bytes "bytes") object and decode it as the instance’s new data. `encode(out)` Write the XML-RPC base 64 encoding of this binary item to the *out* stream object. The encoded data will have newlines every 76 characters as per [**RFC 2045 section 6.8**](https://tools.ietf.org/html/rfc2045.html#section-6.8), which was the de facto standard base64 specification when the XML-RPC spec was written. It also supports certain of Python’s built-in operators through [`__eq__()`](../reference/datamodel#object.__eq__ "object.__eq__") and [`__ne__()`](../reference/datamodel#object.__ne__ "object.__ne__") methods. Example usage of the binary objects. We’re going to transfer an image over XMLRPC: ``` from xmlrpc.server import SimpleXMLRPCServer import xmlrpc.client def python_logo(): with open("python_logo.jpg", "rb") as handle: return xmlrpc.client.Binary(handle.read()) server = SimpleXMLRPCServer(("localhost", 8000)) print("Listening on port 8000...") server.register_function(python_logo, 'python_logo') server.serve_forever() ``` The client gets the image and saves it to a file: ``` import xmlrpc.client proxy = xmlrpc.client.ServerProxy("http://localhost:8000/") with open("fetched_python_logo.jpg", "wb") as handle: handle.write(proxy.python_logo().data) ``` Fault Objects ------------- `class xmlrpc.client.Fault` A [`Fault`](#xmlrpc.client.Fault "xmlrpc.client.Fault") object encapsulates the content of an XML-RPC fault tag. Fault objects have the following attributes: `faultCode` A string indicating the fault type. `faultString` A string containing a diagnostic message associated with the fault. In the following example we’re going to intentionally cause a [`Fault`](#xmlrpc.client.Fault "xmlrpc.client.Fault") by returning a complex type object. The server code: ``` from xmlrpc.server import SimpleXMLRPCServer # A marshalling error is going to occur because we're returning a # complex number def add(x, y): return x+y+0j server = SimpleXMLRPCServer(("localhost", 8000)) print("Listening on port 8000...") server.register_function(add, 'add') server.serve_forever() ``` The client code for the preceding server: ``` import xmlrpc.client proxy = xmlrpc.client.ServerProxy("http://localhost:8000/") try: proxy.add(2, 5) except xmlrpc.client.Fault as err: print("A fault occurred") print("Fault code: %d" % err.faultCode) print("Fault string: %s" % err.faultString) ``` ProtocolError Objects --------------------- `class xmlrpc.client.ProtocolError` A [`ProtocolError`](#xmlrpc.client.ProtocolError "xmlrpc.client.ProtocolError") object describes a protocol error in the underlying transport layer (such as a 404 ‘not found’ error if the server named by the URI does not exist). It has the following attributes: `url` The URI or URL that triggered the error. `errcode` The error code. `errmsg` The error message or diagnostic string. `headers` A dict containing the headers of the HTTP/HTTPS request that triggered the error. In the following example we’re going to intentionally cause a [`ProtocolError`](#xmlrpc.client.ProtocolError "xmlrpc.client.ProtocolError") by providing an invalid URI: ``` import xmlrpc.client # create a ServerProxy with a URI that doesn't respond to XMLRPC requests proxy = xmlrpc.client.ServerProxy("http://google.com/") try: proxy.some_method() except xmlrpc.client.ProtocolError as err: print("A protocol error occurred") print("URL: %s" % err.url) print("HTTP/HTTPS headers: %s" % err.headers) print("Error code: %d" % err.errcode) print("Error message: %s" % err.errmsg) ``` MultiCall Objects ----------------- The [`MultiCall`](#xmlrpc.client.MultiCall "xmlrpc.client.MultiCall") object provides a way to encapsulate multiple calls to a remote server into a single request [1](#id6). `class xmlrpc.client.MultiCall(server)` Create an object used to boxcar method calls. *server* is the eventual target of the call. Calls can be made to the result object, but they will immediately return `None`, and only store the call name and parameters in the [`MultiCall`](#xmlrpc.client.MultiCall "xmlrpc.client.MultiCall") object. Calling the object itself causes all stored calls to be transmitted as a single `system.multicall` request. The result of this call is a [generator](../glossary#term-generator); iterating over this generator yields the individual results. A usage example of this class follows. The server code: ``` from xmlrpc.server import SimpleXMLRPCServer def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x // y # A simple server with simple arithmetic functions server = SimpleXMLRPCServer(("localhost", 8000)) print("Listening on port 8000...") server.register_multicall_functions() server.register_function(add, 'add') server.register_function(subtract, 'subtract') server.register_function(multiply, 'multiply') server.register_function(divide, 'divide') server.serve_forever() ``` The client code for the preceding server: ``` import xmlrpc.client proxy = xmlrpc.client.ServerProxy("http://localhost:8000/") multicall = xmlrpc.client.MultiCall(proxy) multicall.add(7, 3) multicall.subtract(7, 3) multicall.multiply(7, 3) multicall.divide(7, 3) result = multicall() print("7+3=%d, 7-3=%d, 7*3=%d, 7//3=%d" % tuple(result)) ``` Convenience Functions --------------------- `xmlrpc.client.dumps(params, methodname=None, methodresponse=None, encoding=None, allow_none=False)` Convert *params* into an XML-RPC request. or into a response if *methodresponse* is true. *params* can be either a tuple of arguments or an instance of the [`Fault`](#xmlrpc.client.Fault "xmlrpc.client.Fault") exception class. If *methodresponse* is true, only a single value can be returned, meaning that *params* must be of length 1. *encoding*, if supplied, is the encoding to use in the generated XML; the default is UTF-8. Python’s [`None`](constants#None "None") value cannot be used in standard XML-RPC; to allow using it via an extension, provide a true value for *allow\_none*. `xmlrpc.client.loads(data, use_datetime=False, use_builtin_types=False)` Convert an XML-RPC request or response into Python objects, a `(params, methodname)`. *params* is a tuple of argument; *methodname* is a string, or `None` if no method name is present in the packet. If the XML-RPC packet represents a fault condition, this function will raise a [`Fault`](#xmlrpc.client.Fault "xmlrpc.client.Fault") exception. The *use\_builtin\_types* flag can be used to cause date/time values to be presented as [`datetime.datetime`](datetime#datetime.datetime "datetime.datetime") objects and binary data to be presented as [`bytes`](stdtypes#bytes "bytes") objects; this flag is false by default. The obsolete *use\_datetime* flag is similar to *use\_builtin\_types* but it applies only to date/time values. Changed in version 3.3: The *use\_builtin\_types* flag was added. Example of Client Usage ----------------------- ``` # simple test program (from the XML-RPC specification) from xmlrpc.client import ServerProxy, Error # server = ServerProxy("http://localhost:8000") # local server with ServerProxy("http://betty.userland.com") as proxy: print(proxy) try: print(proxy.examples.getStateName(41)) except Error as v: print("ERROR", v) ``` To access an XML-RPC server through a HTTP proxy, you need to define a custom transport. The following example shows how: ``` import http.client import xmlrpc.client class ProxiedTransport(xmlrpc.client.Transport): def set_proxy(self, host, port=None, headers=None): self.proxy = host, port self.proxy_headers = headers def make_connection(self, host): connection = http.client.HTTPConnection(*self.proxy) connection.set_tunnel(host, headers=self.proxy_headers) self._connection = host, connection return connection transport = ProxiedTransport() transport.set_proxy('proxy-server', 8080) server = xmlrpc.client.ServerProxy('http://betty.userland.com', transport=transport) print(server.examples.getStateName(41)) ``` Example of Client and Server Usage ---------------------------------- See [SimpleXMLRPCServer Example](xmlrpc.server#simplexmlrpcserver-example). #### Footnotes `1` This approach has been first presented in [a discussion on xmlrpc.com](https://web.archive.org/web/20060624230303/http://www.xmlrpc.com/discuss/msgReader%241208?mode=topic).
programming_docs
python xml.dom.pulldom — Support for building partial DOM trees xml.dom.pulldom — Support for building partial DOM trees ======================================================== **Source code:** [Lib/xml/dom/pulldom.py](https://github.com/python/cpython/tree/3.9/Lib/xml/dom/pulldom.py) The [`xml.dom.pulldom`](#module-xml.dom.pulldom "xml.dom.pulldom: Support for building partial DOM trees from SAX events.") module provides a “pull parser” which can also be asked to produce DOM-accessible fragments of the document where necessary. The basic concept involves pulling “events” from a stream of incoming XML and processing them. In contrast to SAX which also employs an event-driven processing model together with callbacks, the user of a pull parser is responsible for explicitly pulling events from the stream, looping over those events until either processing is finished or an error condition occurs. Warning The [`xml.dom.pulldom`](#module-xml.dom.pulldom "xml.dom.pulldom: Support for building partial DOM trees from SAX events.") module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data see [XML vulnerabilities](xml#xml-vulnerabilities). Changed in version 3.7.1: The SAX parser no longer processes general external entities by default to increase security by default. To enable processing of external entities, pass a custom parser instance in: ``` from xml.dom.pulldom import parse from xml.sax import make_parser from xml.sax.handler import feature_external_ges parser = make_parser() parser.setFeature(feature_external_ges, True) parse(filename, parser=parser) ``` Example: ``` from xml.dom import pulldom doc = pulldom.parse('sales_items.xml') for event, node in doc: if event == pulldom.START_ELEMENT and node.tagName == 'item': if int(node.getAttribute('price')) > 50: doc.expandNode(node) print(node.toxml()) ``` `event` is a constant and can be one of: * `START_ELEMENT` * `END_ELEMENT` * `COMMENT` * `START_DOCUMENT` * `END_DOCUMENT` * `CHARACTERS` * `PROCESSING_INSTRUCTION` * `IGNORABLE_WHITESPACE` `node` is an object of type `xml.dom.minidom.Document`, `xml.dom.minidom.Element` or `xml.dom.minidom.Text`. Since the document is treated as a “flat” stream of events, the document “tree” is implicitly traversed and the desired elements are found regardless of their depth in the tree. In other words, one does not need to consider hierarchical issues such as recursive searching of the document nodes, although if the context of elements were important, one would either need to maintain some context-related state (i.e. remembering where one is in the document at any given point) or to make use of the [`DOMEventStream.expandNode()`](#xml.dom.pulldom.DOMEventStream.expandNode "xml.dom.pulldom.DOMEventStream.expandNode") method and switch to DOM-related processing. `class xml.dom.pulldom.PullDom(documentFactory=None)` Subclass of [`xml.sax.handler.ContentHandler`](xml.sax.handler#xml.sax.handler.ContentHandler "xml.sax.handler.ContentHandler"). `class xml.dom.pulldom.SAX2DOM(documentFactory=None)` Subclass of [`xml.sax.handler.ContentHandler`](xml.sax.handler#xml.sax.handler.ContentHandler "xml.sax.handler.ContentHandler"). `xml.dom.pulldom.parse(stream_or_string, parser=None, bufsize=None)` Return a [`DOMEventStream`](#xml.dom.pulldom.DOMEventStream "xml.dom.pulldom.DOMEventStream") from the given input. *stream\_or\_string* may be either a file name, or a file-like object. *parser*, if given, must be an [`XMLReader`](xml.sax.reader#xml.sax.xmlreader.XMLReader "xml.sax.xmlreader.XMLReader") object. This function will change the document handler of the parser and activate namespace support; other parser configuration (like setting an entity resolver) must have been done in advance. If you have XML in a string, you can use the [`parseString()`](#xml.dom.pulldom.parseString "xml.dom.pulldom.parseString") function instead: `xml.dom.pulldom.parseString(string, parser=None)` Return a [`DOMEventStream`](#xml.dom.pulldom.DOMEventStream "xml.dom.pulldom.DOMEventStream") that represents the (Unicode) *string*. `xml.dom.pulldom.default_bufsize` Default value for the *bufsize* parameter to [`parse()`](#xml.dom.pulldom.parse "xml.dom.pulldom.parse"). The value of this variable can be changed before calling [`parse()`](#xml.dom.pulldom.parse "xml.dom.pulldom.parse") and the new value will take effect. DOMEventStream Objects ---------------------- `class xml.dom.pulldom.DOMEventStream(stream, parser, bufsize)` Deprecated since version 3.8: Support for [`sequence protocol`](../reference/datamodel#object.__getitem__ "object.__getitem__") is deprecated. `getEvent()` Return a tuple containing *event* and the current *node* as `xml.dom.minidom.Document` if event equals `START_DOCUMENT`, `xml.dom.minidom.Element` if event equals `START_ELEMENT` or `END_ELEMENT` or `xml.dom.minidom.Text` if event equals `CHARACTERS`. The current node does not contain information about its children, unless [`expandNode()`](#xml.dom.pulldom.DOMEventStream.expandNode "xml.dom.pulldom.DOMEventStream.expandNode") is called. `expandNode(node)` Expands all children of *node* into *node*. Example: ``` from xml.dom import pulldom xml = '<html><title>Foo</title> <p>Some text <div>and more</div></p> </html>' doc = pulldom.parseString(xml) for event, node in doc: if event == pulldom.START_ELEMENT and node.tagName == 'p': # Following statement only prints '<p/>' print(node.toxml()) doc.expandNode(node) # Following statement prints node with all its children '<p>Some text <div>and more</div></p>' print(node.toxml()) ``` `reset()` python sys — System-specific parameters and functions sys — System-specific parameters and functions ============================================== This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available. `sys.abiflags` On POSIX systems where Python was built with the standard `configure` script, this contains the ABI flags as specified by [**PEP 3149**](https://www.python.org/dev/peps/pep-3149). Changed in version 3.8: Default flags became an empty string (`m` flag for pymalloc has been removed). New in version 3.2. `sys.addaudithook(hook)` Append the callable *hook* to the list of active auditing hooks for the current (sub)interpreter. When an auditing event is raised through the [`sys.audit()`](#sys.audit "sys.audit") function, each hook will be called in the order it was added with the event name and the tuple of arguments. Native hooks added by [`PySys_AddAuditHook()`](../c-api/sys#c.PySys_AddAuditHook "PySys_AddAuditHook") are called first, followed by hooks added in the current (sub)interpreter. Hooks can then log the event, raise an exception to abort the operation, or terminate the process entirely. Calling [`sys.addaudithook()`](#sys.addaudithook "sys.addaudithook") will itself raise an auditing event named `sys.addaudithook` with no arguments. If any existing hooks raise an exception derived from [`RuntimeError`](exceptions#RuntimeError "RuntimeError"), the new hook will not be added and the exception suppressed. As a result, callers cannot assume that their hook has been added unless they control all existing hooks. See the [audit events table](audit_events#audit-events) for all events raised by CPython, and [**PEP 578**](https://www.python.org/dev/peps/pep-0578) for the original design discussion. New in version 3.8. Changed in version 3.8.1: Exceptions derived from [`Exception`](exceptions#Exception "Exception") but not [`RuntimeError`](exceptions#RuntimeError "RuntimeError") are no longer suppressed. **CPython implementation detail:** When tracing is enabled (see [`settrace()`](#sys.settrace "sys.settrace")), Python hooks are only traced if the callable has a `__cantrace__` member that is set to a true value. Otherwise, trace functions will skip the hook. `sys.argv` The list of command line arguments passed to a Python script. `argv[0]` is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the [`-c`](../using/cmdline#cmdoption-c) command line option to the interpreter, `argv[0]` is set to the string `'-c'`. If no script name was passed to the Python interpreter, `argv[0]` is the empty string. To loop over the standard input, or the list of files given on the command line, see the [`fileinput`](fileinput#module-fileinput "fileinput: Loop over standard input or a list of files.") module. Note On Unix, command line arguments are passed by bytes from OS. Python decodes them with filesystem encoding and “surrogateescape” error handler. When you need original bytes, you can get it by `[os.fsencode(arg) for arg in sys.argv]`. `sys.audit(event, *args)` Raise an auditing event and trigger any active auditing hooks. *event* is a string identifying the event, and *args* may contain optional arguments with more information about the event. The number and types of arguments for a given event are considered a public and stable API and should not be modified between releases. For example, one auditing event is named `os.chdir`. This event has one argument called *path* that will contain the requested new working directory. [`sys.audit()`](#sys.audit "sys.audit") will call the existing auditing hooks, passing the event name and arguments, and will re-raise the first exception from any hook. In general, if an exception is raised, it should not be handled and the process should be terminated as quickly as possible. This allows hook implementations to decide how to respond to particular events: they can merely log the event or abort the operation by raising an exception. Hooks are added using the [`sys.addaudithook()`](#sys.addaudithook "sys.addaudithook") or [`PySys_AddAuditHook()`](../c-api/sys#c.PySys_AddAuditHook "PySys_AddAuditHook") functions. The native equivalent of this function is [`PySys_Audit()`](../c-api/sys#c.PySys_Audit "PySys_Audit"). Using the native function is preferred when possible. See the [audit events table](audit_events#audit-events) for all events raised by CPython. New in version 3.8. `sys.base_exec_prefix` Set during Python startup, before `site.py` is run, to the same value as [`exec_prefix`](#sys.exec_prefix "sys.exec_prefix"). If not running in a [virtual environment](venv#venv-def), the values will stay the same; if `site.py` finds that a virtual environment is in use, the values of [`prefix`](#sys.prefix "sys.prefix") and [`exec_prefix`](#sys.exec_prefix "sys.exec_prefix") will be changed to point to the virtual environment, whereas [`base_prefix`](#sys.base_prefix "sys.base_prefix") and [`base_exec_prefix`](#sys.base_exec_prefix "sys.base_exec_prefix") will remain pointing to the base Python installation (the one which the virtual environment was created from). New in version 3.3. `sys.base_prefix` Set during Python startup, before `site.py` is run, to the same value as [`prefix`](#sys.prefix "sys.prefix"). If not running in a [virtual environment](venv#venv-def), the values will stay the same; if `site.py` finds that a virtual environment is in use, the values of [`prefix`](#sys.prefix "sys.prefix") and [`exec_prefix`](#sys.exec_prefix "sys.exec_prefix") will be changed to point to the virtual environment, whereas [`base_prefix`](#sys.base_prefix "sys.base_prefix") and [`base_exec_prefix`](#sys.base_exec_prefix "sys.base_exec_prefix") will remain pointing to the base Python installation (the one which the virtual environment was created from). New in version 3.3. `sys.byteorder` An indicator of the native byte order. This will have the value `'big'` on big-endian (most-significant byte first) platforms, and `'little'` on little-endian (least-significant byte first) platforms. `sys.builtin_module_names` A tuple of strings giving the names of all modules that are compiled into this Python interpreter. (This information is not available in any other way — `modules.keys()` only lists the imported modules.) `sys.call_tracing(func, args)` Call `func(*args)`, while tracing is enabled. The tracing state is saved, and restored afterwards. This is intended to be called from a debugger from a checkpoint, to recursively debug some other code. `sys.copyright` A string containing the copyright pertaining to the Python interpreter. `sys._clear_type_cache()` Clear the internal type cache. The type cache is used to speed up attribute and method lookups. Use the function *only* to drop unnecessary references during reference leak debugging. This function should be used for internal and specialized purposes only. `sys._current_frames()` Return a dictionary mapping each thread’s identifier to the topmost stack frame currently active in that thread at the time the function is called. Note that functions in the [`traceback`](traceback#module-traceback "traceback: Print or retrieve a stack traceback.") module can build the call stack given such a frame. This is most useful for debugging deadlock: this function does not require the deadlocked threads’ cooperation, and such threads’ call stacks are frozen for as long as they remain deadlocked. The frame returned for a non-deadlocked thread may bear no relationship to that thread’s current activity by the time calling code examines the frame. This function should be used for internal and specialized purposes only. Raises an [auditing event](#auditing) `sys._current_frames` with no arguments. `sys.breakpointhook()` This hook function is called by built-in [`breakpoint()`](functions#breakpoint "breakpoint"). By default, it drops you into the [`pdb`](pdb#module-pdb "pdb: The Python debugger for interactive interpreters.") debugger, but it can be set to any other function so that you can choose which debugger gets used. The signature of this function is dependent on what it calls. For example, the default binding (e.g. `pdb.set_trace()`) expects no arguments, but you might bind it to a function that expects additional arguments (positional and/or keyword). The built-in `breakpoint()` function passes its `*args` and `**kws` straight through. Whatever `breakpointhooks()` returns is returned from `breakpoint()`. The default implementation first consults the environment variable [`PYTHONBREAKPOINT`](../using/cmdline#envvar-PYTHONBREAKPOINT). If that is set to `"0"` then this function returns immediately; i.e. it is a no-op. If the environment variable is not set, or is set to the empty string, `pdb.set_trace()` is called. Otherwise this variable should name a function to run, using Python’s dotted-import nomenclature, e.g. `package.subpackage.module.function`. In this case, `package.subpackage.module` would be imported and the resulting module must have a callable named `function()`. This is run, passing in `*args` and `**kws`, and whatever `function()` returns, `sys.breakpointhook()` returns to the built-in [`breakpoint()`](functions#breakpoint "breakpoint") function. Note that if anything goes wrong while importing the callable named by [`PYTHONBREAKPOINT`](../using/cmdline#envvar-PYTHONBREAKPOINT), a [`RuntimeWarning`](exceptions#RuntimeWarning "RuntimeWarning") is reported and the breakpoint is ignored. Also note that if `sys.breakpointhook()` is overridden programmatically, [`PYTHONBREAKPOINT`](../using/cmdline#envvar-PYTHONBREAKPOINT) is *not* consulted. New in version 3.7. `sys._debugmallocstats()` Print low-level information to stderr about the state of CPython’s memory allocator. If Python is configured –with-pydebug, it also performs some expensive internal consistency checks. New in version 3.3. **CPython implementation detail:** This function is specific to CPython. The exact output format is not defined here, and may change. `sys.dllhandle` Integer specifying the handle of the Python DLL. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Windows. `sys.displayhook(value)` If *value* is not `None`, this function prints `repr(value)` to `sys.stdout`, and saves *value* in `builtins._`. If `repr(value)` is not encodable to `sys.stdout.encoding` with `sys.stdout.errors` error handler (which is probably `'strict'`), encode it to `sys.stdout.encoding` with `'backslashreplace'` error handler. `sys.displayhook` is called on the result of evaluating an [expression](../glossary#term-expression) entered in an interactive Python session. The display of these values can be customized by assigning another one-argument function to `sys.displayhook`. Pseudo-code: ``` def displayhook(value): if value is None: return # Set '_' to None to avoid recursion builtins._ = None text = repr(value) try: sys.stdout.write(text) except UnicodeEncodeError: bytes = text.encode(sys.stdout.encoding, 'backslashreplace') if hasattr(sys.stdout, 'buffer'): sys.stdout.buffer.write(bytes) else: text = bytes.decode(sys.stdout.encoding, 'strict') sys.stdout.write(text) sys.stdout.write("\n") builtins._ = value ``` Changed in version 3.2: Use `'backslashreplace'` error handler on [`UnicodeEncodeError`](exceptions#UnicodeEncodeError "UnicodeEncodeError"). `sys.dont_write_bytecode` If this is true, Python won’t try to write `.pyc` files on the import of source modules. This value is initially set to `True` or `False` depending on the [`-B`](../using/cmdline#id1) command line option and the [`PYTHONDONTWRITEBYTECODE`](../using/cmdline#envvar-PYTHONDONTWRITEBYTECODE) environment variable, but you can set it yourself to control bytecode file generation. `sys.pycache_prefix` If this is set (not `None`), Python will write bytecode-cache `.pyc` files to (and read them from) a parallel directory tree rooted at this directory, rather than from `__pycache__` directories in the source code tree. Any `__pycache__` directories in the source code tree will be ignored and new `.pyc` files written within the pycache prefix. Thus if you use [`compileall`](compileall#module-compileall "compileall: Tools for byte-compiling all Python source files in a directory tree.") as a pre-build step, you must ensure you run it with the same pycache prefix (if any) that you will use at runtime. A relative path is interpreted relative to the current working directory. This value is initially set based on the value of the [`-X`](../using/cmdline#id5) `pycache_prefix=PATH` command-line option or the [`PYTHONPYCACHEPREFIX`](../using/cmdline#envvar-PYTHONPYCACHEPREFIX) environment variable (command-line takes precedence). If neither are set, it is `None`. New in version 3.8. `sys.excepthook(type, value, traceback)` This function prints out a given traceback and exception to `sys.stderr`. When an exception is raised and uncaught, the interpreter calls `sys.excepthook` with three arguments, the exception class, exception instance, and a traceback object. In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits. The handling of such top-level exceptions can be customized by assigning another three-argument function to `sys.excepthook`. Raise an auditing event `sys.excepthook` with arguments `hook`, `type`, `value`, `traceback` when an uncaught exception occurs. If no hook has been set, `hook` may be `None`. If any hook raises an exception derived from [`RuntimeError`](exceptions#RuntimeError "RuntimeError") the call to the hook will be suppressed. Otherwise, the audit hook exception will be reported as unraisable and `sys.excepthook` will be called. See also The [`sys.unraisablehook()`](#sys.unraisablehook "sys.unraisablehook") function handles unraisable exceptions and the [`threading.excepthook()`](threading#threading.excepthook "threading.excepthook") function handles exception raised by [`threading.Thread.run()`](threading#threading.Thread.run "threading.Thread.run"). `sys.__breakpointhook__` `sys.__displayhook__` `sys.__excepthook__` `sys.__unraisablehook__` These objects contain the original values of `breakpointhook`, `displayhook`, `excepthook`, and `unraisablehook` at the start of the program. They are saved so that `breakpointhook`, `displayhook` and `excepthook`, `unraisablehook` can be restored in case they happen to get replaced with broken or alternative objects. New in version 3.7: \_\_breakpointhook\_\_ New in version 3.8: \_\_unraisablehook\_\_ `sys.exc_info()` This function returns a tuple of three values that give information about the exception that is currently being handled. The information returned is specific both to the current thread and to the current stack frame. If the current stack frame is not handling an exception, the information is taken from the calling stack frame, or its caller, and so on until a stack frame is found that is handling an exception. Here, “handling an exception” is defined as “executing an except clause.” For any stack frame, only information about the exception being currently handled is accessible. If no exception is being handled anywhere on the stack, a tuple containing three `None` values is returned. Otherwise, the values returned are `(type, value, traceback)`. Their meaning is: *type* gets the type of the exception being handled (a subclass of [`BaseException`](exceptions#BaseException "BaseException")); *value* gets the exception instance (an instance of the exception type); *traceback* gets a [traceback object](../reference/datamodel#traceback-objects) which encapsulates the call stack at the point where the exception originally occurred. `sys.exec_prefix` A string giving the site-specific directory prefix where the platform-dependent Python files are installed; by default, this is also `'/usr/local'`. This can be set at build time with the `--exec-prefix` argument to the **configure** script. Specifically, all configuration files (e.g. the `pyconfig.h` header file) are installed in the directory `*exec\_prefix*/lib/python*X.Y*/config`, and shared library modules are installed in `*exec\_prefix*/lib/python*X.Y*/lib-dynload`, where *X.Y* is the version number of Python, for example `3.2`. Note If a [virtual environment](venv#venv-def) is in effect, this value will be changed in `site.py` to point to the virtual environment. The value for the Python installation will still be available, via [`base_exec_prefix`](#sys.base_exec_prefix "sys.base_exec_prefix"). `sys.executable` A string giving the absolute path of the executable binary for the Python interpreter, on systems where this makes sense. If Python is unable to retrieve the real path to its executable, [`sys.executable`](#sys.executable "sys.executable") will be an empty string or `None`. `sys.exit([arg])` Raise a [`SystemExit`](exceptions#SystemExit "SystemExit") exception, signaling an intention to exit the interpreter. The optional argument *arg* can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0–127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, `None` is equivalent to passing zero, and any other object is printed to [`stderr`](#sys.stderr "sys.stderr") and results in an exit code of 1. In particular, `sys.exit("some error message")` is a quick way to exit a program when an error occurs. Since [`exit()`](constants#exit "exit") ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted. Cleanup actions specified by finally clauses of [`try`](../reference/compound_stmts#try) statements are honored, and it is possible to intercept the exit attempt at an outer level. Changed in version 3.6: If an error occurs in the cleanup after the Python interpreter has caught [`SystemExit`](exceptions#SystemExit "SystemExit") (such as an error flushing buffered data in the standard streams), the exit status is changed to 120. `sys.flags` The [named tuple](../glossary#term-named-tuple) *flags* exposes the status of command line flags. The attributes are read only. | attribute | flag | | --- | --- | | `debug` | [`-d`](../using/cmdline#cmdoption-d) | | [`inspect`](inspect#module-inspect "inspect: Extract information and source code from live objects.") | [`-i`](../using/cmdline#cmdoption-i) | | `interactive` | [`-i`](../using/cmdline#cmdoption-i) | | `isolated` | [`-I`](../using/cmdline#id2) | | `optimize` | [`-O`](../using/cmdline#cmdoption-o) or [`-OO`](../using/cmdline#cmdoption-oo) | | [`dont_write_bytecode`](#sys.dont_write_bytecode "sys.dont_write_bytecode") | [`-B`](../using/cmdline#id1) | | `no_user_site` | [`-s`](../using/cmdline#cmdoption-s) | | `no_site` | [`-S`](../using/cmdline#id3) | | `ignore_environment` | [`-E`](../using/cmdline#cmdoption-e) | | `verbose` | [`-v`](../using/cmdline#id4) | | `bytes_warning` | [`-b`](../using/cmdline#cmdoption-b) | | `quiet` | [`-q`](../using/cmdline#cmdoption-q) | | `hash_randomization` | [`-R`](../using/cmdline#cmdoption-r) | | `dev_mode` | [`-X dev`](../using/cmdline#id5) ([Python Development Mode](devmode#devmode)) | | `utf8_mode` | [`-X utf8`](../using/cmdline#id5) | | `int_max_str_digits` | [`-X int_max_str_digits`](../using/cmdline#id5) ([integer string conversion length limitation](stdtypes#int-max-str-digits)) | Changed in version 3.2: Added `quiet` attribute for the new [`-q`](../using/cmdline#cmdoption-q) flag. New in version 3.2.3: The `hash_randomization` attribute. Changed in version 3.3: Removed obsolete `division_warning` attribute. Changed in version 3.4: Added `isolated` attribute for [`-I`](../using/cmdline#id2) `isolated` flag. Changed in version 3.7: Added the `dev_mode` attribute for the new [Python Development Mode](devmode#devmode) and the `utf8_mode` attribute for the new [`-X`](../using/cmdline#id5) `utf8` flag. Changed in version 3.9.14: Added the `int_max_str_digits` attribute. `sys.float_info` A [named tuple](../glossary#term-named-tuple) holding information about the float type. It contains low level information about the precision and internal representation. The values correspond to the various floating-point constants defined in the standard header file `float.h` for the ‘C’ programming language; see section 5.2.4.2.2 of the 1999 ISO/IEC C standard [[C99]](#c99), ‘Characteristics of floating types’, for details. | attribute | float.h macro | explanation | | --- | --- | --- | | `epsilon` | DBL\_EPSILON | difference between 1.0 and the least value greater than 1.0 that is representable as a float See also [`math.ulp()`](math#math.ulp "math.ulp"). | | `dig` | DBL\_DIG | maximum number of decimal digits that can be faithfully represented in a float; see below | | `mant_dig` | DBL\_MANT\_DIG | float precision: the number of base-`radix` digits in the significand of a float | | [`max`](functions#max "max") | DBL\_MAX | maximum representable positive finite float | | `max_exp` | DBL\_MAX\_EXP | maximum integer *e* such that `radix**(e-1)` is a representable finite float | | `max_10_exp` | DBL\_MAX\_10\_EXP | maximum integer *e* such that `10**e` is in the range of representable finite floats | | [`min`](functions#min "min") | DBL\_MIN | minimum representable positive *normalized* float Use [`math.ulp(0.0)`](math#math.ulp "math.ulp") to get the smallest positive *denormalized* representable float. | | `min_exp` | DBL\_MIN\_EXP | minimum integer *e* such that `radix**(e-1)` is a normalized float | | `min_10_exp` | DBL\_MIN\_10\_EXP | minimum integer *e* such that `10**e` is a normalized float | | `radix` | FLT\_RADIX | radix of exponent representation | | `rounds` | FLT\_ROUNDS | integer constant representing the rounding mode used for arithmetic operations. This reflects the value of the system FLT\_ROUNDS macro at interpreter startup time. See section 5.2.4.2.2 of the C99 standard for an explanation of the possible values and their meanings. | The attribute `sys.float_info.dig` needs further explanation. If `s` is any string representing a decimal number with at most `sys.float_info.dig` significant digits, then converting `s` to a float and back again will recover a string representing the same decimal value: ``` >>> import sys >>> sys.float_info.dig 15 >>> s = '3.14159265358979' # decimal string with 15 significant digits >>> format(float(s), '.15g') # convert to float and back -> same value '3.14159265358979' ``` But for strings with more than `sys.float_info.dig` significant digits, this isn’t always true: ``` >>> s = '9876543211234567' # 16 significant digits is too many! >>> format(float(s), '.16g') # conversion changes value '9876543211234568' ``` `sys.float_repr_style` A string indicating how the [`repr()`](functions#repr "repr") function behaves for floats. If the string has value `'short'` then for a finite float `x`, `repr(x)` aims to produce a short string with the property that `float(repr(x)) == x`. This is the usual behaviour in Python 3.1 and later. Otherwise, `float_repr_style` has value `'legacy'` and `repr(x)` behaves in the same way as it did in versions of Python prior to 3.1. New in version 3.1. `sys.getallocatedblocks()` Return the number of memory blocks currently allocated by the interpreter, regardless of their size. This function is mainly useful for tracking and debugging memory leaks. Because of the interpreter’s internal caches, the result can vary from call to call; you may have to call [`_clear_type_cache()`](#sys._clear_type_cache "sys._clear_type_cache") and [`gc.collect()`](gc#gc.collect "gc.collect") to get more predictable results. If a Python build or implementation cannot reasonably compute this information, [`getallocatedblocks()`](#sys.getallocatedblocks "sys.getallocatedblocks") is allowed to return 0 instead. New in version 3.4. `sys.getandroidapilevel()` Return the build time API version of Android as an integer. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Android. New in version 3.7. `sys.getdefaultencoding()` Return the name of the current default string encoding used by the Unicode implementation. `sys.getdlopenflags()` Return the current value of the flags that are used for `dlopen()` calls. Symbolic names for the flag values can be found in the [`os`](os#module-os "os: Miscellaneous operating system interfaces.") module (`RTLD_xxx` constants, e.g. [`os.RTLD_LAZY`](os#os.RTLD_LAZY "os.RTLD_LAZY")). [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix. `sys.getfilesystemencoding()` Return the name of the encoding used to convert between Unicode filenames and bytes filenames. For best compatibility, str should be used for filenames in all cases, although representing filenames as bytes is also supported. Functions accepting or returning filenames should support either str or bytes and internally convert to the system’s preferred representation. This encoding is always ASCII-compatible. [`os.fsencode()`](os#os.fsencode "os.fsencode") and [`os.fsdecode()`](os#os.fsdecode "os.fsdecode") should be used to ensure that the correct encoding and errors mode are used. * In the UTF-8 mode, the encoding is `utf-8` on any platform. * On macOS, the encoding is `'utf-8'`. * On Unix, the encoding is the locale encoding. * On Windows, the encoding may be `'utf-8'` or `'mbcs'`, depending on user configuration. * On Android, the encoding is `'utf-8'`. * On VxWorks, the encoding is `'utf-8'`. Changed in version 3.2: [`getfilesystemencoding()`](#sys.getfilesystemencoding "sys.getfilesystemencoding") result cannot be `None` anymore. Changed in version 3.6: Windows is no longer guaranteed to return `'mbcs'`. See [**PEP 529**](https://www.python.org/dev/peps/pep-0529) and [`_enablelegacywindowsfsencoding()`](#sys._enablelegacywindowsfsencoding "sys._enablelegacywindowsfsencoding") for more information. Changed in version 3.7: Return ‘utf-8’ in the UTF-8 mode. `sys.getfilesystemencodeerrors()` Return the name of the error mode used to convert between Unicode filenames and bytes filenames. The encoding name is returned from [`getfilesystemencoding()`](#sys.getfilesystemencoding "sys.getfilesystemencoding"). [`os.fsencode()`](os#os.fsencode "os.fsencode") and [`os.fsdecode()`](os#os.fsdecode "os.fsdecode") should be used to ensure that the correct encoding and errors mode are used. New in version 3.6. `sys.get_int_max_str_digits()` Returns the current value for the [integer string conversion length limitation](stdtypes#int-max-str-digits). See also [`set_int_max_str_digits()`](#sys.set_int_max_str_digits "sys.set_int_max_str_digits"). New in version 3.9.14. `sys.getrefcount(object)` Return the reference count of the *object*. The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to [`getrefcount()`](#sys.getrefcount "sys.getrefcount"). `sys.getrecursionlimit()` Return the current value of the recursion limit, the maximum depth of the Python interpreter stack. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. It can be set by [`setrecursionlimit()`](#sys.setrecursionlimit "sys.setrecursionlimit"). `sys.getsizeof(object[, default])` Return the size of an object in bytes. The object can be any type of object. All built-in objects will return correct results, but this does not have to hold true for third-party extensions as it is implementation specific. Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to. If given, *default* will be returned if the object does not provide means to retrieve the size. Otherwise a [`TypeError`](exceptions#TypeError "TypeError") will be raised. [`getsizeof()`](#sys.getsizeof "sys.getsizeof") calls the object’s `__sizeof__` method and adds an additional garbage collector overhead if the object is managed by the garbage collector. See [recursive sizeof recipe](https://code.activestate.com/recipes/577504) for an example of using [`getsizeof()`](#sys.getsizeof "sys.getsizeof") recursively to find the size of containers and all their contents. `sys.getswitchinterval()` Return the interpreter’s “thread switch interval”; see [`setswitchinterval()`](#sys.setswitchinterval "sys.setswitchinterval"). New in version 3.2. `sys._getframe([depth])` Return a frame object from the call stack. If optional integer *depth* is given, return the frame object that many calls below the top of the stack. If that is deeper than the call stack, [`ValueError`](exceptions#ValueError "ValueError") is raised. The default for *depth* is zero, returning the frame at the top of the call stack. Raises an [auditing event](#auditing) `sys._getframe` with no arguments. **CPython implementation detail:** This function should be used for internal and specialized purposes only. It is not guaranteed to exist in all implementations of Python. `sys.getprofile()` Get the profiler function as set by [`setprofile()`](#sys.setprofile "sys.setprofile"). `sys.gettrace()` Get the trace function as set by [`settrace()`](#sys.settrace "sys.settrace"). **CPython implementation detail:** The [`gettrace()`](#sys.gettrace "sys.gettrace") function is intended only for implementing debuggers, profilers, coverage tools and the like. Its behavior is part of the implementation platform, rather than part of the language definition, and thus may not be available in all Python implementations. `sys.getwindowsversion()` Return a named tuple describing the Windows version currently running. The named elements are *major*, *minor*, *build*, *platform*, *service\_pack*, *service\_pack\_minor*, *service\_pack\_major*, *suite\_mask*, *product\_type* and *platform\_version*. *service\_pack* contains a string, *platform\_version* a 3-tuple and all other values are integers. The components can also be accessed by name, so `sys.getwindowsversion()[0]` is equivalent to `sys.getwindowsversion().major`. For compatibility with prior versions, only the first 5 elements are retrievable by indexing. *platform* will be `2 (VER_PLATFORM_WIN32_NT)`. *product\_type* may be one of the following values: | Constant | Meaning | | --- | --- | | `1 (VER_NT_WORKSTATION)` | The system is a workstation. | | `2 (VER_NT_DOMAIN_CONTROLLER)` | The system is a domain controller. | | `3 (VER_NT_SERVER)` | The system is a server, but not a domain controller. | This function wraps the Win32 `GetVersionEx()` function; see the Microsoft documentation on `OSVERSIONINFOEX()` for more information about these fields. *platform\_version* returns the major version, minor version and build number of the current operating system, rather than the version that is being emulated for the process. It is intended for use in logging rather than for feature detection. Note *platform\_version* derives the version from kernel32.dll which can be of a different version than the OS version. Please use [`platform`](platform#module-platform "platform: Retrieves as much platform identifying data as possible.") module for achieving accurate OS version. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Windows. Changed in version 3.2: Changed to a named tuple and added *service\_pack\_minor*, *service\_pack\_major*, *suite\_mask*, and *product\_type*. Changed in version 3.6: Added *platform\_version* `sys.get_asyncgen_hooks()` Returns an *asyncgen\_hooks* object, which is similar to a [`namedtuple`](collections#collections.namedtuple "collections.namedtuple") of the form `(firstiter, finalizer)`, where *firstiter* and *finalizer* are expected to be either `None` or functions which take an [asynchronous generator iterator](../glossary#term-asynchronous-generator-iterator) as an argument, and are used to schedule finalization of an asynchronous generator by an event loop. New in version 3.6: See [**PEP 525**](https://www.python.org/dev/peps/pep-0525) for more details. Note This function has been added on a provisional basis (see [**PEP 411**](https://www.python.org/dev/peps/pep-0411) for details.) `sys.get_coroutine_origin_tracking_depth()` Get the current coroutine origin tracking depth, as set by [`set_coroutine_origin_tracking_depth()`](#sys.set_coroutine_origin_tracking_depth "sys.set_coroutine_origin_tracking_depth"). New in version 3.7. Note This function has been added on a provisional basis (see [**PEP 411**](https://www.python.org/dev/peps/pep-0411) for details.) Use it only for debugging purposes. `sys.hash_info` A [named tuple](../glossary#term-named-tuple) giving parameters of the numeric hash implementation. For more details about hashing of numeric types, see [Hashing of numeric types](stdtypes#numeric-hash). | attribute | explanation | | --- | --- | | `width` | width in bits used for hash values | | `modulus` | prime modulus P used for numeric hash scheme | | `inf` | hash value returned for a positive infinity | | `nan` | hash value returned for a nan | | `imag` | multiplier used for the imaginary part of a complex number | | `algorithm` | name of the algorithm for hashing of str, bytes, and memoryview | | `hash_bits` | internal output size of the hash algorithm | | `seed_bits` | size of the seed key of the hash algorithm | New in version 3.2. Changed in version 3.4: Added *algorithm*, *hash\_bits* and *seed\_bits* `sys.hexversion` The version number encoded as a single integer. This is guaranteed to increase with each version, including proper support for non-production releases. For example, to test that the Python interpreter is at least version 1.5.2, use: ``` if sys.hexversion >= 0x010502F0: # use some advanced feature ... else: # use an alternative implementation or warn the user ... ``` This is called `hexversion` since it only really looks meaningful when viewed as the result of passing it to the built-in [`hex()`](functions#hex "hex") function. The [named tuple](../glossary#term-named-tuple) [`sys.version_info`](#sys.version_info "sys.version_info") may be used for a more human-friendly encoding of the same information. More details of `hexversion` can be found at [API and ABI Versioning](../c-api/apiabiversion#apiabiversion). `sys.implementation` An object containing information about the implementation of the currently running Python interpreter. The following attributes are required to exist in all Python implementations. *name* is the implementation’s identifier, e.g. `'cpython'`. The actual string is defined by the Python implementation, but it is guaranteed to be lower case. *version* is a named tuple, in the same format as [`sys.version_info`](#sys.version_info "sys.version_info"). It represents the version of the Python *implementation*. This has a distinct meaning from the specific version of the Python *language* to which the currently running interpreter conforms, which `sys.version_info` represents. For example, for PyPy 1.8 `sys.implementation.version` might be `sys.version_info(1, 8, 0, 'final', 0)`, whereas `sys.version_info` would be `sys.version_info(2, 7, 2, 'final', 0)`. For CPython they are the same value, since it is the reference implementation. *hexversion* is the implementation version in hexadecimal format, like [`sys.hexversion`](#sys.hexversion "sys.hexversion"). *cache\_tag* is the tag used by the import machinery in the filenames of cached modules. By convention, it would be a composite of the implementation’s name and version, like `'cpython-33'`. However, a Python implementation may use some other value if appropriate. If `cache_tag` is set to `None`, it indicates that module caching should be disabled. [`sys.implementation`](#sys.implementation "sys.implementation") may contain additional attributes specific to the Python implementation. These non-standard attributes must start with an underscore, and are not described here. Regardless of its contents, [`sys.implementation`](#sys.implementation "sys.implementation") will not change during a run of the interpreter, nor between implementation versions. (It may change between Python language versions, however.) See [**PEP 421**](https://www.python.org/dev/peps/pep-0421) for more information. New in version 3.3. Note The addition of new required attributes must go through the normal PEP process. See [**PEP 421**](https://www.python.org/dev/peps/pep-0421) for more information. `sys.int_info` A [named tuple](../glossary#term-named-tuple) that holds information about Python’s internal representation of integers. The attributes are read only. | Attribute | Explanation | | --- | --- | | `bits_per_digit` | number of bits held in each digit. Python integers are stored internally in base `2**int_info.bits_per_digit` | | `sizeof_digit` | size in bytes of the C type used to represent a digit | | `default_max_str_digits` | default value for [`sys.get_int_max_str_digits()`](#sys.get_int_max_str_digits "sys.get_int_max_str_digits") when it is not otherwise explicitly configured. | | `str_digits_check_threshold` | minimum non-zero value for [`sys.set_int_max_str_digits()`](#sys.set_int_max_str_digits "sys.set_int_max_str_digits"), [`PYTHONINTMAXSTRDIGITS`](../using/cmdline#envvar-PYTHONINTMAXSTRDIGITS), or [`-X int_max_str_digits`](../using/cmdline#id5). | New in version 3.1. Changed in version 3.9.14: Added `default_max_str_digits` and `str_digits_check_threshold`. `sys.__interactivehook__` When this attribute exists, its value is automatically called (with no arguments) when the interpreter is launched in [interactive mode](../tutorial/interpreter#tut-interactive). This is done after the [`PYTHONSTARTUP`](../using/cmdline#envvar-PYTHONSTARTUP) file is read, so that you can set this hook there. The [`site`](site#module-site "site: Module responsible for site-specific configuration.") module [sets this](site#rlcompleter-config). Raises an [auditing event](#auditing) `cpython.run_interactivehook` with the hook object as the argument when the hook is called on startup. New in version 3.4. `sys.intern(string)` Enter *string* in the table of “interned” strings and return the interned string – which is *string* itself or a copy. Interning strings is useful to gain a little performance on dictionary lookup – if the keys in a dictionary are interned, and the lookup key is interned, the key comparisons (after hashing) can be done by a pointer compare instead of a string compare. Normally, the names used in Python programs are automatically interned, and the dictionaries used to hold module, class or instance attributes have interned keys. Interned strings are not immortal; you must keep a reference to the return value of [`intern()`](#sys.intern "sys.intern") around to benefit from it. `sys.is_finalizing()` Return [`True`](constants#True "True") if the Python interpreter is [shutting down](../glossary#term-interpreter-shutdown), [`False`](constants#False "False") otherwise. New in version 3.5. `sys.last_type` `sys.last_value` `sys.last_traceback` These three variables are not always defined; they are set when an exception is not handled and the interpreter prints an error message and a stack traceback. Their intended use is to allow an interactive user to import a debugger module and engage in post-mortem debugging without having to re-execute the command that caused the error. (Typical use is `import pdb; pdb.pm()` to enter the post-mortem debugger; see [`pdb`](pdb#module-pdb "pdb: The Python debugger for interactive interpreters.") module for more information.) The meaning of the variables is the same as that of the return values from [`exc_info()`](#sys.exc_info "sys.exc_info") above. `sys.maxsize` An integer giving the maximum value a variable of type [`Py_ssize_t`](../c-api/intro#c.Py_ssize_t "Py_ssize_t") can take. It’s usually `2**31 - 1` on a 32-bit platform and `2**63 - 1` on a 64-bit platform. `sys.maxunicode` An integer giving the value of the largest Unicode code point, i.e. `1114111` (`0x10FFFF` in hexadecimal). Changed in version 3.3: Before [**PEP 393**](https://www.python.org/dev/peps/pep-0393), `sys.maxunicode` used to be either `0xFFFF` or `0x10FFFF`, depending on the configuration option that specified whether Unicode characters were stored as UCS-2 or UCS-4. `sys.meta_path` A list of [meta path finder](../glossary#term-meta-path-finder) objects that have their [`find_spec()`](importlib#importlib.abc.MetaPathFinder.find_spec "importlib.abc.MetaPathFinder.find_spec") methods called to see if one of the objects can find the module to be imported. The [`find_spec()`](importlib#importlib.abc.MetaPathFinder.find_spec "importlib.abc.MetaPathFinder.find_spec") method is called with at least the absolute name of the module being imported. If the module to be imported is contained in a package, then the parent package’s [`__path__`](../reference/import#__path__ "__path__") attribute is passed in as a second argument. The method returns a [module spec](../glossary#term-module-spec), or `None` if the module cannot be found. See also [`importlib.abc.MetaPathFinder`](importlib#importlib.abc.MetaPathFinder "importlib.abc.MetaPathFinder") The abstract base class defining the interface of finder objects on [`meta_path`](#sys.meta_path "sys.meta_path"). [`importlib.machinery.ModuleSpec`](importlib#importlib.machinery.ModuleSpec "importlib.machinery.ModuleSpec") The concrete class which [`find_spec()`](importlib#importlib.abc.MetaPathFinder.find_spec "importlib.abc.MetaPathFinder.find_spec") should return instances of. Changed in version 3.4: [Module specs](../glossary#term-module-spec) were introduced in Python 3.4, by [**PEP 451**](https://www.python.org/dev/peps/pep-0451). Earlier versions of Python looked for a method called [`find_module()`](importlib#importlib.abc.MetaPathFinder.find_module "importlib.abc.MetaPathFinder.find_module"). This is still called as a fallback if a [`meta_path`](#sys.meta_path "sys.meta_path") entry doesn’t have a [`find_spec()`](importlib#importlib.abc.MetaPathFinder.find_spec "importlib.abc.MetaPathFinder.find_spec") method. `sys.modules` This is a dictionary that maps module names to modules which have already been loaded. This can be manipulated to force reloading of modules and other tricks. However, replacing the dictionary will not necessarily work as expected and deleting essential items from the dictionary may cause Python to fail. `sys.path` A list of strings that specifies the search path for modules. Initialized from the environment variable [`PYTHONPATH`](../using/cmdline#envvar-PYTHONPATH), plus an installation-dependent default. As initialized upon program startup, the first item of this list, `path[0]`, is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), `path[0]` is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted *before* the entries inserted as a result of [`PYTHONPATH`](../using/cmdline#envvar-PYTHONPATH). A program is free to modify this list for its own purposes. Only strings and bytes should be added to [`sys.path`](#sys.path "sys.path"); all other data types are ignored during import. See also Module [`site`](site#module-site "site: Module responsible for site-specific configuration.") This describes how to use .pth files to extend [`sys.path`](#sys.path "sys.path"). `sys.path_hooks` A list of callables that take a path argument to try to create a [finder](../glossary#term-finder) for the path. If a finder can be created, it is to be returned by the callable, else raise [`ImportError`](exceptions#ImportError "ImportError"). Originally specified in [**PEP 302**](https://www.python.org/dev/peps/pep-0302). `sys.path_importer_cache` A dictionary acting as a cache for [finder](../glossary#term-finder) objects. The keys are paths that have been passed to [`sys.path_hooks`](#sys.path_hooks "sys.path_hooks") and the values are the finders that are found. If a path is a valid file system path but no finder is found on [`sys.path_hooks`](#sys.path_hooks "sys.path_hooks") then `None` is stored. Originally specified in [**PEP 302**](https://www.python.org/dev/peps/pep-0302). Changed in version 3.3: `None` is stored instead of [`imp.NullImporter`](imp#imp.NullImporter "imp.NullImporter") when no finder is found. `sys.platform` This string contains a platform identifier that can be used to append platform-specific components to [`sys.path`](#sys.path "sys.path"), for instance. For Unix systems, except on Linux and AIX, this is the lowercased OS name as returned by `uname -s` with the first part of the version as returned by `uname -r` appended, e.g. `'sunos5'` or `'freebsd8'`, *at the time when Python was built*. Unless you want to test for a specific system version, it is therefore recommended to use the following idiom: ``` if sys.platform.startswith('freebsd'): # FreeBSD-specific code here... elif sys.platform.startswith('linux'): # Linux-specific code here... elif sys.platform.startswith('aix'): # AIX-specific code here... ``` For other systems, the values are: | System | `platform` value | | --- | --- | | AIX | `'aix'` | | Linux | `'linux'` | | Windows | `'win32'` | | Windows/Cygwin | `'cygwin'` | | macOS | `'darwin'` | Changed in version 3.3: On Linux, [`sys.platform`](#sys.platform "sys.platform") doesn’t contain the major version anymore. It is always `'linux'`, instead of `'linux2'` or `'linux3'`. Since older Python versions include the version number, it is recommended to always use the `startswith` idiom presented above. Changed in version 3.8: On AIX, [`sys.platform`](#sys.platform "sys.platform") doesn’t contain the major version anymore. It is always `'aix'`, instead of `'aix5'` or `'aix7'`. Since older Python versions include the version number, it is recommended to always use the `startswith` idiom presented above. See also [`os.name`](os#os.name "os.name") has a coarser granularity. [`os.uname()`](os#os.uname "os.uname") gives system-dependent version information. The [`platform`](platform#module-platform "platform: Retrieves as much platform identifying data as possible.") module provides detailed checks for the system’s identity. `sys.platlibdir` Name of the platform-specific library directory. It is used to build the path of standard library and the paths of installed extension modules. It is equal to `"lib"` on most platforms. On Fedora and SuSE, it is equal to `"lib64"` on 64-bit platforms which gives the following `sys.path` paths (where `X.Y` is the Python `major.minor` version): * `/usr/lib64/pythonX.Y/`: Standard library (like `os.py` of the [`os`](os#module-os "os: Miscellaneous operating system interfaces.") module) * `/usr/lib64/pythonX.Y/lib-dynload/`: C extension modules of the standard library (like the [`errno`](errno#module-errno "errno: Standard errno system symbols.") module, the exact filename is platform specific) * `/usr/lib/pythonX.Y/site-packages/` (always use `lib`, not [`sys.platlibdir`](#sys.platlibdir "sys.platlibdir")): Third-party modules * `/usr/lib64/pythonX.Y/site-packages/`: C extension modules of third-party packages New in version 3.9. `sys.prefix` A string giving the site-specific directory prefix where the platform independent Python files are installed; on Unix, the default is `'/usr/local'`. This can be set at build time with the `--prefix` argument to the **configure** script. See [Installation paths](sysconfig#installation-paths) for derived paths. Note If a [virtual environment](venv#venv-def) is in effect, this value will be changed in `site.py` to point to the virtual environment. The value for the Python installation will still be available, via [`base_prefix`](#sys.base_prefix "sys.base_prefix"). `sys.ps1` `sys.ps2` Strings specifying the primary and secondary prompt of the interpreter. These are only defined if the interpreter is in interactive mode. Their initial values in this case are `'>>> '` and `'... '`. If a non-string object is assigned to either variable, its [`str()`](stdtypes#str "str") is re-evaluated each time the interpreter prepares to read a new interactive command; this can be used to implement a dynamic prompt. `sys.setdlopenflags(n)` Set the flags used by the interpreter for `dlopen()` calls, such as when the interpreter loads extension modules. Among other things, this will enable a lazy resolving of symbols when importing a module, if called as `sys.setdlopenflags(0)`. To share symbols across extension modules, call as `sys.setdlopenflags(os.RTLD_GLOBAL)`. Symbolic names for the flag values can be found in the [`os`](os#module-os "os: Miscellaneous operating system interfaces.") module (`RTLD_xxx` constants, e.g. [`os.RTLD_LAZY`](os#os.RTLD_LAZY "os.RTLD_LAZY")). [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix. `sys.set_int_max_str_digits(n)` Set the [integer string conversion length limitation](stdtypes#int-max-str-digits) used by this interpreter. See also [`get_int_max_str_digits()`](#sys.get_int_max_str_digits "sys.get_int_max_str_digits"). New in version 3.9.14. `sys.setprofile(profilefunc)` Set the system’s profile function, which allows you to implement a Python source code profiler in Python. See chapter [The Python Profilers](profile#profile) for more information on the Python profiler. The system’s profile function is called similarly to the system’s trace function (see [`settrace()`](#sys.settrace "sys.settrace")), but it is called with different events, for example it isn’t called for each executed line of code (only on call and return, but the return event is reported even when an exception has been set). The function is thread-specific, but there is no way for the profiler to know about context switches between threads, so it does not make sense to use this in the presence of multiple threads. Also, its return value is not used, so it can simply return `None`. Error in the profile function will cause itself unset. Profile functions should have three arguments: *frame*, *event*, and *arg*. *frame* is the current stack frame. *event* is a string: `'call'`, `'return'`, `'c_call'`, `'c_return'`, or `'c_exception'`. *arg* depends on the event type. Raises an [auditing event](#auditing) `sys.setprofile` with no arguments. The events have the following meaning: `'call'` A function is called (or some other code block entered). The profile function is called; *arg* is `None`. `'return'` A function (or other code block) is about to return. The profile function is called; *arg* is the value that will be returned, or `None` if the event is caused by an exception being raised. `'c_call'` A C function is about to be called. This may be an extension function or a built-in. *arg* is the C function object. `'c_return'` A C function has returned. *arg* is the C function object. `'c_exception'` A C function has raised an exception. *arg* is the C function object. `sys.setrecursionlimit(limit)` Set the maximum depth of the Python interpreter stack to *limit*. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. The highest possible limit is platform-dependent. A user may need to set the limit higher when they have a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash. If the new limit is too low at the current recursion depth, a [`RecursionError`](exceptions#RecursionError "RecursionError") exception is raised. Changed in version 3.5.1: A [`RecursionError`](exceptions#RecursionError "RecursionError") exception is now raised if the new limit is too low at the current recursion depth. `sys.setswitchinterval(interval)` Set the interpreter’s thread switch interval (in seconds). This floating-point value determines the ideal duration of the “timeslices” allocated to concurrently running Python threads. Please note that the actual value can be higher, especially if long-running internal functions or methods are used. Also, which thread becomes scheduled at the end of the interval is the operating system’s decision. The interpreter doesn’t have its own scheduler. New in version 3.2. `sys.settrace(tracefunc)` Set the system’s trace function, which allows you to implement a Python source code debugger in Python. The function is thread-specific; for a debugger to support multiple threads, it must register a trace function using [`settrace()`](#sys.settrace "sys.settrace") for each thread being debugged or use [`threading.settrace()`](threading#threading.settrace "threading.settrace"). Trace functions should have three arguments: *frame*, *event*, and *arg*. *frame* is the current stack frame. *event* is a string: `'call'`, `'line'`, `'return'`, `'exception'` or `'opcode'`. *arg* depends on the event type. The trace function is invoked (with *event* set to `'call'`) whenever a new local scope is entered; it should return a reference to a local trace function to be used for the new scope, or `None` if the scope shouldn’t be traced. The local trace function should return a reference to itself (or to another function for further tracing in that scope), or `None` to turn off tracing in that scope. If there is any error occurred in the trace function, it will be unset, just like `settrace(None)` is called. The events have the following meaning: `'call'` A function is called (or some other code block entered). The global trace function is called; *arg* is `None`; the return value specifies the local trace function. `'line'` The interpreter is about to execute a new line of code or re-execute the condition of a loop. The local trace function is called; *arg* is `None`; the return value specifies the new local trace function. See `Objects/lnotab_notes.txt` for a detailed explanation of how this works. Per-line events may be disabled for a frame by setting `f_trace_lines` to [`False`](constants#False "False") on that frame. `'return'` A function (or other code block) is about to return. The local trace function is called; *arg* is the value that will be returned, or `None` if the event is caused by an exception being raised. The trace function’s return value is ignored. `'exception'` An exception has occurred. The local trace function is called; *arg* is a tuple `(exception, value, traceback)`; the return value specifies the new local trace function. `'opcode'` The interpreter is about to execute a new opcode (see [`dis`](dis#module-dis "dis: Disassembler for Python bytecode.") for opcode details). The local trace function is called; *arg* is `None`; the return value specifies the new local trace function. Per-opcode events are not emitted by default: they must be explicitly requested by setting `f_trace_opcodes` to [`True`](constants#True "True") on the frame. Note that as an exception is propagated down the chain of callers, an `'exception'` event is generated at each level. For more fine-grained usage, it’s possible to set a trace function by assigning `frame.f_trace = tracefunc` explicitly, rather than relying on it being set indirectly via the return value from an already installed trace function. This is also required for activating the trace function on the current frame, which [`settrace()`](#sys.settrace "sys.settrace") doesn’t do. Note that in order for this to work, a global tracing function must have been installed with [`settrace()`](#sys.settrace "sys.settrace") in order to enable the runtime tracing machinery, but it doesn’t need to be the same tracing function (e.g. it could be a low overhead tracing function that simply returns `None` to disable itself immediately on each frame). For more information on code and frame objects, refer to [The standard type hierarchy](../reference/datamodel#types). Raises an [auditing event](#auditing) `sys.settrace` with no arguments. **CPython implementation detail:** The [`settrace()`](#sys.settrace "sys.settrace") function is intended only for implementing debuggers, profilers, coverage tools and the like. Its behavior is part of the implementation platform, rather than part of the language definition, and thus may not be available in all Python implementations. Changed in version 3.7: `'opcode'` event type added; `f_trace_lines` and `f_trace_opcodes` attributes added to frames `sys.set_asyncgen_hooks(firstiter, finalizer)` Accepts two optional keyword arguments which are callables that accept an [asynchronous generator iterator](../glossary#term-asynchronous-generator-iterator) as an argument. The *firstiter* callable will be called when an asynchronous generator is iterated for the first time. The *finalizer* will be called when an asynchronous generator is about to be garbage collected. Raises an [auditing event](#auditing) `sys.set_asyncgen_hooks_firstiter` with no arguments. Raises an [auditing event](#auditing) `sys.set_asyncgen_hooks_finalizer` with no arguments. Two auditing events are raised because the underlying API consists of two calls, each of which must raise its own event. New in version 3.6: See [**PEP 525**](https://www.python.org/dev/peps/pep-0525) for more details, and for a reference example of a *finalizer* method see the implementation of `asyncio.Loop.shutdown_asyncgens` in [Lib/asyncio/base\_events.py](https://github.com/python/cpython/tree/3.9/Lib/asyncio/base_events.py) Note This function has been added on a provisional basis (see [**PEP 411**](https://www.python.org/dev/peps/pep-0411) for details.) `sys.set_coroutine_origin_tracking_depth(depth)` Allows enabling or disabling coroutine origin tracking. When enabled, the `cr_origin` attribute on coroutine objects will contain a tuple of (filename, line number, function name) tuples describing the traceback where the coroutine object was created, with the most recent call first. When disabled, `cr_origin` will be None. To enable, pass a *depth* value greater than zero; this sets the number of frames whose information will be captured. To disable, pass set *depth* to zero. This setting is thread-specific. New in version 3.7. Note This function has been added on a provisional basis (see [**PEP 411**](https://www.python.org/dev/peps/pep-0411) for details.) Use it only for debugging purposes. `sys._enablelegacywindowsfsencoding()` Changes the default filesystem encoding and errors mode to ‘mbcs’ and ‘replace’ respectively, for consistency with versions of Python prior to 3.6. This is equivalent to defining the [`PYTHONLEGACYWINDOWSFSENCODING`](../using/cmdline#envvar-PYTHONLEGACYWINDOWSFSENCODING) environment variable before launching Python. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Windows. New in version 3.6: See [**PEP 529**](https://www.python.org/dev/peps/pep-0529) for more details. `sys.stdin` `sys.stdout` `sys.stderr` [File objects](../glossary#term-file-object) used by the interpreter for standard input, output and errors: * `stdin` is used for all interactive input (including calls to [`input()`](functions#input "input")); * `stdout` is used for the output of [`print()`](functions#print "print") and [expression](../glossary#term-expression) statements and for the prompts of [`input()`](functions#input "input"); * The interpreter’s own prompts and its error messages go to `stderr`. These streams are regular [text files](../glossary#term-text-file) like those returned by the [`open()`](functions#open "open") function. Their parameters are chosen as follows: * The character encoding is platform-dependent. Non-Windows platforms use the locale encoding (see [`locale.getpreferredencoding()`](locale#locale.getpreferredencoding "locale.getpreferredencoding")). On Windows, UTF-8 is used for the console device. Non-character devices such as disk files and pipes use the system locale encoding (i.e. the ANSI codepage). Non-console character devices such as NUL (i.e. where `isatty()` returns `True`) use the value of the console input and output codepages at startup, respectively for stdin and stdout/stderr. This defaults to the system locale encoding if the process is not initially attached to a console. The special behaviour of the console can be overridden by setting the environment variable PYTHONLEGACYWINDOWSSTDIO before starting Python. In that case, the console codepages are used as for any other character device. Under all platforms, you can override the character encoding by setting the [`PYTHONIOENCODING`](../using/cmdline#envvar-PYTHONIOENCODING) environment variable before starting Python or by using the new [`-X`](../using/cmdline#id5) `utf8` command line option and [`PYTHONUTF8`](../using/cmdline#envvar-PYTHONUTF8) environment variable. However, for the Windows console, this only applies when [`PYTHONLEGACYWINDOWSSTDIO`](../using/cmdline#envvar-PYTHONLEGACYWINDOWSSTDIO) is also set. * When interactive, the `stdout` stream is line-buffered. Otherwise, it is block-buffered like regular text files. The `stderr` stream is line-buffered in both cases. You can make both streams unbuffered by passing the [`-u`](../using/cmdline#cmdoption-u) command-line option or setting the [`PYTHONUNBUFFERED`](../using/cmdline#envvar-PYTHONUNBUFFERED) environment variable. Changed in version 3.9: Non-interactive `stderr` is now line-buffered instead of fully buffered. Note To write or read binary data from/to the standard streams, use the underlying binary [`buffer`](io#io.TextIOBase.buffer "io.TextIOBase.buffer") object. For example, to write bytes to [`stdout`](#sys.stdout "sys.stdout"), use `sys.stdout.buffer.write(b'abc')`. However, if you are writing a library (and do not control in which context its code will be executed), be aware that the standard streams may be replaced with file-like objects like [`io.StringIO`](io#io.StringIO "io.StringIO") which do not support the `buffer` attribute. `sys.__stdin__` `sys.__stdout__` `sys.__stderr__` These objects contain the original values of `stdin`, `stderr` and `stdout` at the start of the program. They are used during finalization, and could be useful to print to the actual standard stream no matter if the `sys.std*` object has been redirected. It can also be used to restore the actual files to known working file objects in case they have been overwritten with a broken object. However, the preferred way to do this is to explicitly save the previous stream before replacing it, and restore the saved object. Note Under some conditions `stdin`, `stdout` and `stderr` as well as the original values `__stdin__`, `__stdout__` and `__stderr__` can be `None`. It is usually the case for Windows GUI apps that aren’t connected to a console and Python apps started with **pythonw**. `sys.thread_info` A [named tuple](../glossary#term-named-tuple) holding information about the thread implementation. | Attribute | Explanation | | --- | --- | | `name` | Name of the thread implementation:* `'nt'`: Windows threads * `'pthread'`: POSIX threads * `'solaris'`: Solaris threads | | `lock` | Name of the lock implementation:* `'semaphore'`: a lock uses a semaphore * `'mutex+cond'`: a lock uses a mutex and a condition variable * `None` if this information is unknown | | [`version`](#sys.version "sys.version") | Name and version of the thread library. It is a string, or `None` if this information is unknown. | New in version 3.3. `sys.tracebacklimit` When this variable is set to an integer value, it determines the maximum number of levels of traceback information printed when an unhandled exception occurs. The default is `1000`. When set to `0` or less, all traceback information is suppressed and only the exception type and value are printed. `sys.unraisablehook(unraisable, /)` Handle an unraisable exception. Called when an exception has occurred but there is no way for Python to handle it. For example, when a destructor raises an exception or during garbage collection ([`gc.collect()`](gc#gc.collect "gc.collect")). The *unraisable* argument has the following attributes: * *exc\_type*: Exception type. * *exc\_value*: Exception value, can be `None`. * *exc\_traceback*: Exception traceback, can be `None`. * *err\_msg*: Error message, can be `None`. * *object*: Object causing the exception, can be `None`. The default hook formats *err\_msg* and *object* as: `f'{err_msg}: {object!r}'`; use “Exception ignored in” error message if *err\_msg* is `None`. [`sys.unraisablehook()`](#sys.unraisablehook "sys.unraisablehook") can be overridden to control how unraisable exceptions are handled. Storing *exc\_value* using a custom hook can create a reference cycle. It should be cleared explicitly to break the reference cycle when the exception is no longer needed. Storing *object* using a custom hook can resurrect it if it is set to an object which is being finalized. Avoid storing *object* after the custom hook completes to avoid resurrecting objects. See also [`excepthook()`](#sys.excepthook "sys.excepthook") which handles uncaught exceptions. Raise an auditing event `sys.unraisablehook` with arguments `hook`, `unraisable` when an exception that cannot be handled occurs. The `unraisable` object is the same as what will be passed to the hook. If no hook has been set, `hook` may be `None`. New in version 3.8. `sys.version` A string containing the version number of the Python interpreter plus additional information on the build number and compiler used. This string is displayed when the interactive interpreter is started. Do not extract version information out of it, rather, use [`version_info`](#sys.version_info "sys.version_info") and the functions provided by the [`platform`](platform#module-platform "platform: Retrieves as much platform identifying data as possible.") module. `sys.api_version` The C API version for this interpreter. Programmers may find this useful when debugging version conflicts between Python and extension modules. `sys.version_info` A tuple containing the five components of the version number: *major*, *minor*, *micro*, *releaselevel*, and *serial*. All values except *releaselevel* are integers; the release level is `'alpha'`, `'beta'`, `'candidate'`, or `'final'`. The `version_info` value corresponding to the Python version 2.0 is `(2, 0, 0, 'final', 0)`. The components can also be accessed by name, so `sys.version_info[0]` is equivalent to `sys.version_info.major` and so on. Changed in version 3.1: Added named component attributes. `sys.warnoptions` This is an implementation detail of the warnings framework; do not modify this value. Refer to the [`warnings`](warnings#module-warnings "warnings: Issue warning messages and control their disposition.") module for more information on the warnings framework. `sys.winver` The version number used to form registry keys on Windows platforms. This is stored as string resource 1000 in the Python DLL. The value is normally the first three characters of [`version`](#sys.version "sys.version"). It is provided in the [`sys`](#module-sys "sys: Access system-specific parameters and functions.") module for informational purposes; modifying this value has no effect on the registry keys used by Python. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Windows. `sys._xoptions` A dictionary of the various implementation-specific flags passed through the [`-X`](../using/cmdline#id5) command-line option. Option names are either mapped to their values, if given explicitly, or to [`True`](constants#True "True"). Example: ``` $ ./python -Xa=b -Xc Python 3.2a3+ (py3k, Oct 16 2010, 20:14:50) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys._xoptions {'a': 'b', 'c': True} ``` **CPython implementation detail:** This is a CPython-specific way of accessing options passed through [`-X`](../using/cmdline#id5). Other implementations may export them through other means, or not at all. New in version 3.2. #### Citations `C99` ISO/IEC 9899:1999. “Programming languages – C.” A public draft of this standard is available at <http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf>.
programming_docs
python xml.parsers.expat — Fast XML parsing using Expat xml.parsers.expat — Fast XML parsing using Expat ================================================ Warning The `pyexpat` module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data see [XML vulnerabilities](xml#xml-vulnerabilities). The [`xml.parsers.expat`](#module-xml.parsers.expat "xml.parsers.expat: An interface to the Expat non-validating XML parser.") module is a Python interface to the Expat non-validating XML parser. The module provides a single extension type, `xmlparser`, that represents the current state of an XML parser. After an `xmlparser` object has been created, various attributes of the object can be set to handler functions. When an XML document is then fed to the parser, the handler functions are called for the character data and markup in the XML document. This module uses the `pyexpat` module to provide access to the Expat parser. Direct use of the `pyexpat` module is deprecated. This module provides one exception and one type object: `exception xml.parsers.expat.ExpatError` The exception raised when Expat reports an error. See section [ExpatError Exceptions](#expaterror-objects) for more information on interpreting Expat errors. `exception xml.parsers.expat.error` Alias for [`ExpatError`](#xml.parsers.expat.ExpatError "xml.parsers.expat.ExpatError"). `xml.parsers.expat.XMLParserType` The type of the return values from the [`ParserCreate()`](#xml.parsers.expat.ParserCreate "xml.parsers.expat.ParserCreate") function. The [`xml.parsers.expat`](#module-xml.parsers.expat "xml.parsers.expat: An interface to the Expat non-validating XML parser.") module contains two functions: `xml.parsers.expat.ErrorString(errno)` Returns an explanatory string for a given error number *errno*. `xml.parsers.expat.ParserCreate(encoding=None, namespace_separator=None)` Creates and returns a new `xmlparser` object. *encoding*, if specified, must be a string naming the encoding used by the XML data. Expat doesn’t support as many encodings as Python does, and its repertoire of encodings can’t be extended; it supports UTF-8, UTF-16, ISO-8859-1 (Latin1), and ASCII. If *encoding* [1](#id3) is given it will override the implicit or explicit encoding of the document. Expat can optionally do XML namespace processing for you, enabled by providing a value for *namespace\_separator*. The value must be a one-character string; a [`ValueError`](exceptions#ValueError "ValueError") will be raised if the string has an illegal length (`None` is considered the same as omission). When namespace processing is enabled, element type names and attribute names that belong to a namespace will be expanded. The element name passed to the element handlers `StartElementHandler` and `EndElementHandler` will be the concatenation of the namespace URI, the namespace separator character, and the local part of the name. If the namespace separator is a zero byte (`chr(0)`) then the namespace URI and the local part will be concatenated without any separator. For example, if *namespace\_separator* is set to a space character (`' '`) and the following document is parsed: ``` <?xml version="1.0"?> <root xmlns = "http://default-namespace.org/" xmlns:py = "http://www.python.org/ns/"> <py:elem1 /> <elem2 xmlns="" /> </root> ``` `StartElementHandler` will receive the following strings for each element: ``` http://default-namespace.org/ root http://www.python.org/ns/ elem1 elem2 ``` Due to limitations in the `Expat` library used by `pyexpat`, the `xmlparser` instance returned can only be used to parse a single XML document. Call `ParserCreate` for each document to provide unique parser instances. See also [The Expat XML Parser](http://www.libexpat.org/) Home page of the Expat project. XMLParser Objects ----------------- `xmlparser` objects have the following methods: `xmlparser.Parse(data[, isfinal])` Parses the contents of the string *data*, calling the appropriate handler functions to process the parsed data. *isfinal* must be true on the final call to this method; it allows the parsing of a single file in fragments, not the submission of multiple files. *data* can be the empty string at any time. `xmlparser.ParseFile(file)` Parse XML data reading from the object *file*. *file* only needs to provide the `read(nbytes)` method, returning the empty string when there’s no more data. `xmlparser.SetBase(base)` Sets the base to be used for resolving relative URIs in system identifiers in declarations. Resolving relative identifiers is left to the application: this value will be passed through as the *base* argument to the [`ExternalEntityRefHandler()`](#xml.parsers.expat.xmlparser.ExternalEntityRefHandler "xml.parsers.expat.xmlparser.ExternalEntityRefHandler"), [`NotationDeclHandler()`](#xml.parsers.expat.xmlparser.NotationDeclHandler "xml.parsers.expat.xmlparser.NotationDeclHandler"), and [`UnparsedEntityDeclHandler()`](#xml.parsers.expat.xmlparser.UnparsedEntityDeclHandler "xml.parsers.expat.xmlparser.UnparsedEntityDeclHandler") functions. `xmlparser.GetBase()` Returns a string containing the base set by a previous call to [`SetBase()`](#xml.parsers.expat.xmlparser.SetBase "xml.parsers.expat.xmlparser.SetBase"), or `None` if [`SetBase()`](#xml.parsers.expat.xmlparser.SetBase "xml.parsers.expat.xmlparser.SetBase") hasn’t been called. `xmlparser.GetInputContext()` Returns the input data that generated the current event as a string. The data is in the encoding of the entity which contains the text. When called while an event handler is not active, the return value is `None`. `xmlparser.ExternalEntityParserCreate(context[, encoding])` Create a “child” parser which can be used to parse an external parsed entity referred to by content parsed by the parent parser. The *context* parameter should be the string passed to the [`ExternalEntityRefHandler()`](#xml.parsers.expat.xmlparser.ExternalEntityRefHandler "xml.parsers.expat.xmlparser.ExternalEntityRefHandler") handler function, described below. The child parser is created with the [`ordered_attributes`](#xml.parsers.expat.xmlparser.ordered_attributes "xml.parsers.expat.xmlparser.ordered_attributes") and [`specified_attributes`](#xml.parsers.expat.xmlparser.specified_attributes "xml.parsers.expat.xmlparser.specified_attributes") set to the values of this parser. `xmlparser.SetParamEntityParsing(flag)` Control parsing of parameter entities (including the external DTD subset). Possible *flag* values are `XML_PARAM_ENTITY_PARSING_NEVER`, `XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE` and `XML_PARAM_ENTITY_PARSING_ALWAYS`. Return true if setting the flag was successful. `xmlparser.UseForeignDTD([flag])` Calling this with a true value for *flag* (the default) will cause Expat to call the [`ExternalEntityRefHandler`](#xml.parsers.expat.xmlparser.ExternalEntityRefHandler "xml.parsers.expat.xmlparser.ExternalEntityRefHandler") with [`None`](constants#None "None") for all arguments to allow an alternate DTD to be loaded. If the document does not contain a document type declaration, the [`ExternalEntityRefHandler`](#xml.parsers.expat.xmlparser.ExternalEntityRefHandler "xml.parsers.expat.xmlparser.ExternalEntityRefHandler") will still be called, but the [`StartDoctypeDeclHandler`](#xml.parsers.expat.xmlparser.StartDoctypeDeclHandler "xml.parsers.expat.xmlparser.StartDoctypeDeclHandler") and [`EndDoctypeDeclHandler`](#xml.parsers.expat.xmlparser.EndDoctypeDeclHandler "xml.parsers.expat.xmlparser.EndDoctypeDeclHandler") will not be called. Passing a false value for *flag* will cancel a previous call that passed a true value, but otherwise has no effect. This method can only be called before the [`Parse()`](#xml.parsers.expat.xmlparser.Parse "xml.parsers.expat.xmlparser.Parse") or [`ParseFile()`](#xml.parsers.expat.xmlparser.ParseFile "xml.parsers.expat.xmlparser.ParseFile") methods are called; calling it after either of those have been called causes [`ExpatError`](#xml.parsers.expat.ExpatError "xml.parsers.expat.ExpatError") to be raised with the [`code`](code#module-code "code: Facilities to implement read-eval-print loops.") attribute set to `errors.codes[errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING]`. `xmlparser` objects have the following attributes: `xmlparser.buffer_size` The size of the buffer used when [`buffer_text`](#xml.parsers.expat.xmlparser.buffer_text "xml.parsers.expat.xmlparser.buffer_text") is true. A new buffer size can be set by assigning a new integer value to this attribute. When the size is changed, the buffer will be flushed. `xmlparser.buffer_text` Setting this to true causes the `xmlparser` object to buffer textual content returned by Expat to avoid multiple calls to the [`CharacterDataHandler()`](#xml.parsers.expat.xmlparser.CharacterDataHandler "xml.parsers.expat.xmlparser.CharacterDataHandler") callback whenever possible. This can improve performance substantially since Expat normally breaks character data into chunks at every line ending. This attribute is false by default, and may be changed at any time. `xmlparser.buffer_used` If [`buffer_text`](#xml.parsers.expat.xmlparser.buffer_text "xml.parsers.expat.xmlparser.buffer_text") is enabled, the number of bytes stored in the buffer. These bytes represent UTF-8 encoded text. This attribute has no meaningful interpretation when [`buffer_text`](#xml.parsers.expat.xmlparser.buffer_text "xml.parsers.expat.xmlparser.buffer_text") is false. `xmlparser.ordered_attributes` Setting this attribute to a non-zero integer causes the attributes to be reported as a list rather than a dictionary. The attributes are presented in the order found in the document text. For each attribute, two list entries are presented: the attribute name and the attribute value. (Older versions of this module also used this format.) By default, this attribute is false; it may be changed at any time. `xmlparser.specified_attributes` If set to a non-zero integer, the parser will report only those attributes which were specified in the document instance and not those which were derived from attribute declarations. Applications which set this need to be especially careful to use what additional information is available from the declarations as needed to comply with the standards for the behavior of XML processors. By default, this attribute is false; it may be changed at any time. The following attributes contain values relating to the most recent error encountered by an `xmlparser` object, and will only have correct values once a call to `Parse()` or `ParseFile()` has raised an [`xml.parsers.expat.ExpatError`](#xml.parsers.expat.ExpatError "xml.parsers.expat.ExpatError") exception. `xmlparser.ErrorByteIndex` Byte index at which an error occurred. `xmlparser.ErrorCode` Numeric code specifying the problem. This value can be passed to the [`ErrorString()`](#xml.parsers.expat.ErrorString "xml.parsers.expat.ErrorString") function, or compared to one of the constants defined in the `errors` object. `xmlparser.ErrorColumnNumber` Column number at which an error occurred. `xmlparser.ErrorLineNumber` Line number at which an error occurred. The following attributes contain values relating to the current parse location in an `xmlparser` object. During a callback reporting a parse event they indicate the location of the first of the sequence of characters that generated the event. When called outside of a callback, the position indicated will be just past the last parse event (regardless of whether there was an associated callback). `xmlparser.CurrentByteIndex` Current byte index in the parser input. `xmlparser.CurrentColumnNumber` Current column number in the parser input. `xmlparser.CurrentLineNumber` Current line number in the parser input. Here is the list of handlers that can be set. To set a handler on an `xmlparser` object *o*, use `o.handlername = func`. *handlername* must be taken from the following list, and *func* must be a callable object accepting the correct number of arguments. The arguments are all strings, unless otherwise stated. `xmlparser.XmlDeclHandler(version, encoding, standalone)` Called when the XML declaration is parsed. The XML declaration is the (optional) declaration of the applicable version of the XML recommendation, the encoding of the document text, and an optional “standalone” declaration. *version* and *encoding* will be strings, and *standalone* will be `1` if the document is declared standalone, `0` if it is declared not to be standalone, or `-1` if the standalone clause was omitted. This is only available with Expat version 1.95.0 or newer. `xmlparser.StartDoctypeDeclHandler(doctypeName, systemId, publicId, has_internal_subset)` Called when Expat begins parsing the document type declaration (`<!DOCTYPE ...`). The *doctypeName* is provided exactly as presented. The *systemId* and *publicId* parameters give the system and public identifiers if specified, or `None` if omitted. *has\_internal\_subset* will be true if the document contains and internal document declaration subset. This requires Expat version 1.2 or newer. `xmlparser.EndDoctypeDeclHandler()` Called when Expat is done parsing the document type declaration. This requires Expat version 1.2 or newer. `xmlparser.ElementDeclHandler(name, model)` Called once for each element type declaration. *name* is the name of the element type, and *model* is a representation of the content model. `xmlparser.AttlistDeclHandler(elname, attname, type, default, required)` Called for each declared attribute for an element type. If an attribute list declaration declares three attributes, this handler is called three times, once for each attribute. *elname* is the name of the element to which the declaration applies and *attname* is the name of the attribute declared. The attribute type is a string passed as *type*; the possible values are `'CDATA'`, `'ID'`, `'IDREF'`, … *default* gives the default value for the attribute used when the attribute is not specified by the document instance, or `None` if there is no default value (`#IMPLIED` values). If the attribute is required to be given in the document instance, *required* will be true. This requires Expat version 1.95.0 or newer. `xmlparser.StartElementHandler(name, attributes)` Called for the start of every element. *name* is a string containing the element name, and *attributes* is the element attributes. If [`ordered_attributes`](#xml.parsers.expat.xmlparser.ordered_attributes "xml.parsers.expat.xmlparser.ordered_attributes") is true, this is a list (see [`ordered_attributes`](#xml.parsers.expat.xmlparser.ordered_attributes "xml.parsers.expat.xmlparser.ordered_attributes") for a full description). Otherwise it’s a dictionary mapping names to values. `xmlparser.EndElementHandler(name)` Called for the end of every element. `xmlparser.ProcessingInstructionHandler(target, data)` Called for every processing instruction. `xmlparser.CharacterDataHandler(data)` Called for character data. This will be called for normal character data, CDATA marked content, and ignorable whitespace. Applications which must distinguish these cases can use the [`StartCdataSectionHandler`](#xml.parsers.expat.xmlparser.StartCdataSectionHandler "xml.parsers.expat.xmlparser.StartCdataSectionHandler"), [`EndCdataSectionHandler`](#xml.parsers.expat.xmlparser.EndCdataSectionHandler "xml.parsers.expat.xmlparser.EndCdataSectionHandler"), and [`ElementDeclHandler`](#xml.parsers.expat.xmlparser.ElementDeclHandler "xml.parsers.expat.xmlparser.ElementDeclHandler") callbacks to collect the required information. `xmlparser.UnparsedEntityDeclHandler(entityName, base, systemId, publicId, notationName)` Called for unparsed (NDATA) entity declarations. This is only present for version 1.2 of the Expat library; for more recent versions, use [`EntityDeclHandler`](#xml.parsers.expat.xmlparser.EntityDeclHandler "xml.parsers.expat.xmlparser.EntityDeclHandler") instead. (The underlying function in the Expat library has been declared obsolete.) `xmlparser.EntityDeclHandler(entityName, is_parameter_entity, value, base, systemId, publicId, notationName)` Called for all entity declarations. For parameter and internal entities, *value* will be a string giving the declared contents of the entity; this will be `None` for external entities. The *notationName* parameter will be `None` for parsed entities, and the name of the notation for unparsed entities. *is\_parameter\_entity* will be true if the entity is a parameter entity or false for general entities (most applications only need to be concerned with general entities). This is only available starting with version 1.95.0 of the Expat library. `xmlparser.NotationDeclHandler(notationName, base, systemId, publicId)` Called for notation declarations. *notationName*, *base*, and *systemId*, and *publicId* are strings if given. If the public identifier is omitted, *publicId* will be `None`. `xmlparser.StartNamespaceDeclHandler(prefix, uri)` Called when an element contains a namespace declaration. Namespace declarations are processed before the [`StartElementHandler`](#xml.parsers.expat.xmlparser.StartElementHandler "xml.parsers.expat.xmlparser.StartElementHandler") is called for the element on which declarations are placed. `xmlparser.EndNamespaceDeclHandler(prefix)` Called when the closing tag is reached for an element that contained a namespace declaration. This is called once for each namespace declaration on the element in the reverse of the order for which the [`StartNamespaceDeclHandler`](#xml.parsers.expat.xmlparser.StartNamespaceDeclHandler "xml.parsers.expat.xmlparser.StartNamespaceDeclHandler") was called to indicate the start of each namespace declaration’s scope. Calls to this handler are made after the corresponding [`EndElementHandler`](#xml.parsers.expat.xmlparser.EndElementHandler "xml.parsers.expat.xmlparser.EndElementHandler") for the end of the element. `xmlparser.CommentHandler(data)` Called for comments. *data* is the text of the comment, excluding the leading `'<!-``-'` and trailing `'-``->'`. `xmlparser.StartCdataSectionHandler()` Called at the start of a CDATA section. This and [`EndCdataSectionHandler`](#xml.parsers.expat.xmlparser.EndCdataSectionHandler "xml.parsers.expat.xmlparser.EndCdataSectionHandler") are needed to be able to identify the syntactical start and end for CDATA sections. `xmlparser.EndCdataSectionHandler()` Called at the end of a CDATA section. `xmlparser.DefaultHandler(data)` Called for any characters in the XML document for which no applicable handler has been specified. This means characters that are part of a construct which could be reported, but for which no handler has been supplied. `xmlparser.DefaultHandlerExpand(data)` This is the same as the [`DefaultHandler()`](#xml.parsers.expat.xmlparser.DefaultHandler "xml.parsers.expat.xmlparser.DefaultHandler"), but doesn’t inhibit expansion of internal entities. The entity reference will not be passed to the default handler. `xmlparser.NotStandaloneHandler()` Called if the XML document hasn’t been declared as being a standalone document. This happens when there is an external subset or a reference to a parameter entity, but the XML declaration does not set standalone to `yes` in an XML declaration. If this handler returns `0`, then the parser will raise an `XML_ERROR_NOT_STANDALONE` error. If this handler is not set, no exception is raised by the parser for this condition. `xmlparser.ExternalEntityRefHandler(context, base, systemId, publicId)` Called for references to external entities. *base* is the current base, as set by a previous call to [`SetBase()`](#xml.parsers.expat.xmlparser.SetBase "xml.parsers.expat.xmlparser.SetBase"). The public and system identifiers, *systemId* and *publicId*, are strings if given; if the public identifier is not given, *publicId* will be `None`. The *context* value is opaque and should only be used as described below. For external entities to be parsed, this handler must be implemented. It is responsible for creating the sub-parser using `ExternalEntityParserCreate(context)`, initializing it with the appropriate callbacks, and parsing the entity. This handler should return an integer; if it returns `0`, the parser will raise an `XML_ERROR_EXTERNAL_ENTITY_HANDLING` error, otherwise parsing will continue. If this handler is not provided, external entities are reported by the [`DefaultHandler`](#xml.parsers.expat.xmlparser.DefaultHandler "xml.parsers.expat.xmlparser.DefaultHandler") callback, if provided. ExpatError Exceptions --------------------- [`ExpatError`](#xml.parsers.expat.ExpatError "xml.parsers.expat.ExpatError") exceptions have a number of interesting attributes: `ExpatError.code` Expat’s internal error number for the specific error. The [`errors.messages`](#xml.parsers.expat.errors.messages "xml.parsers.expat.errors.messages") dictionary maps these error numbers to Expat’s error messages. For example: ``` from xml.parsers.expat import ParserCreate, ExpatError, errors p = ParserCreate() try: p.Parse(some_xml_document) except ExpatError as err: print("Error:", errors.messages[err.code]) ``` The [`errors`](#module-xml.parsers.expat.errors "xml.parsers.expat.errors") module also provides error message constants and a dictionary [`codes`](#xml.parsers.expat.errors.codes "xml.parsers.expat.errors.codes") mapping these messages back to the error codes, see below. `ExpatError.lineno` Line number on which the error was detected. The first line is numbered `1`. `ExpatError.offset` Character offset into the line where the error occurred. The first column is numbered `0`. Example ------- The following program defines three handlers that just print out their arguments. ``` import xml.parsers.expat # 3 handler functions def start_element(name, attrs): print('Start element:', name, attrs) def end_element(name): print('End element:', name) def char_data(data): print('Character data:', repr(data)) p = xml.parsers.expat.ParserCreate() p.StartElementHandler = start_element p.EndElementHandler = end_element p.CharacterDataHandler = char_data p.Parse("""<?xml version="1.0"?> <parent id="top"><child1 name="paul">Text goes here</child1> <child2 name="fred">More text</child2> </parent>""", 1) ``` The output from this program is: ``` Start element: parent {'id': 'top'} Start element: child1 {'name': 'paul'} Character data: 'Text goes here' End element: child1 Character data: '\n' Start element: child2 {'name': 'fred'} Character data: 'More text' End element: child2 Character data: '\n' End element: parent ``` Content Model Descriptions -------------------------- Content models are described using nested tuples. Each tuple contains four values: the type, the quantifier, the name, and a tuple of children. Children are simply additional content model descriptions. The values of the first two fields are constants defined in the [`xml.parsers.expat.model`](#module-xml.parsers.expat.model "xml.parsers.expat.model") module. These constants can be collected in two groups: the model type group and the quantifier group. The constants in the model type group are: `xml.parsers.expat.model.XML_CTYPE_ANY` The element named by the model name was declared to have a content model of `ANY`. `xml.parsers.expat.model.XML_CTYPE_CHOICE` The named element allows a choice from a number of options; this is used for content models such as `(A | B | C)`. `xml.parsers.expat.model.XML_CTYPE_EMPTY` Elements which are declared to be `EMPTY` have this model type. `xml.parsers.expat.model.XML_CTYPE_MIXED` `xml.parsers.expat.model.XML_CTYPE_NAME` `xml.parsers.expat.model.XML_CTYPE_SEQ` Models which represent a series of models which follow one after the other are indicated with this model type. This is used for models such as `(A, B, C)`. The constants in the quantifier group are: `xml.parsers.expat.model.XML_CQUANT_NONE` No modifier is given, so it can appear exactly once, as for `A`. `xml.parsers.expat.model.XML_CQUANT_OPT` The model is optional: it can appear once or not at all, as for `A?`. `xml.parsers.expat.model.XML_CQUANT_PLUS` The model must occur one or more times (like `A+`). `xml.parsers.expat.model.XML_CQUANT_REP` The model must occur zero or more times, as for `A*`. Expat error constants --------------------- The following constants are provided in the [`xml.parsers.expat.errors`](#module-xml.parsers.expat.errors "xml.parsers.expat.errors") module. These constants are useful in interpreting some of the attributes of the `ExpatError` exception objects raised when an error has occurred. Since for backwards compatibility reasons, the constants’ value is the error *message* and not the numeric error *code*, you do this by comparing its [`code`](code#module-code "code: Facilities to implement read-eval-print loops.") attribute with `errors.codes[errors.XML_ERROR_*CONSTANT\_NAME*]`. The `errors` module has the following attributes: `xml.parsers.expat.errors.codes` A dictionary mapping string descriptions to their error codes. New in version 3.2. `xml.parsers.expat.errors.messages` A dictionary mapping numeric error codes to their string descriptions. New in version 3.2. `xml.parsers.expat.errors.XML_ERROR_ASYNC_ENTITY` `xml.parsers.expat.errors.XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF` An entity reference in an attribute value referred to an external entity instead of an internal entity. `xml.parsers.expat.errors.XML_ERROR_BAD_CHAR_REF` A character reference referred to a character which is illegal in XML (for example, character `0`, or ‘`&#0;`’). `xml.parsers.expat.errors.XML_ERROR_BINARY_ENTITY_REF` An entity reference referred to an entity which was declared with a notation, so cannot be parsed. `xml.parsers.expat.errors.XML_ERROR_DUPLICATE_ATTRIBUTE` An attribute was used more than once in a start tag. `xml.parsers.expat.errors.XML_ERROR_INCORRECT_ENCODING` `xml.parsers.expat.errors.XML_ERROR_INVALID_TOKEN` Raised when an input byte could not properly be assigned to a character; for example, a NUL byte (value `0`) in a UTF-8 input stream. `xml.parsers.expat.errors.XML_ERROR_JUNK_AFTER_DOC_ELEMENT` Something other than whitespace occurred after the document element. `xml.parsers.expat.errors.XML_ERROR_MISPLACED_XML_PI` An XML declaration was found somewhere other than the start of the input data. `xml.parsers.expat.errors.XML_ERROR_NO_ELEMENTS` The document contains no elements (XML requires all documents to contain exactly one top-level element).. `xml.parsers.expat.errors.XML_ERROR_NO_MEMORY` Expat was not able to allocate memory internally. `xml.parsers.expat.errors.XML_ERROR_PARAM_ENTITY_REF` A parameter entity reference was found where it was not allowed. `xml.parsers.expat.errors.XML_ERROR_PARTIAL_CHAR` An incomplete character was found in the input. `xml.parsers.expat.errors.XML_ERROR_RECURSIVE_ENTITY_REF` An entity reference contained another reference to the same entity; possibly via a different name, and possibly indirectly. `xml.parsers.expat.errors.XML_ERROR_SYNTAX` Some unspecified syntax error was encountered. `xml.parsers.expat.errors.XML_ERROR_TAG_MISMATCH` An end tag did not match the innermost open start tag. `xml.parsers.expat.errors.XML_ERROR_UNCLOSED_TOKEN` Some token (such as a start tag) was not closed before the end of the stream or the next token was encountered. `xml.parsers.expat.errors.XML_ERROR_UNDEFINED_ENTITY` A reference was made to an entity which was not defined. `xml.parsers.expat.errors.XML_ERROR_UNKNOWN_ENCODING` The document encoding is not supported by Expat. `xml.parsers.expat.errors.XML_ERROR_UNCLOSED_CDATA_SECTION` A CDATA marked section was not closed. `xml.parsers.expat.errors.XML_ERROR_EXTERNAL_ENTITY_HANDLING` `xml.parsers.expat.errors.XML_ERROR_NOT_STANDALONE` The parser determined that the document was not “standalone” though it declared itself to be in the XML declaration, and the `NotStandaloneHandler` was set and returned `0`. `xml.parsers.expat.errors.XML_ERROR_UNEXPECTED_STATE` `xml.parsers.expat.errors.XML_ERROR_ENTITY_DECLARED_IN_PE` `xml.parsers.expat.errors.XML_ERROR_FEATURE_REQUIRES_XML_DTD` An operation was requested that requires DTD support to be compiled in, but Expat was configured without DTD support. This should never be reported by a standard build of the [`xml.parsers.expat`](#module-xml.parsers.expat "xml.parsers.expat: An interface to the Expat non-validating XML parser.") module. `xml.parsers.expat.errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING` A behavioral change was requested after parsing started that can only be changed before parsing has started. This is (currently) only raised by `UseForeignDTD()`. `xml.parsers.expat.errors.XML_ERROR_UNBOUND_PREFIX` An undeclared prefix was found when namespace processing was enabled. `xml.parsers.expat.errors.XML_ERROR_UNDECLARING_PREFIX` The document attempted to remove the namespace declaration associated with a prefix. `xml.parsers.expat.errors.XML_ERROR_INCOMPLETE_PE` A parameter entity contained incomplete markup. `xml.parsers.expat.errors.XML_ERROR_XML_DECL` The document contained no document element at all. `xml.parsers.expat.errors.XML_ERROR_TEXT_DECL` There was an error parsing a text declaration in an external entity. `xml.parsers.expat.errors.XML_ERROR_PUBLICID` Characters were found in the public id that are not allowed. `xml.parsers.expat.errors.XML_ERROR_SUSPENDED` The requested operation was made on a suspended parser, but isn’t allowed. This includes attempts to provide additional input or to stop the parser. `xml.parsers.expat.errors.XML_ERROR_NOT_SUSPENDED` An attempt to resume the parser was made when the parser had not been suspended. `xml.parsers.expat.errors.XML_ERROR_ABORTED` This should not be reported to Python applications. `xml.parsers.expat.errors.XML_ERROR_FINISHED` The requested operation was made on a parser which was finished parsing input, but isn’t allowed. This includes attempts to provide additional input or to stop the parser. `xml.parsers.expat.errors.XML_ERROR_SUSPEND_PE` #### Footnotes `1` The encoding string included in XML output should conform to the appropriate standards. For example, “UTF-8” is valid, but “UTF8” is not. See <https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl> and <https://www.iana.org/assignments/character-sets/character-sets.xhtml>.
programming_docs
python Distributing Python Modules Distributing Python Modules =========================== Email [[email protected]](mailto:distutils-sig%40python.org) As a popular open source development project, Python has an active supporting community of contributors and users that also make their software available for other Python developers to use under open source license terms. This allows Python users to share and collaborate effectively, benefiting from the solutions others have already created to common (and sometimes even rare!) problems, as well as potentially contributing their own solutions to the common pool. This guide covers the distribution part of the process. For a guide to installing other Python projects, refer to the [installation guide](../installing/index#installing-index). Note For corporate and other institutional users, be aware that many organisations have their own policies around using and contributing to open source software. Please take such policies into account when making use of the distribution and installation tools provided with Python. Key terms --------- * the [Python Package Index](https://pypi.org) is a public repository of open source licensed packages made available for use by other Python users * the [Python Packaging Authority](https://www.pypa.io/) are the group of developers and documentation authors responsible for the maintenance and evolution of the standard packaging tools and the associated metadata and file format standards. They maintain a variety of tools, documentation and issue trackers on both [GitHub](https://github.com/pypa) and [Bitbucket](https://bitbucket.org/pypa/). * [`distutils`](../library/distutils#module-distutils "distutils: Support for building and installing Python modules into an existing Python installation.") is the original build and distribution system first added to the Python standard library in 1998. While direct use of [`distutils`](../library/distutils#module-distutils "distutils: Support for building and installing Python modules into an existing Python installation.") is being phased out, it still laid the foundation for the current packaging and distribution infrastructure, and it not only remains part of the standard library, but its name lives on in other ways (such as the name of the mailing list used to coordinate Python packaging standards development). * [setuptools](https://setuptools.readthedocs.io/en/latest/) is a (largely) drop-in replacement for [`distutils`](../library/distutils#module-distutils "distutils: Support for building and installing Python modules into an existing Python installation.") first published in 2004. Its most notable addition over the unmodified [`distutils`](../library/distutils#module-distutils "distutils: Support for building and installing Python modules into an existing Python installation.") tools was the ability to declare dependencies on other packages. It is currently recommended as a more regularly updated alternative to [`distutils`](../library/distutils#module-distutils "distutils: Support for building and installing Python modules into an existing Python installation.") that offers consistent support for more recent packaging standards across a wide range of Python versions. * [wheel](https://wheel.readthedocs.io/) (in this context) is a project that adds the `bdist_wheel` command to [`distutils`](../library/distutils#module-distutils "distutils: Support for building and installing Python modules into an existing Python installation.")/[setuptools](https://setuptools.readthedocs.io/en/latest/). This produces a cross platform binary packaging format (called “wheels” or “wheel files” and defined in [**PEP 427**](https://www.python.org/dev/peps/pep-0427)) that allows Python libraries, even those including binary extensions, to be installed on a system without needing to be built locally. Open source licensing and collaboration --------------------------------------- In most parts of the world, software is automatically covered by copyright. This means that other developers require explicit permission to copy, use, modify and redistribute the software. Open source licensing is a way of explicitly granting such permission in a relatively consistent way, allowing developers to share and collaborate efficiently by making common solutions to various problems freely available. This leaves many developers free to spend more time focusing on the problems that are relatively unique to their specific situation. The distribution tools provided with Python are designed to make it reasonably straightforward for developers to make their own contributions back to that common pool of software if they choose to do so. The same distribution tools can also be used to distribute software within an organisation, regardless of whether that software is published as open source software or not. Installing the tools -------------------- The standard library does not include build tools that support modern Python packaging standards, as the core development team has found that it is important to have standard tools that work consistently, even on older versions of Python. The currently recommended build and distribution tools can be installed by invoking the `pip` module at the command line: ``` python -m pip install setuptools wheel twine ``` Note For POSIX users (including macOS and Linux users), these instructions assume the use of a [virtual environment](../glossary#term-virtual-environment). For Windows users, these instructions assume that the option to adjust the system PATH environment variable was selected when installing Python. The Python Packaging User Guide includes more details on the [currently recommended tools](https://packaging.python.org/guides/tool-recommendations/#packaging-tool-recommendations). Reading the Python Packaging User Guide --------------------------------------- The Python Packaging User Guide covers the various key steps and elements involved in creating and publishing a project: * [Project structure](https://packaging.python.org/tutorials/packaging-projects/#packaging-python-projects) * [Building and packaging the project](https://packaging.python.org/tutorials/packaging-projects/#creating-the-package-files) * [Uploading the project to the Python Package Index](https://packaging.python.org/tutorials/packaging-projects/#uploading-the-distribution-archives) * [The .pypirc file](https://packaging.python.org/specifications/pypirc/) How do I…? ---------- These are quick answers or links for some common tasks. ### … choose a name for my project? This isn’t an easy topic, but here are a few tips: * check the Python Package Index to see if the name is already in use * check popular hosting sites like GitHub, Bitbucket, etc to see if there is already a project with that name * check what comes up in a web search for the name you’re considering * avoid particularly common words, especially ones with multiple meanings, as they can make it difficult for users to find your software when searching for it ### … create and distribute binary extensions? This is actually quite a complex topic, with a variety of alternatives available depending on exactly what you’re aiming to achieve. See the Python Packaging User Guide for more information and recommendations. See also [Python Packaging User Guide: Binary Extensions](https://packaging.python.org/guides/packaging-binary-extensions/) python Extending and Embedding the Python Interpreter Extending and Embedding the Python Interpreter ============================================== This document describes how to write modules in C or C++ to extend the Python interpreter with new modules. Those modules can not only define new functions but also new object types and their methods. The document also describes how to embed the Python interpreter in another application, for use as an extension language. Finally, it shows how to compile and link extension modules so that they can be loaded dynamically (at run time) into the interpreter, if the underlying operating system supports this feature. This document assumes basic knowledge about Python. For an informal introduction to the language, see [The Python Tutorial](../tutorial/index#tutorial-index). [The Python Language Reference](../reference/index#reference-index) gives a more formal definition of the language. [The Python Standard Library](../library/index#library-index) documents the existing object types, functions and modules (both built-in and written in Python) that give the language its wide application range. For a detailed description of the whole Python/C API, see the separate [Python/C API Reference Manual](../c-api/index#c-api-index). Recommended third party tools ----------------------------- This guide only covers the basic tools for creating extensions provided as part of this version of CPython. Third party tools like [Cython](http://cython.org/), [cffi](https://cffi.readthedocs.io), [SWIG](http://www.swig.org) and [Numba](https://numba.pydata.org/) offer both simpler and more sophisticated approaches to creating C and C++ extensions for Python. See also [Python Packaging User Guide: Binary Extensions](https://packaging.python.org/guides/packaging-binary-extensions/) The Python Packaging User Guide not only covers several available tools that simplify the creation of binary extensions, but also discusses the various reasons why creating an extension module may be desirable in the first place. Creating extensions without third party tools --------------------------------------------- This section of the guide covers creating C and C++ extensions without assistance from third party tools. It is intended primarily for creators of those tools, rather than being a recommended way to create your own C extensions. * [1. Extending Python with C or C++](extending) + [1.1. A Simple Example](extending#a-simple-example) + [1.2. Intermezzo: Errors and Exceptions](extending#intermezzo-errors-and-exceptions) + [1.3. Back to the Example](extending#back-to-the-example) + [1.4. The Module’s Method Table and Initialization Function](extending#the-module-s-method-table-and-initialization-function) + [1.5. Compilation and Linkage](extending#compilation-and-linkage) + [1.6. Calling Python Functions from C](extending#calling-python-functions-from-c) + [1.7. Extracting Parameters in Extension Functions](extending#extracting-parameters-in-extension-functions) + [1.8. Keyword Parameters for Extension Functions](extending#keyword-parameters-for-extension-functions) + [1.9. Building Arbitrary Values](extending#building-arbitrary-values) + [1.10. Reference Counts](extending#reference-counts) + [1.11. Writing Extensions in C++](extending#writing-extensions-in-c) + [1.12. Providing a C API for an Extension Module](extending#providing-a-c-api-for-an-extension-module) * [2. Defining Extension Types: Tutorial](newtypes_tutorial) + [2.1. The Basics](newtypes_tutorial#the-basics) + [2.2. Adding data and methods to the Basic example](newtypes_tutorial#adding-data-and-methods-to-the-basic-example) + [2.3. Providing finer control over data attributes](newtypes_tutorial#providing-finer-control-over-data-attributes) + [2.4. Supporting cyclic garbage collection](newtypes_tutorial#supporting-cyclic-garbage-collection) + [2.5. Subclassing other types](newtypes_tutorial#subclassing-other-types) * [3. Defining Extension Types: Assorted Topics](newtypes) + [3.1. Finalization and De-allocation](newtypes#finalization-and-de-allocation) + [3.2. Object Presentation](newtypes#object-presentation) + [3.3. Attribute Management](newtypes#attribute-management) + [3.4. Object Comparison](newtypes#object-comparison) + [3.5. Abstract Protocol Support](newtypes#abstract-protocol-support) + [3.6. Weak Reference Support](newtypes#weak-reference-support) + [3.7. More Suggestions](newtypes#more-suggestions) * [4. Building C and C++ Extensions](building) + [4.1. Building C and C++ Extensions with distutils](building#building-c-and-c-extensions-with-distutils) + [4.2. Distributing your extension modules](building#distributing-your-extension-modules) * [5. Building C and C++ Extensions on Windows](windows) + [5.1. A Cookbook Approach](windows#a-cookbook-approach) + [5.2. Differences Between Unix and Windows](windows#differences-between-unix-and-windows) + [5.3. Using DLLs in Practice](windows#using-dlls-in-practice) Embedding the CPython runtime in a larger application ----------------------------------------------------- Sometimes, rather than creating an extension that runs inside the Python interpreter as the main application, it is desirable to instead embed the CPython runtime inside a larger application. This section covers some of the details involved in doing that successfully. * [1. Embedding Python in Another Application](embedding) + [1.1. Very High Level Embedding](embedding#very-high-level-embedding) + [1.2. Beyond Very High Level Embedding: An overview](embedding#beyond-very-high-level-embedding-an-overview) + [1.3. Pure Embedding](embedding#pure-embedding) + [1.4. Extending Embedded Python](embedding#extending-embedded-python) + [1.5. Embedding Python in C++](embedding#embedding-python-in-c) + [1.6. Compiling and Linking under Unix-like systems](embedding#compiling-and-linking-under-unix-like-systems) python Defining Extension Types: Assorted Topics Defining Extension Types: Assorted Topics ========================================== This section aims to give a quick fly-by on the various type methods you can implement and what they do. Here is the definition of [`PyTypeObject`](../c-api/type#c.PyTypeObject "PyTypeObject"), with some fields only used in debug builds omitted: ``` typedef struct _typeobject { PyObject_VAR_HEAD const char *tp_name; /* For printing, in format "<module>.<name>" */ Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */ /* Methods to implement standard operations */ destructor tp_dealloc; Py_ssize_t tp_vectorcall_offset; getattrfunc tp_getattr; setattrfunc tp_setattr; PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2) or tp_reserved (Python 3) */ reprfunc tp_repr; /* Method suites for standard classes */ PyNumberMethods *tp_as_number; PySequenceMethods *tp_as_sequence; PyMappingMethods *tp_as_mapping; /* More standard operations (here for binary compatibility) */ hashfunc tp_hash; ternaryfunc tp_call; reprfunc tp_str; getattrofunc tp_getattro; setattrofunc tp_setattro; /* Functions to access object as input/output buffer */ PyBufferProcs *tp_as_buffer; /* Flags to define presence of optional/expanded features */ unsigned long tp_flags; const char *tp_doc; /* Documentation string */ /* call function for all accessible objects */ traverseproc tp_traverse; /* delete references to contained objects */ inquiry tp_clear; /* rich comparisons */ richcmpfunc tp_richcompare; /* weak reference enabler */ Py_ssize_t tp_weaklistoffset; /* Iterators */ getiterfunc tp_iter; iternextfunc tp_iternext; /* Attribute descriptor and subclassing stuff */ struct PyMethodDef *tp_methods; struct PyMemberDef *tp_members; struct PyGetSetDef *tp_getset; struct _typeobject *tp_base; PyObject *tp_dict; descrgetfunc tp_descr_get; descrsetfunc tp_descr_set; Py_ssize_t tp_dictoffset; initproc tp_init; allocfunc tp_alloc; newfunc tp_new; freefunc tp_free; /* Low-level free-memory routine */ inquiry tp_is_gc; /* For PyObject_IS_GC */ PyObject *tp_bases; PyObject *tp_mro; /* method resolution order */ PyObject *tp_cache; PyObject *tp_subclasses; PyObject *tp_weaklist; destructor tp_del; /* Type attribute cache version tag. Added in version 2.6 */ unsigned int tp_version_tag; destructor tp_finalize; } PyTypeObject; ``` Now that’s a *lot* of methods. Don’t worry too much though – if you have a type you want to define, the chances are very good that you will only implement a handful of these. As you probably expect by now, we’re going to go over this and give more information about the various handlers. We won’t go in the order they are defined in the structure, because there is a lot of historical baggage that impacts the ordering of the fields. It’s often easiest to find an example that includes the fields you need and then change the values to suit your new type. ``` const char *tp_name; /* For printing */ ``` The name of the type – as mentioned in the previous chapter, this will appear in various places, almost entirely for diagnostic purposes. Try to choose something that will be helpful in such a situation! ``` Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */ ``` These fields tell the runtime how much memory to allocate when new objects of this type are created. Python has some built-in support for variable length structures (think: strings, tuples) which is where the [`tp_itemsize`](../c-api/typeobj#c.PyTypeObject.tp_itemsize "PyTypeObject.tp_itemsize") field comes in. This will be dealt with later. ``` const char *tp_doc; ``` Here you can put a string (or its address) that you want returned when the Python script references `obj.__doc__` to retrieve the doc string. Now we come to the basic type methods – the ones most extension types will implement. 3.1. Finalization and De-allocation ------------------------------------ ``` destructor tp_dealloc; ``` This function is called when the reference count of the instance of your type is reduced to zero and the Python interpreter wants to reclaim it. If your type has memory to free or other clean-up to perform, you can put it here. The object itself needs to be freed here as well. Here is an example of this function: ``` static void newdatatype_dealloc(newdatatypeobject *obj) { free(obj->obj_UnderlyingDatatypePtr); Py_TYPE(obj)->tp_free((PyObject *)obj); } ``` If your type supports garbage collection, the destructor should call [`PyObject_GC_UnTrack()`](../c-api/gcsupport#c.PyObject_GC_UnTrack "PyObject_GC_UnTrack") before clearing any member fields: ``` static void newdatatype_dealloc(newdatatypeobject *obj) { PyObject_GC_UnTrack(obj); Py_CLEAR(obj->other_obj); ... Py_TYPE(obj)->tp_free((PyObject *)obj); } ``` One important requirement of the deallocator function is that it leaves any pending exceptions alone. This is important since deallocators are frequently called as the interpreter unwinds the Python stack; when the stack is unwound due to an exception (rather than normal returns), nothing is done to protect the deallocators from seeing that an exception has already been set. Any actions which a deallocator performs which may cause additional Python code to be executed may detect that an exception has been set. This can lead to misleading errors from the interpreter. The proper way to protect against this is to save a pending exception before performing the unsafe action, and restoring it when done. This can be done using the [`PyErr_Fetch()`](../c-api/exceptions#c.PyErr_Fetch "PyErr_Fetch") and [`PyErr_Restore()`](../c-api/exceptions#c.PyErr_Restore "PyErr_Restore") functions: ``` static void my_dealloc(PyObject *obj) { MyObject *self = (MyObject *) obj; PyObject *cbresult; if (self->my_callback != NULL) { PyObject *err_type, *err_value, *err_traceback; /* This saves the current exception state */ PyErr_Fetch(&err_type, &err_value, &err_traceback); cbresult = PyObject_CallNoArgs(self->my_callback); if (cbresult == NULL) PyErr_WriteUnraisable(self->my_callback); else Py_DECREF(cbresult); /* This restores the saved exception state */ PyErr_Restore(err_type, err_value, err_traceback); Py_DECREF(self->my_callback); } Py_TYPE(obj)->tp_free((PyObject*)self); } ``` Note There are limitations to what you can safely do in a deallocator function. First, if your type supports garbage collection (using [`tp_traverse`](../c-api/typeobj#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse") and/or [`tp_clear`](../c-api/typeobj#c.PyTypeObject.tp_clear "PyTypeObject.tp_clear")), some of the object’s members can have been cleared or finalized by the time [`tp_dealloc`](../c-api/typeobj#c.PyTypeObject.tp_dealloc "PyTypeObject.tp_dealloc") is called. Second, in [`tp_dealloc`](../c-api/typeobj#c.PyTypeObject.tp_dealloc "PyTypeObject.tp_dealloc"), your object is in an unstable state: its reference count is equal to zero. Any call to a non-trivial object or API (as in the example above) might end up calling [`tp_dealloc`](../c-api/typeobj#c.PyTypeObject.tp_dealloc "PyTypeObject.tp_dealloc") again, causing a double free and a crash. Starting with Python 3.4, it is recommended not to put any complex finalization code in [`tp_dealloc`](../c-api/typeobj#c.PyTypeObject.tp_dealloc "PyTypeObject.tp_dealloc"), and instead use the new [`tp_finalize`](../c-api/typeobj#c.PyTypeObject.tp_finalize "PyTypeObject.tp_finalize") type method. See also [**PEP 442**](https://www.python.org/dev/peps/pep-0442) explains the new finalization scheme. 3.2. Object Presentation ------------------------- In Python, there are two ways to generate a textual representation of an object: the [`repr()`](../library/functions#repr "repr") function, and the [`str()`](../library/stdtypes#str "str") function. (The [`print()`](../library/functions#print "print") function just calls [`str()`](../library/stdtypes#str "str").) These handlers are both optional. ``` reprfunc tp_repr; reprfunc tp_str; ``` The [`tp_repr`](../c-api/typeobj#c.PyTypeObject.tp_repr "PyTypeObject.tp_repr") handler should return a string object containing a representation of the instance for which it is called. Here is a simple example: ``` static PyObject * newdatatype_repr(newdatatypeobject * obj) { return PyUnicode_FromFormat("Repr-ified_newdatatype{{size:%d}}", obj->obj_UnderlyingDatatypePtr->size); } ``` If no [`tp_repr`](../c-api/typeobj#c.PyTypeObject.tp_repr "PyTypeObject.tp_repr") handler is specified, the interpreter will supply a representation that uses the type’s [`tp_name`](../c-api/typeobj#c.PyTypeObject.tp_name "PyTypeObject.tp_name") and a uniquely-identifying value for the object. The [`tp_str`](../c-api/typeobj#c.PyTypeObject.tp_str "PyTypeObject.tp_str") handler is to [`str()`](../library/stdtypes#str "str") what the [`tp_repr`](../c-api/typeobj#c.PyTypeObject.tp_repr "PyTypeObject.tp_repr") handler described above is to [`repr()`](../library/functions#repr "repr"); that is, it is called when Python code calls [`str()`](../library/stdtypes#str "str") on an instance of your object. Its implementation is very similar to the [`tp_repr`](../c-api/typeobj#c.PyTypeObject.tp_repr "PyTypeObject.tp_repr") function, but the resulting string is intended for human consumption. If [`tp_str`](../c-api/typeobj#c.PyTypeObject.tp_str "PyTypeObject.tp_str") is not specified, the [`tp_repr`](../c-api/typeobj#c.PyTypeObject.tp_repr "PyTypeObject.tp_repr") handler is used instead. Here is a simple example: ``` static PyObject * newdatatype_str(newdatatypeobject * obj) { return PyUnicode_FromFormat("Stringified_newdatatype{{size:%d}}", obj->obj_UnderlyingDatatypePtr->size); } ``` 3.3. Attribute Management -------------------------- For every object which can support attributes, the corresponding type must provide the functions that control how the attributes are resolved. There needs to be a function which can retrieve attributes (if any are defined), and another to set attributes (if setting attributes is allowed). Removing an attribute is a special case, for which the new value passed to the handler is `NULL`. Python supports two pairs of attribute handlers; a type that supports attributes only needs to implement the functions for one pair. The difference is that one pair takes the name of the attribute as a `char*`, while the other accepts a [`PyObject*`](../c-api/structures#c.PyObject "PyObject"). Each type can use whichever pair makes more sense for the implementation’s convenience. ``` getattrfunc tp_getattr; /* char * version */ setattrfunc tp_setattr; /* ... */ getattrofunc tp_getattro; /* PyObject * version */ setattrofunc tp_setattro; ``` If accessing attributes of an object is always a simple operation (this will be explained shortly), there are generic implementations which can be used to provide the [`PyObject*`](../c-api/structures#c.PyObject "PyObject") version of the attribute management functions. The actual need for type-specific attribute handlers almost completely disappeared starting with Python 2.2, though there are many examples which have not been updated to use some of the new generic mechanism that is available. ### 3.3.1. Generic Attribute Management Most extension types only use *simple* attributes. So, what makes the attributes simple? There are only a couple of conditions that must be met: 1. The name of the attributes must be known when [`PyType_Ready()`](../c-api/type#c.PyType_Ready "PyType_Ready") is called. 2. No special processing is needed to record that an attribute was looked up or set, nor do actions need to be taken based on the value. Note that this list does not place any restrictions on the values of the attributes, when the values are computed, or how relevant data is stored. When [`PyType_Ready()`](../c-api/type#c.PyType_Ready "PyType_Ready") is called, it uses three tables referenced by the type object to create [descriptor](../glossary#term-descriptor)s which are placed in the dictionary of the type object. Each descriptor controls access to one attribute of the instance object. Each of the tables is optional; if all three are `NULL`, instances of the type will only have attributes that are inherited from their base type, and should leave the [`tp_getattro`](../c-api/typeobj#c.PyTypeObject.tp_getattro "PyTypeObject.tp_getattro") and [`tp_setattro`](../c-api/typeobj#c.PyTypeObject.tp_setattro "PyTypeObject.tp_setattro") fields `NULL` as well, allowing the base type to handle attributes. The tables are declared as three fields of the type object: ``` struct PyMethodDef *tp_methods; struct PyMemberDef *tp_members; struct PyGetSetDef *tp_getset; ``` If [`tp_methods`](../c-api/typeobj#c.PyTypeObject.tp_methods "PyTypeObject.tp_methods") is not `NULL`, it must refer to an array of [`PyMethodDef`](../c-api/structures#c.PyMethodDef "PyMethodDef") structures. Each entry in the table is an instance of this structure: ``` typedef struct PyMethodDef { const char *ml_name; /* method name */ PyCFunction ml_meth; /* implementation function */ int ml_flags; /* flags */ const char *ml_doc; /* docstring */ } PyMethodDef; ``` One entry should be defined for each method provided by the type; no entries are needed for methods inherited from a base type. One additional entry is needed at the end; it is a sentinel that marks the end of the array. The `ml_name` field of the sentinel must be `NULL`. The second table is used to define attributes which map directly to data stored in the instance. A variety of primitive C types are supported, and access may be read-only or read-write. The structures in the table are defined as: ``` typedef struct PyMemberDef { const char *name; int type; int offset; int flags; const char *doc; } PyMemberDef; ``` For each entry in the table, a [descriptor](../glossary#term-descriptor) will be constructed and added to the type which will be able to extract a value from the instance structure. The [`type`](../library/functions#type "type") field should contain one of the type codes defined in the `structmember.h` header; the value will be used to determine how to convert Python values to and from C values. The `flags` field is used to store flags which control how the attribute can be accessed. The following flag constants are defined in `structmember.h`; they may be combined using bitwise-OR. | Constant | Meaning | | --- | --- | | `READONLY` | Never writable. | | `READ_RESTRICTED` | Not readable in restricted mode. | | `WRITE_RESTRICTED` | Not writable in restricted mode. | | `RESTRICTED` | Not readable or writable in restricted mode. | An interesting advantage of using the [`tp_members`](../c-api/typeobj#c.PyTypeObject.tp_members "PyTypeObject.tp_members") table to build descriptors that are used at runtime is that any attribute defined this way can have an associated doc string simply by providing the text in the table. An application can use the introspection API to retrieve the descriptor from the class object, and get the doc string using its `__doc__` attribute. As with the [`tp_methods`](../c-api/typeobj#c.PyTypeObject.tp_methods "PyTypeObject.tp_methods") table, a sentinel entry with a `name` value of `NULL` is required. ### 3.3.2. Type-specific Attribute Management For simplicity, only the `char*` version will be demonstrated here; the type of the name parameter is the only difference between the `char*` and [`PyObject*`](../c-api/structures#c.PyObject "PyObject") flavors of the interface. This example effectively does the same thing as the generic example above, but does not use the generic support added in Python 2.2. It explains how the handler functions are called, so that if you do need to extend their functionality, you’ll understand what needs to be done. The [`tp_getattr`](../c-api/typeobj#c.PyTypeObject.tp_getattr "PyTypeObject.tp_getattr") handler is called when the object requires an attribute look-up. It is called in the same situations where the [`__getattr__()`](../reference/datamodel#object.__getattr__ "object.__getattr__") method of a class would be called. Here is an example: ``` static PyObject * newdatatype_getattr(newdatatypeobject *obj, char *name) { if (strcmp(name, "data") == 0) { return PyLong_FromLong(obj->data); } PyErr_Format(PyExc_AttributeError, "'%.50s' object has no attribute '%.400s'", tp->tp_name, name); return NULL; } ``` The [`tp_setattr`](../c-api/typeobj#c.PyTypeObject.tp_setattr "PyTypeObject.tp_setattr") handler is called when the [`__setattr__()`](../reference/datamodel#object.__setattr__ "object.__setattr__") or [`__delattr__()`](../reference/datamodel#object.__delattr__ "object.__delattr__") method of a class instance would be called. When an attribute should be deleted, the third parameter will be `NULL`. Here is an example that simply raises an exception; if this were really all you wanted, the [`tp_setattr`](../c-api/typeobj#c.PyTypeObject.tp_setattr "PyTypeObject.tp_setattr") handler should be set to `NULL`. ``` static int newdatatype_setattr(newdatatypeobject *obj, char *name, PyObject *v) { PyErr_Format(PyExc_RuntimeError, "Read-only attribute: %s", name); return -1; } ``` 3.4. Object Comparison ----------------------- ``` richcmpfunc tp_richcompare; ``` The [`tp_richcompare`](../c-api/typeobj#c.PyTypeObject.tp_richcompare "PyTypeObject.tp_richcompare") handler is called when comparisons are needed. It is analogous to the [rich comparison methods](../reference/datamodel#richcmpfuncs), like [`__lt__()`](../reference/datamodel#object.__lt__ "object.__lt__"), and also called by [`PyObject_RichCompare()`](../c-api/object#c.PyObject_RichCompare "PyObject_RichCompare") and [`PyObject_RichCompareBool()`](../c-api/object#c.PyObject_RichCompareBool "PyObject_RichCompareBool"). This function is called with two Python objects and the operator as arguments, where the operator is one of `Py_EQ`, `Py_NE`, `Py_LE`, `Py_GE`, `Py_LT` or `Py_GT`. It should compare the two objects with respect to the specified operator and return `Py_True` or `Py_False` if the comparison is successful, `Py_NotImplemented` to indicate that comparison is not implemented and the other object’s comparison method should be tried, or `NULL` if an exception was set. Here is a sample implementation, for a datatype that is considered equal if the size of an internal pointer is equal: ``` static PyObject * newdatatype_richcmp(PyObject *obj1, PyObject *obj2, int op) { PyObject *result; int c, size1, size2; /* code to make sure that both arguments are of type newdatatype omitted */ size1 = obj1->obj_UnderlyingDatatypePtr->size; size2 = obj2->obj_UnderlyingDatatypePtr->size; switch (op) { case Py_LT: c = size1 < size2; break; case Py_LE: c = size1 <= size2; break; case Py_EQ: c = size1 == size2; break; case Py_NE: c = size1 != size2; break; case Py_GT: c = size1 > size2; break; case Py_GE: c = size1 >= size2; break; } result = c ? Py_True : Py_False; Py_INCREF(result); return result; } ``` 3.5. Abstract Protocol Support ------------------------------- Python supports a variety of *abstract* ‘protocols;’ the specific interfaces provided to use these interfaces are documented in [Abstract Objects Layer](../c-api/abstract#abstract). A number of these abstract interfaces were defined early in the development of the Python implementation. In particular, the number, mapping, and sequence protocols have been part of Python since the beginning. Other protocols have been added over time. For protocols which depend on several handler routines from the type implementation, the older protocols have been defined as optional blocks of handlers referenced by the type object. For newer protocols there are additional slots in the main type object, with a flag bit being set to indicate that the slots are present and should be checked by the interpreter. (The flag bit does not indicate that the slot values are non-`NULL`. The flag may be set to indicate the presence of a slot, but a slot may still be unfilled.) ``` PyNumberMethods *tp_as_number; PySequenceMethods *tp_as_sequence; PyMappingMethods *tp_as_mapping; ``` If you wish your object to be able to act like a number, a sequence, or a mapping object, then you place the address of a structure that implements the C type [`PyNumberMethods`](../c-api/typeobj#c.PyNumberMethods "PyNumberMethods"), [`PySequenceMethods`](../c-api/typeobj#c.PySequenceMethods "PySequenceMethods"), or [`PyMappingMethods`](../c-api/typeobj#c.PyMappingMethods "PyMappingMethods"), respectively. It is up to you to fill in this structure with appropriate values. You can find examples of the use of each of these in the `Objects` directory of the Python source distribution. ``` hashfunc tp_hash; ``` This function, if you choose to provide it, should return a hash number for an instance of your data type. Here is a simple example: ``` static Py_hash_t newdatatype_hash(newdatatypeobject *obj) { Py_hash_t result; result = obj->some_size + 32767 * obj->some_number; if (result == -1) result = -2; return result; } ``` `Py_hash_t` is a signed integer type with a platform-varying width. Returning `-1` from [`tp_hash`](../c-api/typeobj#c.PyTypeObject.tp_hash "PyTypeObject.tp_hash") indicates an error, which is why you should be careful to avoid returning it when hash computation is successful, as seen above. ``` ternaryfunc tp_call; ``` This function is called when an instance of your data type is “called”, for example, if `obj1` is an instance of your data type and the Python script contains `obj1('hello')`, the [`tp_call`](../c-api/typeobj#c.PyTypeObject.tp_call "PyTypeObject.tp_call") handler is invoked. This function takes three arguments: 1. *self* is the instance of the data type which is the subject of the call. If the call is `obj1('hello')`, then *self* is `obj1`. 2. *args* is a tuple containing the arguments to the call. You can use [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple") to extract the arguments. 3. *kwds* is a dictionary of keyword arguments that were passed. If this is non-`NULL` and you support keyword arguments, use [`PyArg_ParseTupleAndKeywords()`](../c-api/arg#c.PyArg_ParseTupleAndKeywords "PyArg_ParseTupleAndKeywords") to extract the arguments. If you do not want to support keyword arguments and this is non-`NULL`, raise a [`TypeError`](../library/exceptions#TypeError "TypeError") with a message saying that keyword arguments are not supported. Here is a toy `tp_call` implementation: ``` static PyObject * newdatatype_call(newdatatypeobject *self, PyObject *args, PyObject *kwds) { PyObject *result; const char *arg1; const char *arg2; const char *arg3; if (!PyArg_ParseTuple(args, "sss:call", &arg1, &arg2, &arg3)) { return NULL; } result = PyUnicode_FromFormat( "Returning -- value: [%d] arg1: [%s] arg2: [%s] arg3: [%s]\n", obj->obj_UnderlyingDatatypePtr->size, arg1, arg2, arg3); return result; } ``` ``` /* Iterators */ getiterfunc tp_iter; iternextfunc tp_iternext; ``` These functions provide support for the iterator protocol. Both handlers take exactly one parameter, the instance for which they are being called, and return a new reference. In the case of an error, they should set an exception and return `NULL`. [`tp_iter`](../c-api/typeobj#c.PyTypeObject.tp_iter "PyTypeObject.tp_iter") corresponds to the Python [`__iter__()`](../reference/datamodel#object.__iter__ "object.__iter__") method, while [`tp_iternext`](../c-api/typeobj#c.PyTypeObject.tp_iternext "PyTypeObject.tp_iternext") corresponds to the Python [`__next__()`](../library/stdtypes#iterator.__next__ "iterator.__next__") method. Any [iterable](../glossary#term-iterable) object must implement the [`tp_iter`](../c-api/typeobj#c.PyTypeObject.tp_iter "PyTypeObject.tp_iter") handler, which must return an [iterator](../glossary#term-iterator) object. Here the same guidelines apply as for Python classes: * For collections (such as lists and tuples) which can support multiple independent iterators, a new iterator should be created and returned by each call to [`tp_iter`](../c-api/typeobj#c.PyTypeObject.tp_iter "PyTypeObject.tp_iter"). * Objects which can only be iterated over once (usually due to side effects of iteration, such as file objects) can implement [`tp_iter`](../c-api/typeobj#c.PyTypeObject.tp_iter "PyTypeObject.tp_iter") by returning a new reference to themselves – and should also therefore implement the [`tp_iternext`](../c-api/typeobj#c.PyTypeObject.tp_iternext "PyTypeObject.tp_iternext") handler. Any [iterator](../glossary#term-iterator) object should implement both [`tp_iter`](../c-api/typeobj#c.PyTypeObject.tp_iter "PyTypeObject.tp_iter") and [`tp_iternext`](../c-api/typeobj#c.PyTypeObject.tp_iternext "PyTypeObject.tp_iternext"). An iterator’s [`tp_iter`](../c-api/typeobj#c.PyTypeObject.tp_iter "PyTypeObject.tp_iter") handler should return a new reference to the iterator. Its [`tp_iternext`](../c-api/typeobj#c.PyTypeObject.tp_iternext "PyTypeObject.tp_iternext") handler should return a new reference to the next object in the iteration, if there is one. If the iteration has reached the end, [`tp_iternext`](../c-api/typeobj#c.PyTypeObject.tp_iternext "PyTypeObject.tp_iternext") may return `NULL` without setting an exception, or it may set [`StopIteration`](../library/exceptions#StopIteration "StopIteration") *in addition* to returning `NULL`; avoiding the exception can yield slightly better performance. If an actual error occurs, [`tp_iternext`](../c-api/typeobj#c.PyTypeObject.tp_iternext "PyTypeObject.tp_iternext") should always set an exception and return `NULL`. 3.6. Weak Reference Support ---------------------------- One of the goals of Python’s weak reference implementation is to allow any type to participate in the weak reference mechanism without incurring the overhead on performance-critical objects (such as numbers). See also Documentation for the [`weakref`](../library/weakref#module-weakref "weakref: Support for weak references and weak dictionaries.") module. For an object to be weakly referencable, the extension type must do two things: 1. Include a [`PyObject*`](../c-api/structures#c.PyObject "PyObject") field in the C object structure dedicated to the weak reference mechanism. The object’s constructor should leave it `NULL` (which is automatic when using the default [`tp_alloc`](../c-api/typeobj#c.PyTypeObject.tp_alloc "PyTypeObject.tp_alloc")). 2. Set the [`tp_weaklistoffset`](../c-api/typeobj#c.PyTypeObject.tp_weaklistoffset "PyTypeObject.tp_weaklistoffset") type member to the offset of the aforementioned field in the C object structure, so that the interpreter knows how to access and modify that field. Concretely, here is how a trivial object structure would be augmented with the required field: ``` typedef struct { PyObject_HEAD PyObject *weakreflist; /* List of weak references */ } TrivialObject; ``` And the corresponding member in the statically-declared type object: ``` static PyTypeObject TrivialType = { PyVarObject_HEAD_INIT(NULL, 0) /* ... other members omitted for brevity ... */ .tp_weaklistoffset = offsetof(TrivialObject, weakreflist), }; ``` The only further addition is that `tp_dealloc` needs to clear any weak references (by calling `PyObject_ClearWeakRefs()`) if the field is non-`NULL`: ``` static void Trivial_dealloc(TrivialObject *self) { /* Clear weakrefs first before calling any destructors */ if (self->weakreflist != NULL) PyObject_ClearWeakRefs((PyObject *) self); /* ... remainder of destruction code omitted for brevity ... */ Py_TYPE(self)->tp_free((PyObject *) self); } ``` 3.7. More Suggestions ---------------------- In order to learn how to implement any specific method for your new data type, get the [CPython](../glossary#term-cpython) source code. Go to the `Objects` directory, then search the C source files for `tp_` plus the function you want (for example, `tp_richcompare`). You will find examples of the function you want to implement. When you need to verify that an object is a concrete instance of the type you are implementing, use the [`PyObject_TypeCheck()`](../c-api/object#c.PyObject_TypeCheck "PyObject_TypeCheck") function. A sample of its use might be something like the following: ``` if (!PyObject_TypeCheck(some_object, &MyType)) { PyErr_SetString(PyExc_TypeError, "arg #1 not a mything"); return NULL; } ``` See also Download CPython source releases. <https://www.python.org/downloads/source/> The CPython project on GitHub, where the CPython source code is developed. <https://github.com/python/cpython>
programming_docs
python Building C and C++ Extensions on Windows Building C and C++ Extensions on Windows ========================================= This chapter briefly explains how to create a Windows extension module for Python using Microsoft Visual C++, and follows with more detailed background information on how it works. The explanatory material is useful for both the Windows programmer learning to build Python extensions and the Unix programmer interested in producing software which can be successfully built on both Unix and Windows. Module authors are encouraged to use the distutils approach for building extension modules, instead of the one described in this section. You will still need the C compiler that was used to build Python; typically Microsoft Visual C++. Note This chapter mentions a number of filenames that include an encoded Python version number. These filenames are represented with the version number shown as `XY`; in practice, `'X'` will be the major version number and `'Y'` will be the minor version number of the Python release you’re working with. For example, if you are using Python 2.2.1, `XY` will actually be `22`. 5.1. A Cookbook Approach ------------------------- There are two approaches to building extension modules on Windows, just as there are on Unix: use the [`distutils`](../library/distutils#module-distutils "distutils: Support for building and installing Python modules into an existing Python installation.") package to control the build process, or do things manually. The distutils approach works well for most extensions; documentation on using [`distutils`](../library/distutils#module-distutils "distutils: Support for building and installing Python modules into an existing Python installation.") to build and package extension modules is available in [Distributing Python Modules (Legacy version)](../distutils/index#distutils-index). If you find you really need to do things manually, it may be instructive to study the project file for the [winsound](https://github.com/python/cpython/tree/3.9/PCbuild/winsound.vcxproj) standard library module. 5.2. Differences Between Unix and Windows ------------------------------------------ Unix and Windows use completely different paradigms for run-time loading of code. Before you try to build a module that can be dynamically loaded, be aware of how your system works. In Unix, a shared object (`.so`) file contains code to be used by the program, and also the names of functions and data that it expects to find in the program. When the file is joined to the program, all references to those functions and data in the file’s code are changed to point to the actual locations in the program where the functions and data are placed in memory. This is basically a link operation. In Windows, a dynamic-link library (`.dll`) file has no dangling references. Instead, an access to functions or data goes through a lookup table. So the DLL code does not have to be fixed up at runtime to refer to the program’s memory; instead, the code already uses the DLL’s lookup table, and the lookup table is modified at runtime to point to the functions and data. In Unix, there is only one type of library file (`.a`) which contains code from several object files (`.o`). During the link step to create a shared object file (`.so`), the linker may find that it doesn’t know where an identifier is defined. The linker will look for it in the object files in the libraries; if it finds it, it will include all the code from that object file. In Windows, there are two types of library, a static library and an import library (both called `.lib`). A static library is like a Unix `.a` file; it contains code to be included as necessary. An import library is basically used only to reassure the linker that a certain identifier is legal, and will be present in the program when the DLL is loaded. So the linker uses the information from the import library to build the lookup table for using identifiers that are not included in the DLL. When an application or a DLL is linked, an import library may be generated, which will need to be used for all future DLLs that depend on the symbols in the application or DLL. Suppose you are building two dynamic-load modules, B and C, which should share another block of code A. On Unix, you would *not* pass `A.a` to the linker for `B.so` and `C.so`; that would cause it to be included twice, so that B and C would each have their own copy. In Windows, building `A.dll` will also build `A.lib`. You *do* pass `A.lib` to the linker for B and C. `A.lib` does not contain code; it just contains information which will be used at runtime to access A’s code. In Windows, using an import library is sort of like using `import spam`; it gives you access to spam’s names, but does not create a separate copy. On Unix, linking with a library is more like `from spam import *`; it does create a separate copy. 5.3. Using DLLs in Practice ---------------------------- Windows Python is built in Microsoft Visual C++; using other compilers may or may not work. The rest of this section is MSVC++ specific. When creating DLLs in Windows, you must pass `pythonXY.lib` to the linker. To build two DLLs, spam and ni (which uses C functions found in spam), you could use these commands: ``` cl /LD /I/python/include spam.c ../libs/pythonXY.lib cl /LD /I/python/include ni.c spam.lib ../libs/pythonXY.lib ``` The first command created three files: `spam.obj`, `spam.dll` and `spam.lib`. `Spam.dll` does not contain any Python functions (such as [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple")), but it does know how to find the Python code thanks to `pythonXY.lib`. The second command created `ni.dll` (and `.obj` and `.lib`), which knows how to find the necessary functions from spam, and also from the Python executable. Not every identifier is exported to the lookup table. If you want any other modules (including Python) to be able to see your identifiers, you have to say `_declspec(dllexport)`, as in `void _declspec(dllexport) initspam(void)` or `PyObject _declspec(dllexport) *NiGetSpamData(void)`. Developer Studio will throw in a lot of import libraries that you do not really need, adding about 100K to your executable. To get rid of them, use the Project Settings dialog, Link tab, to specify *ignore default libraries*. Add the correct `msvcrtxx.lib` to the list of libraries. python Extending Python with C or C++ Extending Python with C or C++ =============================== It is quite easy to add new built-in modules to Python, if you know how to program in C. Such *extension modules* can do two things that can’t be done directly in Python: they can implement new built-in object types, and they can call C library functions and system calls. To support extensions, the Python API (Application Programmers Interface) defines a set of functions, macros and variables that provide access to most aspects of the Python run-time system. The Python API is incorporated in a C source file by including the header `"Python.h"`. The compilation of an extension module depends on its intended use as well as on your system setup; details are given in later chapters. Note The C extension interface is specific to CPython, and extension modules do not work on other Python implementations. In many cases, it is possible to avoid writing C extensions and preserve portability to other implementations. For example, if your use case is calling C library functions or system calls, you should consider using the [`ctypes`](../library/ctypes#module-ctypes "ctypes: A foreign function library for Python.") module or the [cffi](https://cffi.readthedocs.io/) library rather than writing custom C code. These modules let you write Python code to interface with C code and are more portable between implementations of Python than writing and compiling a C extension module. 1.1. A Simple Example ---------------------- Let’s create an extension module called `spam` (the favorite food of Monty Python fans…) and let’s say we want to create a Python interface to the C library function `system()` [1](#id5). This function takes a null-terminated character string as argument and returns an integer. We want this function to be callable from Python as follows: ``` >>> import spam >>> status = spam.system("ls -l") ``` Begin by creating a file `spammodule.c`. (Historically, if a module is called `spam`, the C file containing its implementation is called `spammodule.c`; if the module name is very long, like `spammify`, the module name can be just `spammify.c`.) The first two lines of our file can be: ``` #define PY_SSIZE_T_CLEAN #include <Python.h> ``` which pulls in the Python API (you can add a comment describing the purpose of the module and a copyright notice if you like). Note Since Python may define some pre-processor definitions which affect the standard headers on some systems, you *must* include `Python.h` before any standard headers are included. It is recommended to always define `PY_SSIZE_T_CLEAN` before including `Python.h`. See [Extracting Parameters in Extension Functions](#parsetuple) for a description of this macro. All user-visible symbols defined by `Python.h` have a prefix of `Py` or `PY`, except those defined in standard header files. For convenience, and since they are used extensively by the Python interpreter, `"Python.h"` includes a few standard header files: `<stdio.h>`, `<string.h>`, `<errno.h>`, and `<stdlib.h>`. If the latter header file does not exist on your system, it declares the functions `malloc()`, `free()` and `realloc()` directly. The next thing we add to our module file is the C function that will be called when the Python expression `spam.system(string)` is evaluated (we’ll see shortly how it ends up being called): ``` static PyObject * spam_system(PyObject *self, PyObject *args) { const char *command; int sts; if (!PyArg_ParseTuple(args, "s", &command)) return NULL; sts = system(command); return PyLong_FromLong(sts); } ``` There is a straightforward translation from the argument list in Python (for example, the single expression `"ls -l"`) to the arguments passed to the C function. The C function always has two arguments, conventionally named *self* and *args*. The *self* argument points to the module object for module-level functions; for a method it would point to the object instance. The *args* argument will be a pointer to a Python tuple object containing the arguments. Each item of the tuple corresponds to an argument in the call’s argument list. The arguments are Python objects — in order to do anything with them in our C function we have to convert them to C values. The function [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple") in the Python API checks the argument types and converts them to C values. It uses a template string to determine the required types of the arguments as well as the types of the C variables into which to store the converted values. More about this later. [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple") returns true (nonzero) if all arguments have the right type and its components have been stored in the variables whose addresses are passed. It returns false (zero) if an invalid argument list was passed. In the latter case it also raises an appropriate exception so the calling function can return `NULL` immediately (as we saw in the example). 1.2. Intermezzo: Errors and Exceptions --------------------------------------- An important convention throughout the Python interpreter is the following: when a function fails, it should set an exception condition and return an error value (usually `-1` or a `NULL` pointer). Exception information is stored in three members of the interpreter’s thread state. These are `NULL` if there is no exception. Otherwise they are the C equivalents of the members of the Python tuple returned by [`sys.exc_info()`](../library/sys#sys.exc_info "sys.exc_info"). These are the exception type, exception instance, and a traceback object. It is important to know about them to understand how errors are passed around. The Python API defines a number of functions to set various types of exceptions. The most common one is [`PyErr_SetString()`](../c-api/exceptions#c.PyErr_SetString "PyErr_SetString"). Its arguments are an exception object and a C string. The exception object is usually a predefined object like `PyExc_ZeroDivisionError`. The C string indicates the cause of the error and is converted to a Python string object and stored as the “associated value” of the exception. Another useful function is [`PyErr_SetFromErrno()`](../c-api/exceptions#c.PyErr_SetFromErrno "PyErr_SetFromErrno"), which only takes an exception argument and constructs the associated value by inspection of the global variable `errno`. The most general function is [`PyErr_SetObject()`](../c-api/exceptions#c.PyErr_SetObject "PyErr_SetObject"), which takes two object arguments, the exception and its associated value. You don’t need to [`Py_INCREF()`](../c-api/refcounting#c.Py_INCREF "Py_INCREF") the objects passed to any of these functions. You can test non-destructively whether an exception has been set with [`PyErr_Occurred()`](../c-api/exceptions#c.PyErr_Occurred "PyErr_Occurred"). This returns the current exception object, or `NULL` if no exception has occurred. You normally don’t need to call [`PyErr_Occurred()`](../c-api/exceptions#c.PyErr_Occurred "PyErr_Occurred") to see whether an error occurred in a function call, since you should be able to tell from the return value. When a function *f* that calls another function *g* detects that the latter fails, *f* should itself return an error value (usually `NULL` or `-1`). It should *not* call one of the `PyErr_*()` functions — one has already been called by *g*. *f*’s caller is then supposed to also return an error indication to *its* caller, again *without* calling `PyErr_*()`, and so on — the most detailed cause of the error was already reported by the function that first detected it. Once the error reaches the Python interpreter’s main loop, this aborts the currently executing Python code and tries to find an exception handler specified by the Python programmer. (There are situations where a module can actually give a more detailed error message by calling another `PyErr_*()` function, and in such cases it is fine to do so. As a general rule, however, this is not necessary, and can cause information about the cause of the error to be lost: most operations can fail for a variety of reasons.) To ignore an exception set by a function call that failed, the exception condition must be cleared explicitly by calling [`PyErr_Clear()`](../c-api/exceptions#c.PyErr_Clear "PyErr_Clear"). The only time C code should call [`PyErr_Clear()`](../c-api/exceptions#c.PyErr_Clear "PyErr_Clear") is if it doesn’t want to pass the error on to the interpreter but wants to handle it completely by itself (possibly by trying something else, or pretending nothing went wrong). Every failing `malloc()` call must be turned into an exception — the direct caller of `malloc()` (or `realloc()`) must call [`PyErr_NoMemory()`](../c-api/exceptions#c.PyErr_NoMemory "PyErr_NoMemory") and return a failure indicator itself. All the object-creating functions (for example, [`PyLong_FromLong()`](../c-api/long#c.PyLong_FromLong "PyLong_FromLong")) already do this, so this note is only relevant to those who call `malloc()` directly. Also note that, with the important exception of [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple") and friends, functions that return an integer status usually return a positive value or zero for success and `-1` for failure, like Unix system calls. Finally, be careful to clean up garbage (by making [`Py_XDECREF()`](../c-api/refcounting#c.Py_XDECREF "Py_XDECREF") or [`Py_DECREF()`](../c-api/refcounting#c.Py_DECREF "Py_DECREF") calls for objects you have already created) when you return an error indicator! The choice of which exception to raise is entirely yours. There are predeclared C objects corresponding to all built-in Python exceptions, such as `PyExc_ZeroDivisionError`, which you can use directly. Of course, you should choose exceptions wisely — don’t use `PyExc_TypeError` to mean that a file couldn’t be opened (that should probably be `PyExc_IOError`). If something’s wrong with the argument list, the [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple") function usually raises `PyExc_TypeError`. If you have an argument whose value must be in a particular range or must satisfy other conditions, `PyExc_ValueError` is appropriate. You can also define a new exception that is unique to your module. For this, you usually declare a static object variable at the beginning of your file: ``` static PyObject *SpamError; ``` and initialize it in your module’s initialization function (`PyInit_spam()`) with an exception object: ``` PyMODINIT_FUNC PyInit_spam(void) { PyObject *m; m = PyModule_Create(&spammodule); if (m == NULL) return NULL; SpamError = PyErr_NewException("spam.error", NULL, NULL); Py_XINCREF(SpamError); if (PyModule_AddObject(m, "error", SpamError) < 0) { Py_XDECREF(SpamError); Py_CLEAR(SpamError); Py_DECREF(m); return NULL; } return m; } ``` Note that the Python name for the exception object is `spam.error`. The [`PyErr_NewException()`](../c-api/exceptions#c.PyErr_NewException "PyErr_NewException") function may create a class with the base class being [`Exception`](../library/exceptions#Exception "Exception") (unless another class is passed in instead of `NULL`), described in [Built-in Exceptions](../library/exceptions#bltin-exceptions). Note also that the `SpamError` variable retains a reference to the newly created exception class; this is intentional! Since the exception could be removed from the module by external code, an owned reference to the class is needed to ensure that it will not be discarded, causing `SpamError` to become a dangling pointer. Should it become a dangling pointer, C code which raises the exception could cause a core dump or other unintended side effects. We discuss the use of `PyMODINIT_FUNC` as a function return type later in this sample. The `spam.error` exception can be raised in your extension module using a call to [`PyErr_SetString()`](../c-api/exceptions#c.PyErr_SetString "PyErr_SetString") as shown below: ``` static PyObject * spam_system(PyObject *self, PyObject *args) { const char *command; int sts; if (!PyArg_ParseTuple(args, "s", &command)) return NULL; sts = system(command); if (sts < 0) { PyErr_SetString(SpamError, "System command failed"); return NULL; } return PyLong_FromLong(sts); } ``` 1.3. Back to the Example ------------------------- Going back to our example function, you should now be able to understand this statement: ``` if (!PyArg_ParseTuple(args, "s", &command)) return NULL; ``` It returns `NULL` (the error indicator for functions returning object pointers) if an error is detected in the argument list, relying on the exception set by [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple"). Otherwise the string value of the argument has been copied to the local variable `command`. This is a pointer assignment and you are not supposed to modify the string to which it points (so in Standard C, the variable `command` should properly be declared as `const char *command`). The next statement is a call to the Unix function `system()`, passing it the string we just got from [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple"): ``` sts = system(command); ``` Our `spam.system()` function must return the value of `sts` as a Python object. This is done using the function [`PyLong_FromLong()`](../c-api/long#c.PyLong_FromLong "PyLong_FromLong"). ``` return PyLong_FromLong(sts); ``` In this case, it will return an integer object. (Yes, even integers are objects on the heap in Python!) If you have a C function that returns no useful argument (a function returning `void`), the corresponding Python function must return `None`. You need this idiom to do so (which is implemented by the [`Py_RETURN_NONE`](../c-api/none#c.Py_RETURN_NONE "Py_RETURN_NONE") macro): ``` Py_INCREF(Py_None); return Py_None; ``` [`Py_None`](../c-api/none#c.Py_None "Py_None") is the C name for the special Python object `None`. It is a genuine Python object rather than a `NULL` pointer, which means “error” in most contexts, as we have seen. 1.4. The Module’s Method Table and Initialization Function ----------------------------------------------------------- I promised to show how `spam_system()` is called from Python programs. First, we need to list its name and address in a “method table”: ``` static PyMethodDef SpamMethods[] = { ... {"system", spam_system, METH_VARARGS, "Execute a shell command."}, ... {NULL, NULL, 0, NULL} /* Sentinel */ }; ``` Note the third entry (`METH_VARARGS`). This is a flag telling the interpreter the calling convention to be used for the C function. It should normally always be `METH_VARARGS` or `METH_VARARGS | METH_KEYWORDS`; a value of `0` means that an obsolete variant of [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple") is used. When using only `METH_VARARGS`, the function should expect the Python-level parameters to be passed in as a tuple acceptable for parsing via [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple"); more information on this function is provided below. The `METH_KEYWORDS` bit may be set in the third field if keyword arguments should be passed to the function. In this case, the C function should accept a third `PyObject *` parameter which will be a dictionary of keywords. Use [`PyArg_ParseTupleAndKeywords()`](../c-api/arg#c.PyArg_ParseTupleAndKeywords "PyArg_ParseTupleAndKeywords") to parse the arguments to such a function. The method table must be referenced in the module definition structure: ``` static struct PyModuleDef spammodule = { PyModuleDef_HEAD_INIT, "spam", /* name of module */ spam_doc, /* module documentation, may be NULL */ -1, /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */ SpamMethods }; ``` This structure, in turn, must be passed to the interpreter in the module’s initialization function. The initialization function must be named `PyInit_name()`, where *name* is the name of the module, and should be the only non-`static` item defined in the module file: ``` PyMODINIT_FUNC PyInit_spam(void) { return PyModule_Create(&spammodule); } ``` Note that PyMODINIT\_FUNC declares the function as `PyObject *` return type, declares any special linkage declarations required by the platform, and for C++ declares the function as `extern "C"`. When the Python program imports module `spam` for the first time, `PyInit_spam()` is called. (See below for comments about embedding Python.) It calls [`PyModule_Create()`](../c-api/module#c.PyModule_Create "PyModule_Create"), which returns a module object, and inserts built-in function objects into the newly created module based upon the table (an array of [`PyMethodDef`](../c-api/structures#c.PyMethodDef "PyMethodDef") structures) found in the module definition. [`PyModule_Create()`](../c-api/module#c.PyModule_Create "PyModule_Create") returns a pointer to the module object that it creates. It may abort with a fatal error for certain errors, or return `NULL` if the module could not be initialized satisfactorily. The init function must return the module object to its caller, so that it then gets inserted into `sys.modules`. When embedding Python, the `PyInit_spam()` function is not called automatically unless there’s an entry in the `PyImport_Inittab` table. To add the module to the initialization table, use [`PyImport_AppendInittab()`](../c-api/import#c.PyImport_AppendInittab "PyImport_AppendInittab"), optionally followed by an import of the module: ``` int main(int argc, char *argv[]) { wchar_t *program = Py_DecodeLocale(argv[0], NULL); if (program == NULL) { fprintf(stderr, "Fatal error: cannot decode argv[0]\n"); exit(1); } /* Add a built-in module, before Py_Initialize */ if (PyImport_AppendInittab("spam", PyInit_spam) == -1) { fprintf(stderr, "Error: could not extend in-built modules table\n"); exit(1); } /* Pass argv[0] to the Python interpreter */ Py_SetProgramName(program); /* Initialize the Python interpreter. Required. If this step fails, it will be a fatal error. */ Py_Initialize(); /* Optionally import the module; alternatively, import can be deferred until the embedded script imports it. */ PyObject *pmodule = PyImport_ImportModule("spam"); if (!pmodule) { PyErr_Print(); fprintf(stderr, "Error: could not import module 'spam'\n"); } ... PyMem_RawFree(program); return 0; } ``` Note Removing entries from `sys.modules` or importing compiled modules into multiple interpreters within a process (or following a `fork()` without an intervening `exec()`) can create problems for some extension modules. Extension module authors should exercise caution when initializing internal data structures. A more substantial example module is included in the Python source distribution as `Modules/xxmodule.c`. This file may be used as a template or simply read as an example. Note Unlike our `spam` example, `xxmodule` uses *multi-phase initialization* (new in Python 3.5), where a PyModuleDef structure is returned from `PyInit_spam`, and creation of the module is left to the import machinery. For details on multi-phase initialization, see [**PEP 489**](https://www.python.org/dev/peps/pep-0489). 1.5. Compilation and Linkage ----------------------------- There are two more things to do before you can use your new extension: compiling and linking it with the Python system. If you use dynamic loading, the details may depend on the style of dynamic loading your system uses; see the chapters about building extension modules (chapter [Building C and C++ Extensions](building#building)) and additional information that pertains only to building on Windows (chapter [Building C and C++ Extensions on Windows](windows#building-on-windows)) for more information about this. If you can’t use dynamic loading, or if you want to make your module a permanent part of the Python interpreter, you will have to change the configuration setup and rebuild the interpreter. Luckily, this is very simple on Unix: just place your file (`spammodule.c` for example) in the `Modules/` directory of an unpacked source distribution, add a line to the file `Modules/Setup.local` describing your file: ``` spam spammodule.o ``` and rebuild the interpreter by running **make** in the toplevel directory. You can also run **make** in the `Modules/` subdirectory, but then you must first rebuild `Makefile` there by running ‘**make** Makefile’. (This is necessary each time you change the `Setup` file.) If your module requires additional libraries to link with, these can be listed on the line in the configuration file as well, for instance: ``` spam spammodule.o -lX11 ``` 1.6. Calling Python Functions from C ------------------------------------- So far we have concentrated on making C functions callable from Python. The reverse is also useful: calling Python functions from C. This is especially the case for libraries that support so-called “callback” functions. If a C interface makes use of callbacks, the equivalent Python often needs to provide a callback mechanism to the Python programmer; the implementation will require calling the Python callback functions from a C callback. Other uses are also imaginable. Fortunately, the Python interpreter is easily called recursively, and there is a standard interface to call a Python function. (I won’t dwell on how to call the Python parser with a particular string as input — if you’re interested, have a look at the implementation of the [`-c`](../using/cmdline#cmdoption-c) command line option in `Modules/main.c` from the Python source code.) Calling a Python function is easy. First, the Python program must somehow pass you the Python function object. You should provide a function (or some other interface) to do this. When this function is called, save a pointer to the Python function object (be careful to [`Py_INCREF()`](../c-api/refcounting#c.Py_INCREF "Py_INCREF") it!) in a global variable — or wherever you see fit. For example, the following function might be part of a module definition: ``` static PyObject *my_callback = NULL; static PyObject * my_set_callback(PyObject *dummy, PyObject *args) { PyObject *result = NULL; PyObject *temp; if (PyArg_ParseTuple(args, "O:set_callback", &temp)) { if (!PyCallable_Check(temp)) { PyErr_SetString(PyExc_TypeError, "parameter must be callable"); return NULL; } Py_XINCREF(temp); /* Add a reference to new callback */ Py_XDECREF(my_callback); /* Dispose of previous callback */ my_callback = temp; /* Remember new callback */ /* Boilerplate to return "None" */ Py_INCREF(Py_None); result = Py_None; } return result; } ``` This function must be registered with the interpreter using the [`METH_VARARGS`](../c-api/structures#METH_VARARGS "METH_VARARGS") flag; this is described in section [The Module’s Method Table and Initialization Function](#methodtable). The [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple") function and its arguments are documented in section [Extracting Parameters in Extension Functions](#parsetuple). The macros [`Py_XINCREF()`](../c-api/refcounting#c.Py_XINCREF "Py_XINCREF") and [`Py_XDECREF()`](../c-api/refcounting#c.Py_XDECREF "Py_XDECREF") increment/decrement the reference count of an object and are safe in the presence of `NULL` pointers (but note that *temp* will not be `NULL` in this context). More info on them in section [Reference Counts](#refcounts). Later, when it is time to call the function, you call the C function [`PyObject_CallObject()`](../c-api/call#c.PyObject_CallObject "PyObject_CallObject"). This function has two arguments, both pointers to arbitrary Python objects: the Python function, and the argument list. The argument list must always be a tuple object, whose length is the number of arguments. To call the Python function with no arguments, pass in `NULL`, or an empty tuple; to call it with one argument, pass a singleton tuple. [`Py_BuildValue()`](../c-api/arg#c.Py_BuildValue "Py_BuildValue") returns a tuple when its format string consists of zero or more format codes between parentheses. For example: ``` int arg; PyObject *arglist; PyObject *result; ... arg = 123; ... /* Time to call the callback */ arglist = Py_BuildValue("(i)", arg); result = PyObject_CallObject(my_callback, arglist); Py_DECREF(arglist); ``` [`PyObject_CallObject()`](../c-api/call#c.PyObject_CallObject "PyObject_CallObject") returns a Python object pointer: this is the return value of the Python function. [`PyObject_CallObject()`](../c-api/call#c.PyObject_CallObject "PyObject_CallObject") is “reference-count-neutral” with respect to its arguments. In the example a new tuple was created to serve as the argument list, which is [`Py_DECREF()`](../c-api/refcounting#c.Py_DECREF "Py_DECREF")-ed immediately after the [`PyObject_CallObject()`](../c-api/call#c.PyObject_CallObject "PyObject_CallObject") call. The return value of [`PyObject_CallObject()`](../c-api/call#c.PyObject_CallObject "PyObject_CallObject") is “new”: either it is a brand new object, or it is an existing object whose reference count has been incremented. So, unless you want to save it in a global variable, you should somehow [`Py_DECREF()`](../c-api/refcounting#c.Py_DECREF "Py_DECREF") the result, even (especially!) if you are not interested in its value. Before you do this, however, it is important to check that the return value isn’t `NULL`. If it is, the Python function terminated by raising an exception. If the C code that called [`PyObject_CallObject()`](../c-api/call#c.PyObject_CallObject "PyObject_CallObject") is called from Python, it should now return an error indication to its Python caller, so the interpreter can print a stack trace, or the calling Python code can handle the exception. If this is not possible or desirable, the exception should be cleared by calling [`PyErr_Clear()`](../c-api/exceptions#c.PyErr_Clear "PyErr_Clear"). For example: ``` if (result == NULL) return NULL; /* Pass error back */ ...use result... Py_DECREF(result); ``` Depending on the desired interface to the Python callback function, you may also have to provide an argument list to [`PyObject_CallObject()`](../c-api/call#c.PyObject_CallObject "PyObject_CallObject"). In some cases the argument list is also provided by the Python program, through the same interface that specified the callback function. It can then be saved and used in the same manner as the function object. In other cases, you may have to construct a new tuple to pass as the argument list. The simplest way to do this is to call [`Py_BuildValue()`](../c-api/arg#c.Py_BuildValue "Py_BuildValue"). For example, if you want to pass an integral event code, you might use the following code: ``` PyObject *arglist; ... arglist = Py_BuildValue("(l)", eventcode); result = PyObject_CallObject(my_callback, arglist); Py_DECREF(arglist); if (result == NULL) return NULL; /* Pass error back */ /* Here maybe use the result */ Py_DECREF(result); ``` Note the placement of `Py_DECREF(arglist)` immediately after the call, before the error check! Also note that strictly speaking this code is not complete: [`Py_BuildValue()`](../c-api/arg#c.Py_BuildValue "Py_BuildValue") may run out of memory, and this should be checked. You may also call a function with keyword arguments by using [`PyObject_Call()`](../c-api/call#c.PyObject_Call "PyObject_Call"), which supports arguments and keyword arguments. As in the above example, we use [`Py_BuildValue()`](../c-api/arg#c.Py_BuildValue "Py_BuildValue") to construct the dictionary. ``` PyObject *dict; ... dict = Py_BuildValue("{s:i}", "name", val); result = PyObject_Call(my_callback, NULL, dict); Py_DECREF(dict); if (result == NULL) return NULL; /* Pass error back */ /* Here maybe use the result */ Py_DECREF(result); ``` 1.7. Extracting Parameters in Extension Functions -------------------------------------------------- The [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple") function is declared as follows: ``` int PyArg_ParseTuple(PyObject *arg, const char *format, ...); ``` The *arg* argument must be a tuple object containing an argument list passed from Python to a C function. The *format* argument must be a format string, whose syntax is explained in [Parsing arguments and building values](../c-api/arg#arg-parsing) in the Python/C API Reference Manual. The remaining arguments must be addresses of variables whose type is determined by the format string. Note that while [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple") checks that the Python arguments have the required types, it cannot check the validity of the addresses of C variables passed to the call: if you make mistakes there, your code will probably crash or at least overwrite random bits in memory. So be careful! Note that any Python object references which are provided to the caller are *borrowed* references; do not decrement their reference count! Some example calls: ``` #define PY_SSIZE_T_CLEAN /* Make "s#" use Py_ssize_t rather than int. */ #include <Python.h> ``` ``` int ok; int i, j; long k, l; const char *s; Py_ssize_t size; ok = PyArg_ParseTuple(args, ""); /* No arguments */ /* Python call: f() */ ``` ``` ok = PyArg_ParseTuple(args, "s", &s); /* A string */ /* Possible Python call: f('whoops!') */ ``` ``` ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); /* Two longs and a string */ /* Possible Python call: f(1, 2, 'three') */ ``` ``` ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size); /* A pair of ints and a string, whose size is also returned */ /* Possible Python call: f((1, 2), 'three') */ ``` ``` { const char *file; const char *mode = "r"; int bufsize = 0; ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize); /* A string, and optionally another string and an integer */ /* Possible Python calls: f('spam') f('spam', 'w') f('spam', 'wb', 100000) */ } ``` ``` { int left, top, right, bottom, h, v; ok = PyArg_ParseTuple(args, "((ii)(ii))(ii)", &left, &top, &right, &bottom, &h, &v); /* A rectangle and a point */ /* Possible Python call: f(((0, 0), (400, 300)), (10, 10)) */ } ``` ``` { Py_complex c; ok = PyArg_ParseTuple(args, "D:myfunction", &c); /* a complex, also providing a function name for errors */ /* Possible Python call: myfunction(1+2j) */ } ``` 1.8. Keyword Parameters for Extension Functions ------------------------------------------------ The [`PyArg_ParseTupleAndKeywords()`](../c-api/arg#c.PyArg_ParseTupleAndKeywords "PyArg_ParseTupleAndKeywords") function is declared as follows: ``` int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict, const char *format, char *kwlist[], ...); ``` The *arg* and *format* parameters are identical to those of the [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple") function. The *kwdict* parameter is the dictionary of keywords received as the third parameter from the Python runtime. The *kwlist* parameter is a `NULL`-terminated list of strings which identify the parameters; the names are matched with the type information from *format* from left to right. On success, [`PyArg_ParseTupleAndKeywords()`](../c-api/arg#c.PyArg_ParseTupleAndKeywords "PyArg_ParseTupleAndKeywords") returns true, otherwise it returns false and raises an appropriate exception. Note Nested tuples cannot be parsed when using keyword arguments! Keyword parameters passed in which are not present in the *kwlist* will cause [`TypeError`](../library/exceptions#TypeError "TypeError") to be raised. Here is an example module which uses keywords, based on an example by Geoff Philbrick ([[email protected]](mailto:philbrick%40hks.com)): ``` #define PY_SSIZE_T_CLEAN /* Make "s#" use Py_ssize_t rather than int. */ #include <Python.h> static PyObject * keywdarg_parrot(PyObject *self, PyObject *args, PyObject *keywds) { int voltage; const char *state = "a stiff"; const char *action = "voom"; const char *type = "Norwegian Blue"; static char *kwlist[] = {"voltage", "state", "action", "type", NULL}; if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist, &voltage, &state, &action, &type)) return NULL; printf("-- This parrot wouldn't %s if you put %i Volts through it.\n", action, voltage); printf("-- Lovely plumage, the %s -- It's %s!\n", type, state); Py_RETURN_NONE; } static PyMethodDef keywdarg_methods[] = { /* The cast of the function is necessary since PyCFunction values * only take two PyObject* parameters, and keywdarg_parrot() takes * three. */ {"parrot", (PyCFunction)(void(*)(void))keywdarg_parrot, METH_VARARGS | METH_KEYWORDS, "Print a lovely skit to standard output."}, {NULL, NULL, 0, NULL} /* sentinel */ }; static struct PyModuleDef keywdargmodule = { PyModuleDef_HEAD_INIT, "keywdarg", NULL, -1, keywdarg_methods }; PyMODINIT_FUNC PyInit_keywdarg(void) { return PyModule_Create(&keywdargmodule); } ``` 1.9. Building Arbitrary Values ------------------------------- This function is the counterpart to [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple"). It is declared as follows: ``` PyObject *Py_BuildValue(const char *format, ...); ``` It recognizes a set of format units similar to the ones recognized by [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple"), but the arguments (which are input to the function, not output) must not be pointers, just values. It returns a new Python object, suitable for returning from a C function called from Python. One difference with [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple"): while the latter requires its first argument to be a tuple (since Python argument lists are always represented as tuples internally), [`Py_BuildValue()`](../c-api/arg#c.Py_BuildValue "Py_BuildValue") does not always build a tuple. It builds a tuple only if its format string contains two or more format units. If the format string is empty, it returns `None`; if it contains exactly one format unit, it returns whatever object is described by that format unit. To force it to return a tuple of size 0 or one, parenthesize the format string. Examples (to the left the call, to the right the resulting Python value): ``` Py_BuildValue("") None Py_BuildValue("i", 123) 123 Py_BuildValue("iii", 123, 456, 789) (123, 456, 789) Py_BuildValue("s", "hello") 'hello' Py_BuildValue("y", "hello") b'hello' Py_BuildValue("ss", "hello", "world") ('hello', 'world') Py_BuildValue("s#", "hello", 4) 'hell' Py_BuildValue("y#", "hello", 4) b'hell' Py_BuildValue("()") () Py_BuildValue("(i)", 123) (123,) Py_BuildValue("(ii)", 123, 456) (123, 456) Py_BuildValue("(i,i)", 123, 456) (123, 456) Py_BuildValue("[i,i]", 123, 456) [123, 456] Py_BuildValue("{s:i,s:i}", "abc", 123, "def", 456) {'abc': 123, 'def': 456} Py_BuildValue("((ii)(ii)) (ii)", 1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6)) ``` 1.10. Reference Counts ----------------------- In languages like C or C++, the programmer is responsible for dynamic allocation and deallocation of memory on the heap. In C, this is done using the functions `malloc()` and `free()`. In C++, the operators `new` and `delete` are used with essentially the same meaning and we’ll restrict the following discussion to the C case. Every block of memory allocated with `malloc()` should eventually be returned to the pool of available memory by exactly one call to `free()`. It is important to call `free()` at the right time. If a block’s address is forgotten but `free()` is not called for it, the memory it occupies cannot be reused until the program terminates. This is called a *memory leak*. On the other hand, if a program calls `free()` for a block and then continues to use the block, it creates a conflict with re-use of the block through another `malloc()` call. This is called *using freed memory*. It has the same bad consequences as referencing uninitialized data — core dumps, wrong results, mysterious crashes. Common causes of memory leaks are unusual paths through the code. For instance, a function may allocate a block of memory, do some calculation, and then free the block again. Now a change in the requirements for the function may add a test to the calculation that detects an error condition and can return prematurely from the function. It’s easy to forget to free the allocated memory block when taking this premature exit, especially when it is added later to the code. Such leaks, once introduced, often go undetected for a long time: the error exit is taken only in a small fraction of all calls, and most modern machines have plenty of virtual memory, so the leak only becomes apparent in a long-running process that uses the leaking function frequently. Therefore, it’s important to prevent leaks from happening by having a coding convention or strategy that minimizes this kind of errors. Since Python makes heavy use of `malloc()` and `free()`, it needs a strategy to avoid memory leaks as well as the use of freed memory. The chosen method is called *reference counting*. The principle is simple: every object contains a counter, which is incremented when a reference to the object is stored somewhere, and which is decremented when a reference to it is deleted. When the counter reaches zero, the last reference to the object has been deleted and the object is freed. An alternative strategy is called *automatic garbage collection*. (Sometimes, reference counting is also referred to as a garbage collection strategy, hence my use of “automatic” to distinguish the two.) The big advantage of automatic garbage collection is that the user doesn’t need to call `free()` explicitly. (Another claimed advantage is an improvement in speed or memory usage — this is no hard fact however.) The disadvantage is that for C, there is no truly portable automatic garbage collector, while reference counting can be implemented portably (as long as the functions `malloc()` and `free()` are available — which the C Standard guarantees). Maybe some day a sufficiently portable automatic garbage collector will be available for C. Until then, we’ll have to live with reference counts. While Python uses the traditional reference counting implementation, it also offers a cycle detector that works to detect reference cycles. This allows applications to not worry about creating direct or indirect circular references; these are the weakness of garbage collection implemented using only reference counting. Reference cycles consist of objects which contain (possibly indirect) references to themselves, so that each object in the cycle has a reference count which is non-zero. Typical reference counting implementations are not able to reclaim the memory belonging to any objects in a reference cycle, or referenced from the objects in the cycle, even though there are no further references to the cycle itself. The cycle detector is able to detect garbage cycles and can reclaim them. The [`gc`](../library/gc#module-gc "gc: Interface to the cycle-detecting garbage collector.") module exposes a way to run the detector (the [`collect()`](../library/gc#gc.collect "gc.collect") function), as well as configuration interfaces and the ability to disable the detector at runtime. The cycle detector is considered an optional component; though it is included by default, it can be disabled at build time using the `--without-cycle-gc` option to the **configure** script on Unix platforms (including Mac OS X). If the cycle detector is disabled in this way, the [`gc`](../library/gc#module-gc "gc: Interface to the cycle-detecting garbage collector.") module will not be available. ### 1.10.1. Reference Counting in Python There are two macros, `Py_INCREF(x)` and `Py_DECREF(x)`, which handle the incrementing and decrementing of the reference count. [`Py_DECREF()`](../c-api/refcounting#c.Py_DECREF "Py_DECREF") also frees the object when the count reaches zero. For flexibility, it doesn’t call `free()` directly — rather, it makes a call through a function pointer in the object’s *type object*. For this purpose (and others), every object also contains a pointer to its type object. The big question now remains: when to use `Py_INCREF(x)` and `Py_DECREF(x)`? Let’s first introduce some terms. Nobody “owns” an object; however, you can *own a reference* to an object. An object’s reference count is now defined as the number of owned references to it. The owner of a reference is responsible for calling [`Py_DECREF()`](../c-api/refcounting#c.Py_DECREF "Py_DECREF") when the reference is no longer needed. Ownership of a reference can be transferred. There are three ways to dispose of an owned reference: pass it on, store it, or call [`Py_DECREF()`](../c-api/refcounting#c.Py_DECREF "Py_DECREF"). Forgetting to dispose of an owned reference creates a memory leak. It is also possible to *borrow* [2](#id6) a reference to an object. The borrower of a reference should not call [`Py_DECREF()`](../c-api/refcounting#c.Py_DECREF "Py_DECREF"). The borrower must not hold on to the object longer than the owner from which it was borrowed. Using a borrowed reference after the owner has disposed of it risks using freed memory and should be avoided completely [3](#id7). The advantage of borrowing over owning a reference is that you don’t need to take care of disposing of the reference on all possible paths through the code — in other words, with a borrowed reference you don’t run the risk of leaking when a premature exit is taken. The disadvantage of borrowing over owning is that there are some subtle situations where in seemingly correct code a borrowed reference can be used after the owner from which it was borrowed has in fact disposed of it. A borrowed reference can be changed into an owned reference by calling [`Py_INCREF()`](../c-api/refcounting#c.Py_INCREF "Py_INCREF"). This does not affect the status of the owner from which the reference was borrowed — it creates a new owned reference, and gives full owner responsibilities (the new owner must dispose of the reference properly, as well as the previous owner). ### 1.10.2. Ownership Rules Whenever an object reference is passed into or out of a function, it is part of the function’s interface specification whether ownership is transferred with the reference or not. Most functions that return a reference to an object pass on ownership with the reference. In particular, all functions whose function it is to create a new object, such as [`PyLong_FromLong()`](../c-api/long#c.PyLong_FromLong "PyLong_FromLong") and [`Py_BuildValue()`](../c-api/arg#c.Py_BuildValue "Py_BuildValue"), pass ownership to the receiver. Even if the object is not actually new, you still receive ownership of a new reference to that object. For instance, [`PyLong_FromLong()`](../c-api/long#c.PyLong_FromLong "PyLong_FromLong") maintains a cache of popular values and can return a reference to a cached item. Many functions that extract objects from other objects also transfer ownership with the reference, for instance [`PyObject_GetAttrString()`](../c-api/object#c.PyObject_GetAttrString "PyObject_GetAttrString"). The picture is less clear, here, however, since a few common routines are exceptions: [`PyTuple_GetItem()`](../c-api/tuple#c.PyTuple_GetItem "PyTuple_GetItem"), [`PyList_GetItem()`](../c-api/list#c.PyList_GetItem "PyList_GetItem"), [`PyDict_GetItem()`](../c-api/dict#c.PyDict_GetItem "PyDict_GetItem"), and [`PyDict_GetItemString()`](../c-api/dict#c.PyDict_GetItemString "PyDict_GetItemString") all return references that you borrow from the tuple, list or dictionary. The function [`PyImport_AddModule()`](../c-api/import#c.PyImport_AddModule "PyImport_AddModule") also returns a borrowed reference, even though it may actually create the object it returns: this is possible because an owned reference to the object is stored in `sys.modules`. When you pass an object reference into another function, in general, the function borrows the reference from you — if it needs to store it, it will use [`Py_INCREF()`](../c-api/refcounting#c.Py_INCREF "Py_INCREF") to become an independent owner. There are exactly two important exceptions to this rule: [`PyTuple_SetItem()`](../c-api/tuple#c.PyTuple_SetItem "PyTuple_SetItem") and [`PyList_SetItem()`](../c-api/list#c.PyList_SetItem "PyList_SetItem"). These functions take over ownership of the item passed to them — even if they fail! (Note that [`PyDict_SetItem()`](../c-api/dict#c.PyDict_SetItem "PyDict_SetItem") and friends don’t take over ownership — they are “normal.”) When a C function is called from Python, it borrows references to its arguments from the caller. The caller owns a reference to the object, so the borrowed reference’s lifetime is guaranteed until the function returns. Only when such a borrowed reference must be stored or passed on, it must be turned into an owned reference by calling [`Py_INCREF()`](../c-api/refcounting#c.Py_INCREF "Py_INCREF"). The object reference returned from a C function that is called from Python must be an owned reference — ownership is transferred from the function to its caller. ### 1.10.3. Thin Ice There are a few situations where seemingly harmless use of a borrowed reference can lead to problems. These all have to do with implicit invocations of the interpreter, which can cause the owner of a reference to dispose of it. The first and most important case to know about is using [`Py_DECREF()`](../c-api/refcounting#c.Py_DECREF "Py_DECREF") on an unrelated object while borrowing a reference to a list item. For instance: ``` void bug(PyObject *list) { PyObject *item = PyList_GetItem(list, 0); PyList_SetItem(list, 1, PyLong_FromLong(0L)); PyObject_Print(item, stdout, 0); /* BUG! */ } ``` This function first borrows a reference to `list[0]`, then replaces `list[1]` with the value `0`, and finally prints the borrowed reference. Looks harmless, right? But it’s not! Let’s follow the control flow into [`PyList_SetItem()`](../c-api/list#c.PyList_SetItem "PyList_SetItem"). The list owns references to all its items, so when item 1 is replaced, it has to dispose of the original item 1. Now let’s suppose the original item 1 was an instance of a user-defined class, and let’s further suppose that the class defined a [`__del__()`](../reference/datamodel#object.__del__ "object.__del__") method. If this class instance has a reference count of 1, disposing of it will call its [`__del__()`](../reference/datamodel#object.__del__ "object.__del__") method. Since it is written in Python, the [`__del__()`](../reference/datamodel#object.__del__ "object.__del__") method can execute arbitrary Python code. Could it perhaps do something to invalidate the reference to `item` in `bug()`? You bet! Assuming that the list passed into `bug()` is accessible to the [`__del__()`](../reference/datamodel#object.__del__ "object.__del__") method, it could execute a statement to the effect of `del list[0]`, and assuming this was the last reference to that object, it would free the memory associated with it, thereby invalidating `item`. The solution, once you know the source of the problem, is easy: temporarily increment the reference count. The correct version of the function reads: ``` void no_bug(PyObject *list) { PyObject *item = PyList_GetItem(list, 0); Py_INCREF(item); PyList_SetItem(list, 1, PyLong_FromLong(0L)); PyObject_Print(item, stdout, 0); Py_DECREF(item); } ``` This is a true story. An older version of Python contained variants of this bug and someone spent a considerable amount of time in a C debugger to figure out why his [`__del__()`](../reference/datamodel#object.__del__ "object.__del__") methods would fail… The second case of problems with a borrowed reference is a variant involving threads. Normally, multiple threads in the Python interpreter can’t get in each other’s way, because there is a global lock protecting Python’s entire object space. However, it is possible to temporarily release this lock using the macro [`Py_BEGIN_ALLOW_THREADS`](../c-api/init#c.Py_BEGIN_ALLOW_THREADS "Py_BEGIN_ALLOW_THREADS"), and to re-acquire it using [`Py_END_ALLOW_THREADS`](../c-api/init#c.Py_END_ALLOW_THREADS "Py_END_ALLOW_THREADS"). This is common around blocking I/O calls, to let other threads use the processor while waiting for the I/O to complete. Obviously, the following function has the same problem as the previous one: ``` void bug(PyObject *list) { PyObject *item = PyList_GetItem(list, 0); Py_BEGIN_ALLOW_THREADS ...some blocking I/O call... Py_END_ALLOW_THREADS PyObject_Print(item, stdout, 0); /* BUG! */ } ``` ### 1.10.4. NULL Pointers In general, functions that take object references as arguments do not expect you to pass them `NULL` pointers, and will dump core (or cause later core dumps) if you do so. Functions that return object references generally return `NULL` only to indicate that an exception occurred. The reason for not testing for `NULL` arguments is that functions often pass the objects they receive on to other function — if each function were to test for `NULL`, there would be a lot of redundant tests and the code would run more slowly. It is better to test for `NULL` only at the “source:” when a pointer that may be `NULL` is received, for example, from `malloc()` or from a function that may raise an exception. The macros [`Py_INCREF()`](../c-api/refcounting#c.Py_INCREF "Py_INCREF") and [`Py_DECREF()`](../c-api/refcounting#c.Py_DECREF "Py_DECREF") do not check for `NULL` pointers — however, their variants [`Py_XINCREF()`](../c-api/refcounting#c.Py_XINCREF "Py_XINCREF") and [`Py_XDECREF()`](../c-api/refcounting#c.Py_XDECREF "Py_XDECREF") do. The macros for checking for a particular object type (`Pytype_Check()`) don’t check for `NULL` pointers — again, there is much code that calls several of these in a row to test an object against various different expected types, and this would generate redundant tests. There are no variants with `NULL` checking. The C function calling mechanism guarantees that the argument list passed to C functions (`args` in the examples) is never `NULL` — in fact it guarantees that it is always a tuple [4](#id8). It is a severe error to ever let a `NULL` pointer “escape” to the Python user. 1.11. Writing Extensions in C++ -------------------------------- It is possible to write extension modules in C++. Some restrictions apply. If the main program (the Python interpreter) is compiled and linked by the C compiler, global or static objects with constructors cannot be used. This is not a problem if the main program is linked by the C++ compiler. Functions that will be called by the Python interpreter (in particular, module initialization functions) have to be declared using `extern "C"`. It is unnecessary to enclose the Python header files in `extern "C" {...}` — they use this form already if the symbol `__cplusplus` is defined (all recent C++ compilers define this symbol). 1.12. Providing a C API for an Extension Module ------------------------------------------------ Many extension modules just provide new functions and types to be used from Python, but sometimes the code in an extension module can be useful for other extension modules. For example, an extension module could implement a type “collection” which works like lists without order. Just like the standard Python list type has a C API which permits extension modules to create and manipulate lists, this new collection type should have a set of C functions for direct manipulation from other extension modules. At first sight this seems easy: just write the functions (without declaring them `static`, of course), provide an appropriate header file, and document the C API. And in fact this would work if all extension modules were always linked statically with the Python interpreter. When modules are used as shared libraries, however, the symbols defined in one module may not be visible to another module. The details of visibility depend on the operating system; some systems use one global namespace for the Python interpreter and all extension modules (Windows, for example), whereas others require an explicit list of imported symbols at module link time (AIX is one example), or offer a choice of different strategies (most Unices). And even if symbols are globally visible, the module whose functions one wishes to call might not have been loaded yet! Portability therefore requires not to make any assumptions about symbol visibility. This means that all symbols in extension modules should be declared `static`, except for the module’s initialization function, in order to avoid name clashes with other extension modules (as discussed in section [The Module’s Method Table and Initialization Function](#methodtable)). And it means that symbols that *should* be accessible from other extension modules must be exported in a different way. Python provides a special mechanism to pass C-level information (pointers) from one extension module to another one: Capsules. A Capsule is a Python data type which stores a pointer (`void *`). Capsules can only be created and accessed via their C API, but they can be passed around like any other Python object. In particular, they can be assigned to a name in an extension module’s namespace. Other extension modules can then import this module, retrieve the value of this name, and then retrieve the pointer from the Capsule. There are many ways in which Capsules can be used to export the C API of an extension module. Each function could get its own Capsule, or all C API pointers could be stored in an array whose address is published in a Capsule. And the various tasks of storing and retrieving the pointers can be distributed in different ways between the module providing the code and the client modules. Whichever method you choose, it’s important to name your Capsules properly. The function [`PyCapsule_New()`](../c-api/capsule#c.PyCapsule_New "PyCapsule_New") takes a name parameter (`const char *`); you’re permitted to pass in a `NULL` name, but we strongly encourage you to specify a name. Properly named Capsules provide a degree of runtime type-safety; there is no feasible way to tell one unnamed Capsule from another. In particular, Capsules used to expose C APIs should be given a name following this convention: ``` modulename.attributename ``` The convenience function [`PyCapsule_Import()`](../c-api/capsule#c.PyCapsule_Import "PyCapsule_Import") makes it easy to load a C API provided via a Capsule, but only if the Capsule’s name matches this convention. This behavior gives C API users a high degree of certainty that the Capsule they load contains the correct C API. The following example demonstrates an approach that puts most of the burden on the writer of the exporting module, which is appropriate for commonly used library modules. It stores all C API pointers (just one in the example!) in an array of `void` pointers which becomes the value of a Capsule. The header file corresponding to the module provides a macro that takes care of importing the module and retrieving its C API pointers; client modules only have to call this macro before accessing the C API. The exporting module is a modification of the `spam` module from section [A Simple Example](#extending-simpleexample). The function `spam.system()` does not call the C library function `system()` directly, but a function `PySpam_System()`, which would of course do something more complicated in reality (such as adding “spam” to every command). This function `PySpam_System()` is also exported to other extension modules. The function `PySpam_System()` is a plain C function, declared `static` like everything else: ``` static int PySpam_System(const char *command) { return system(command); } ``` The function `spam_system()` is modified in a trivial way: ``` static PyObject * spam_system(PyObject *self, PyObject *args) { const char *command; int sts; if (!PyArg_ParseTuple(args, "s", &command)) return NULL; sts = PySpam_System(command); return PyLong_FromLong(sts); } ``` In the beginning of the module, right after the line ``` #include <Python.h> ``` two more lines must be added: ``` #define SPAM_MODULE #include "spammodule.h" ``` The `#define` is used to tell the header file that it is being included in the exporting module, not a client module. Finally, the module’s initialization function must take care of initializing the C API pointer array: ``` PyMODINIT_FUNC PyInit_spam(void) { PyObject *m; static void *PySpam_API[PySpam_API_pointers]; PyObject *c_api_object; m = PyModule_Create(&spammodule); if (m == NULL) return NULL; /* Initialize the C API pointer array */ PySpam_API[PySpam_System_NUM] = (void *)PySpam_System; /* Create a Capsule containing the API pointer array's address */ c_api_object = PyCapsule_New((void *)PySpam_API, "spam._C_API", NULL); if (PyModule_AddObject(m, "_C_API", c_api_object) < 0) { Py_XDECREF(c_api_object); Py_DECREF(m); return NULL; } return m; } ``` Note that `PySpam_API` is declared `static`; otherwise the pointer array would disappear when `PyInit_spam()` terminates! The bulk of the work is in the header file `spammodule.h`, which looks like this: ``` #ifndef Py_SPAMMODULE_H #define Py_SPAMMODULE_H #ifdef __cplusplus extern "C" { #endif /* Header file for spammodule */ /* C API functions */ #define PySpam_System_NUM 0 #define PySpam_System_RETURN int #define PySpam_System_PROTO (const char *command) /* Total number of C API pointers */ #define PySpam_API_pointers 1 #ifdef SPAM_MODULE /* This section is used when compiling spammodule.c */ static PySpam_System_RETURN PySpam_System PySpam_System_PROTO; #else /* This section is used in modules that use spammodule's API */ static void **PySpam_API; #define PySpam_System \ (*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM]) /* Return -1 on error, 0 on success. * PyCapsule_Import will set an exception if there's an error. */ static int import_spam(void) { PySpam_API = (void **)PyCapsule_Import("spam._C_API", 0); return (PySpam_API != NULL) ? 0 : -1; } #endif #ifdef __cplusplus } #endif #endif /* !defined(Py_SPAMMODULE_H) */ ``` All that a client module must do in order to have access to the function `PySpam_System()` is to call the function (or rather macro) `import_spam()` in its initialization function: ``` PyMODINIT_FUNC PyInit_client(void) { PyObject *m; m = PyModule_Create(&clientmodule); if (m == NULL) return NULL; if (import_spam() < 0) return NULL; /* additional initialization can happen here */ return m; } ``` The main disadvantage of this approach is that the file `spammodule.h` is rather complicated. However, the basic structure is the same for each function that is exported, so it has to be learned only once. Finally it should be mentioned that Capsules offer additional functionality, which is especially useful for memory allocation and deallocation of the pointer stored in a Capsule. The details are described in the Python/C API Reference Manual in the section [Capsules](../c-api/capsule#capsules) and in the implementation of Capsules (files `Include/pycapsule.h` and `Objects/pycapsule.c` in the Python source code distribution). #### Footnotes `1` An interface for this function already exists in the standard module [`os`](../library/os#module-os "os: Miscellaneous operating system interfaces.") — it was chosen as a simple and straightforward example. `2` The metaphor of “borrowing” a reference is not completely correct: the owner still has a copy of the reference. `3` Checking that the reference count is at least 1 **does not work** — the reference count itself could be in freed memory and may thus be reused for another object! `4` These guarantees don’t hold when you use the “old” style calling convention — this is still found in much existing code.
programming_docs
python Embedding Python in Another Application Embedding Python in Another Application ======================================== The previous chapters discussed how to extend Python, that is, how to extend the functionality of Python by attaching a library of C functions to it. It is also possible to do it the other way around: enrich your C/C++ application by embedding Python in it. Embedding provides your application with the ability to implement some of the functionality of your application in Python rather than C or C++. This can be used for many purposes; one example would be to allow users to tailor the application to their needs by writing some scripts in Python. You can also use it yourself if some of the functionality can be written in Python more easily. Embedding Python is similar to extending it, but not quite. The difference is that when you extend Python, the main program of the application is still the Python interpreter, while if you embed Python, the main program may have nothing to do with Python — instead, some parts of the application occasionally call the Python interpreter to run some Python code. So if you are embedding Python, you are providing your own main program. One of the things this main program has to do is initialize the Python interpreter. At the very least, you have to call the function [`Py_Initialize()`](../c-api/init#c.Py_Initialize "Py_Initialize"). There are optional calls to pass command line arguments to Python. Then later you can call the interpreter from any part of the application. There are several different ways to call the interpreter: you can pass a string containing Python statements to [`PyRun_SimpleString()`](../c-api/veryhigh#c.PyRun_SimpleString "PyRun_SimpleString"), or you can pass a stdio file pointer and a file name (for identification in error messages only) to [`PyRun_SimpleFile()`](../c-api/veryhigh#c.PyRun_SimpleFile "PyRun_SimpleFile"). You can also call the lower-level operations described in the previous chapters to construct and use Python objects. See also [Python/C API Reference Manual](../c-api/index#c-api-index) The details of Python’s C interface are given in this manual. A great deal of necessary information can be found here. 1.1. Very High Level Embedding ------------------------------- The simplest form of embedding Python is the use of the very high level interface. This interface is intended to execute a Python script without needing to interact with the application directly. This can for example be used to perform some operation on a file. ``` #define PY_SSIZE_T_CLEAN #include <Python.h> int main(int argc, char *argv[]) { wchar_t *program = Py_DecodeLocale(argv[0], NULL); if (program == NULL) { fprintf(stderr, "Fatal error: cannot decode argv[0]\n"); exit(1); } Py_SetProgramName(program); /* optional but recommended */ Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print('Today is', ctime(time()))\n"); if (Py_FinalizeEx() < 0) { exit(120); } PyMem_RawFree(program); return 0; } ``` The [`Py_SetProgramName()`](../c-api/init#c.Py_SetProgramName "Py_SetProgramName") function should be called before [`Py_Initialize()`](../c-api/init#c.Py_Initialize "Py_Initialize") to inform the interpreter about paths to Python run-time libraries. Next, the Python interpreter is initialized with [`Py_Initialize()`](../c-api/init#c.Py_Initialize "Py_Initialize"), followed by the execution of a hard-coded Python script that prints the date and time. Afterwards, the [`Py_FinalizeEx()`](../c-api/init#c.Py_FinalizeEx "Py_FinalizeEx") call shuts the interpreter down, followed by the end of the program. In a real program, you may want to get the Python script from another source, perhaps a text-editor routine, a file, or a database. Getting the Python code from a file can better be done by using the [`PyRun_SimpleFile()`](../c-api/veryhigh#c.PyRun_SimpleFile "PyRun_SimpleFile") function, which saves you the trouble of allocating memory space and loading the file contents. 1.2. Beyond Very High Level Embedding: An overview --------------------------------------------------- The high level interface gives you the ability to execute arbitrary pieces of Python code from your application, but exchanging data values is quite cumbersome to say the least. If you want that, you should use lower level calls. At the cost of having to write more C code, you can achieve almost anything. It should be noted that extending Python and embedding Python is quite the same activity, despite the different intent. Most topics discussed in the previous chapters are still valid. To show this, consider what the extension code from Python to C really does: 1. Convert data values from Python to C, 2. Perform a function call to a C routine using the converted values, and 3. Convert the data values from the call from C to Python. When embedding Python, the interface code does: 1. Convert data values from C to Python, 2. Perform a function call to a Python interface routine using the converted values, and 3. Convert the data values from the call from Python to C. As you can see, the data conversion steps are simply swapped to accommodate the different direction of the cross-language transfer. The only difference is the routine that you call between both data conversions. When extending, you call a C routine, when embedding, you call a Python routine. This chapter will not discuss how to convert data from Python to C and vice versa. Also, proper use of references and dealing with errors is assumed to be understood. Since these aspects do not differ from extending the interpreter, you can refer to earlier chapters for the required information. 1.3. Pure Embedding -------------------- The first program aims to execute a function in a Python script. Like in the section about the very high level interface, the Python interpreter does not directly interact with the application (but that will change in the next section). The code to run a function defined in a Python script is: ``` #define PY_SSIZE_T_CLEAN #include <Python.h> int main(int argc, char *argv[]) { PyObject *pName, *pModule, *pFunc; PyObject *pArgs, *pValue; int i; if (argc < 3) { fprintf(stderr,"Usage: call pythonfile funcname [args]\n"); return 1; } Py_Initialize(); pName = PyUnicode_DecodeFSDefault(argv[1]); /* Error checking of pName left out */ pModule = PyImport_Import(pName); Py_DECREF(pName); if (pModule != NULL) { pFunc = PyObject_GetAttrString(pModule, argv[2]); /* pFunc is a new reference */ if (pFunc && PyCallable_Check(pFunc)) { pArgs = PyTuple_New(argc - 3); for (i = 0; i < argc - 3; ++i) { pValue = PyLong_FromLong(atoi(argv[i + 3])); if (!pValue) { Py_DECREF(pArgs); Py_DECREF(pModule); fprintf(stderr, "Cannot convert argument\n"); return 1; } /* pValue reference stolen here: */ PyTuple_SetItem(pArgs, i, pValue); } pValue = PyObject_CallObject(pFunc, pArgs); Py_DECREF(pArgs); if (pValue != NULL) { printf("Result of call: %ld\n", PyLong_AsLong(pValue)); Py_DECREF(pValue); } else { Py_DECREF(pFunc); Py_DECREF(pModule); PyErr_Print(); fprintf(stderr,"Call failed\n"); return 1; } } else { if (PyErr_Occurred()) PyErr_Print(); fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]); } Py_XDECREF(pFunc); Py_DECREF(pModule); } else { PyErr_Print(); fprintf(stderr, "Failed to load \"%s\"\n", argv[1]); return 1; } if (Py_FinalizeEx() < 0) { return 120; } return 0; } ``` This code loads a Python script using `argv[1]`, and calls the function named in `argv[2]`. Its integer arguments are the other values of the `argv` array. If you [compile and link](#compiling) this program (let’s call the finished executable **call**), and use it to execute a Python script, such as: ``` def multiply(a,b): print("Will compute", a, "times", b) c = 0 for i in range(0, a): c = c + b return c ``` then the result should be: ``` $ call multiply multiply 3 2 Will compute 3 times 2 Result of call: 6 ``` Although the program is quite large for its functionality, most of the code is for data conversion between Python and C, and for error reporting. The interesting part with respect to embedding Python starts with ``` Py_Initialize(); pName = PyUnicode_DecodeFSDefault(argv[1]); /* Error checking of pName left out */ pModule = PyImport_Import(pName); ``` After initializing the interpreter, the script is loaded using [`PyImport_Import()`](../c-api/import#c.PyImport_Import "PyImport_Import"). This routine needs a Python string as its argument, which is constructed using the [`PyUnicode_FromString()`](../c-api/unicode#c.PyUnicode_FromString "PyUnicode_FromString") data conversion routine. ``` pFunc = PyObject_GetAttrString(pModule, argv[2]); /* pFunc is a new reference */ if (pFunc && PyCallable_Check(pFunc)) { ... } Py_XDECREF(pFunc); ``` Once the script is loaded, the name we’re looking for is retrieved using [`PyObject_GetAttrString()`](../c-api/object#c.PyObject_GetAttrString "PyObject_GetAttrString"). If the name exists, and the object returned is callable, you can safely assume that it is a function. The program then proceeds by constructing a tuple of arguments as normal. The call to the Python function is then made with: ``` pValue = PyObject_CallObject(pFunc, pArgs); ``` Upon return of the function, `pValue` is either `NULL` or it contains a reference to the return value of the function. Be sure to release the reference after examining the value. 1.4. Extending Embedded Python ------------------------------- Until now, the embedded Python interpreter had no access to functionality from the application itself. The Python API allows this by extending the embedded interpreter. That is, the embedded interpreter gets extended with routines provided by the application. While it sounds complex, it is not so bad. Simply forget for a while that the application starts the Python interpreter. Instead, consider the application to be a set of subroutines, and write some glue code that gives Python access to those routines, just like you would write a normal Python extension. For example: ``` static int numargs=0; /* Return the number of arguments of the application command line */ static PyObject* emb_numargs(PyObject *self, PyObject *args) { if(!PyArg_ParseTuple(args, ":numargs")) return NULL; return PyLong_FromLong(numargs); } static PyMethodDef EmbMethods[] = { {"numargs", emb_numargs, METH_VARARGS, "Return the number of arguments received by the process."}, {NULL, NULL, 0, NULL} }; static PyModuleDef EmbModule = { PyModuleDef_HEAD_INIT, "emb", NULL, -1, EmbMethods, NULL, NULL, NULL, NULL }; static PyObject* PyInit_emb(void) { return PyModule_Create(&EmbModule); } ``` Insert the above code just above the `main()` function. Also, insert the following two statements before the call to [`Py_Initialize()`](../c-api/init#c.Py_Initialize "Py_Initialize"): ``` numargs = argc; PyImport_AppendInittab("emb", &PyInit_emb); ``` These two lines initialize the `numargs` variable, and make the `emb.numargs()` function accessible to the embedded Python interpreter. With these extensions, the Python script can do things like ``` import emb print("Number of arguments", emb.numargs()) ``` In a real application, the methods will expose an API of the application to Python. 1.5. Embedding Python in C++ ----------------------------- It is also possible to embed Python in a C++ program; precisely how this is done will depend on the details of the C++ system used; in general you will need to write the main program in C++, and use the C++ compiler to compile and link your program. There is no need to recompile Python itself using C++. 1.6. Compiling and Linking under Unix-like systems --------------------------------------------------- It is not necessarily trivial to find the right flags to pass to your compiler (and linker) in order to embed the Python interpreter into your application, particularly because Python needs to load library modules implemented as C dynamic extensions (`.so` files) linked against it. To find out the required compiler and linker flags, you can execute the `python*X.Y*-config` script which is generated as part of the installation process (a `python3-config` script may also be available). This script has several options, of which the following will be directly useful to you: * `pythonX.Y-config --cflags` will give you the recommended flags when compiling: ``` $ /opt/bin/python3.4-config --cflags -I/opt/include/python3.4m -I/opt/include/python3.4m -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes ``` * `pythonX.Y-config --ldflags` will give you the recommended flags when linking: ``` $ /opt/bin/python3.4-config --ldflags -L/opt/lib/python3.4/config-3.4m -lpthread -ldl -lutil -lm -lpython3.4m -Xlinker -export-dynamic ``` Note To avoid confusion between several Python installations (and especially between the system Python and your own compiled Python), it is recommended that you use the absolute path to `python*X.Y*-config`, as in the above example. If this procedure doesn’t work for you (it is not guaranteed to work for all Unix-like platforms; however, we welcome [bug reports](../bugs#reporting-bugs)) you will have to read your system’s documentation about dynamic linking and/or examine Python’s `Makefile` (use [`sysconfig.get_makefile_filename()`](../library/sysconfig#sysconfig.get_makefile_filename "sysconfig.get_makefile_filename") to find its location) and compilation options. In this case, the [`sysconfig`](../library/sysconfig#module-sysconfig "sysconfig: Python's configuration information") module is a useful tool to programmatically extract the configuration values that you will want to combine together. For example: ``` >>> import sysconfig >>> sysconfig.get_config_var('LIBS') '-lpthread -ldl -lutil' >>> sysconfig.get_config_var('LINKFORSHARED') '-Xlinker -export-dynamic' ``` python Building C and C++ Extensions Building C and C++ Extensions ============================== A C extension for CPython is a shared library (e.g. a `.so` file on Linux, `.pyd` on Windows), which exports an *initialization function*. To be importable, the shared library must be available on [`PYTHONPATH`](../using/cmdline#envvar-PYTHONPATH), and must be named after the module name, with an appropriate extension. When using distutils, the correct filename is generated automatically. The initialization function has the signature: `PyObject* PyInit_modulename(void)` It returns either a fully-initialized module, or a [`PyModuleDef`](../c-api/module#c.PyModuleDef "PyModuleDef") instance. See [Initializing C modules](../c-api/module#initializing-modules) for details. For modules with ASCII-only names, the function must be named `PyInit_<modulename>`, with `<modulename>` replaced by the name of the module. When using [Multi-phase initialization](../c-api/module#multi-phase-initialization), non-ASCII module names are allowed. In this case, the initialization function name is `PyInitU_<modulename>`, with `<modulename>` encoded using Python’s *punycode* encoding with hyphens replaced by underscores. In Python: ``` def initfunc_name(name): try: suffix = b'_' + name.encode('ascii') except UnicodeEncodeError: suffix = b'U_' + name.encode('punycode').replace(b'-', b'_') return b'PyInit' + suffix ``` It is possible to export multiple modules from a single shared library by defining multiple initialization functions. However, importing them requires using symbolic links or a custom importer, because by default only the function corresponding to the filename is found. See the *“Multiple modules in one library”* section in [**PEP 489**](https://www.python.org/dev/peps/pep-0489) for details. 4.1. Building C and C++ Extensions with distutils -------------------------------------------------- Extension modules can be built using distutils, which is included in Python. Since distutils also supports creation of binary packages, users don’t necessarily need a compiler and distutils to install the extension. A distutils package contains a driver script, `setup.py`. This is a plain Python file, which, in the most simple case, could look like this: ``` from distutils.core import setup, Extension module1 = Extension('demo', sources = ['demo.c']) setup (name = 'PackageName', version = '1.0', description = 'This is a demo package', ext_modules = [module1]) ``` With this `setup.py`, and a file `demo.c`, running ``` python setup.py build ``` will compile `demo.c`, and produce an extension module named `demo` in the `build` directory. Depending on the system, the module file will end up in a subdirectory `build/lib.system`, and may have a name like `demo.so` or `demo.pyd`. In the `setup.py`, all execution is performed by calling the `setup` function. This takes a variable number of keyword arguments, of which the example above uses only a subset. Specifically, the example specifies meta-information to build packages, and it specifies the contents of the package. Normally, a package will contain additional modules, like Python source modules, documentation, subpackages, etc. Please refer to the distutils documentation in [Distributing Python Modules (Legacy version)](../distutils/index#distutils-index) to learn more about the features of distutils; this section explains building extension modules only. It is common to pre-compute arguments to `setup()`, to better structure the driver script. In the example above, the `ext_modules` argument to [`setup()`](../distutils/apiref#distutils.core.setup "distutils.core.setup") is a list of extension modules, each of which is an instance of the `Extension`. In the example, the instance defines an extension named `demo` which is build by compiling a single source file, `demo.c`. In many cases, building an extension is more complex, since additional preprocessor defines and libraries may be needed. This is demonstrated in the example below. ``` from distutils.core import setup, Extension module1 = Extension('demo', define_macros = [('MAJOR_VERSION', '1'), ('MINOR_VERSION', '0')], include_dirs = ['/usr/local/include'], libraries = ['tcl83'], library_dirs = ['/usr/local/lib'], sources = ['demo.c']) setup (name = 'PackageName', version = '1.0', description = 'This is a demo package', author = 'Martin v. Loewis', author_email = '[email protected]', url = 'https://docs.python.org/extending/building', long_description = ''' This is really just a demo package. ''', ext_modules = [module1]) ``` In this example, [`setup()`](../distutils/apiref#distutils.core.setup "distutils.core.setup") is called with additional meta-information, which is recommended when distribution packages have to be built. For the extension itself, it specifies preprocessor defines, include directories, library directories, and libraries. Depending on the compiler, distutils passes this information in different ways to the compiler. For example, on Unix, this may result in the compilation commands ``` gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -DMAJOR_VERSION=1 -DMINOR_VERSION=0 -I/usr/local/include -I/usr/local/include/python2.2 -c demo.c -o build/temp.linux-i686-2.2/demo.o gcc -shared build/temp.linux-i686-2.2/demo.o -L/usr/local/lib -ltcl83 -o build/lib.linux-i686-2.2/demo.so ``` These lines are for demonstration purposes only; distutils users should trust that distutils gets the invocations right. 4.2. Distributing your extension modules ----------------------------------------- When an extension has been successfully built, there are three ways to use it. End-users will typically want to install the module, they do so by running ``` python setup.py install ``` Module maintainers should produce source packages; to do so, they run ``` python setup.py sdist ``` In some cases, additional files need to be included in a source distribution; this is done through a `MANIFEST.in` file; see [Specifying the files to distribute](../distutils/sourcedist#manifest) for details. If the source distribution has been built successfully, maintainers can also create binary distributions. Depending on the platform, one of the following commands can be used to do so. ``` python setup.py bdist_wininst python setup.py bdist_rpm python setup.py bdist_dumb ```
programming_docs
python Defining Extension Types: Tutorial Defining Extension Types: Tutorial =================================== Python allows the writer of a C extension module to define new types that can be manipulated from Python code, much like the built-in [`str`](../library/stdtypes#str "str") and [`list`](../library/stdtypes#list "list") types. The code for all extension types follows a pattern, but there are some details that you need to understand before you can get started. This document is a gentle introduction to the topic. 2.1. The Basics ---------------- The [CPython](../glossary#term-cpython) runtime sees all Python objects as variables of type [`PyObject*`](../c-api/structures#c.PyObject "PyObject"), which serves as a “base type” for all Python objects. The [`PyObject`](../c-api/structures#c.PyObject "PyObject") structure itself only contains the object’s [reference count](../glossary#term-reference-count) and a pointer to the object’s “type object”. This is where the action is; the type object determines which (C) functions get called by the interpreter when, for instance, an attribute gets looked up on an object, a method called, or it is multiplied by another object. These C functions are called “type methods”. So, if you want to define a new extension type, you need to create a new type object. This sort of thing can only be explained by example, so here’s a minimal, but complete, module that defines a new type named `Custom` inside a C extension module `custom`: Note What we’re showing here is the traditional way of defining *static* extension types. It should be adequate for most uses. The C API also allows defining heap-allocated extension types using the [`PyType_FromSpec()`](../c-api/type#c.PyType_FromSpec "PyType_FromSpec") function, which isn’t covered in this tutorial. ``` #define PY_SSIZE_T_CLEAN #include <Python.h> typedef struct { PyObject_HEAD /* Type-specific fields go here. */ } CustomObject; static PyTypeObject CustomType = { PyVarObject_HEAD_INIT(NULL, 0) .tp_name = "custom.Custom", .tp_doc = PyDoc_STR("Custom objects"), .tp_basicsize = sizeof(CustomObject), .tp_itemsize = 0, .tp_flags = Py_TPFLAGS_DEFAULT, .tp_new = PyType_GenericNew, }; static PyModuleDef custommodule = { PyModuleDef_HEAD_INIT, .m_name = "custom", .m_doc = "Example module that creates an extension type.", .m_size = -1, }; PyMODINIT_FUNC PyInit_custom(void) { PyObject *m; if (PyType_Ready(&CustomType) < 0) return NULL; m = PyModule_Create(&custommodule); if (m == NULL) return NULL; Py_INCREF(&CustomType); if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) { Py_DECREF(&CustomType); Py_DECREF(m); return NULL; } return m; } ``` Now that’s quite a bit to take in at once, but hopefully bits will seem familiar from the previous chapter. This file defines three things: 1. What a `Custom` **object** contains: this is the `CustomObject` struct, which is allocated once for each `Custom` instance. 2. How the `Custom` **type** behaves: this is the `CustomType` struct, which defines a set of flags and function pointers that the interpreter inspects when specific operations are requested. 3. How to initialize the `custom` module: this is the `PyInit_custom` function and the associated `custommodule` struct. The first bit is: ``` typedef struct { PyObject_HEAD } CustomObject; ``` This is what a Custom object will contain. `PyObject_HEAD` is mandatory at the start of each object struct and defines a field called `ob_base` of type [`PyObject`](../c-api/structures#c.PyObject "PyObject"), containing a pointer to a type object and a reference count (these can be accessed using the macros [`Py_TYPE`](../c-api/structures#c.Py_TYPE "Py_TYPE") and [`Py_REFCNT`](../c-api/structures#c.Py_REFCNT "Py_REFCNT") respectively). The reason for the macro is to abstract away the layout and to enable additional fields in debug builds. Note There is no semicolon above after the [`PyObject_HEAD`](../c-api/structures#c.PyObject_HEAD "PyObject_HEAD") macro. Be wary of adding one by accident: some compilers will complain. Of course, objects generally store additional data besides the standard `PyObject_HEAD` boilerplate; for example, here is the definition for standard Python floats: ``` typedef struct { PyObject_HEAD double ob_fval; } PyFloatObject; ``` The second bit is the definition of the type object. ``` static PyTypeObject CustomType = { PyVarObject_HEAD_INIT(NULL, 0) .tp_name = "custom.Custom", .tp_doc = PyDoc_STR("Custom objects"), .tp_basicsize = sizeof(CustomObject), .tp_itemsize = 0, .tp_flags = Py_TPFLAGS_DEFAULT, .tp_new = PyType_GenericNew, }; ``` Note We recommend using C99-style designated initializers as above, to avoid listing all the [`PyTypeObject`](../c-api/type#c.PyTypeObject "PyTypeObject") fields that you don’t care about and also to avoid caring about the fields’ declaration order. The actual definition of [`PyTypeObject`](../c-api/type#c.PyTypeObject "PyTypeObject") in `object.h` has many more [fields](../c-api/typeobj#type-structs) than the definition above. The remaining fields will be filled with zeros by the C compiler, and it’s common practice to not specify them explicitly unless you need them. We’re going to pick it apart, one field at a time: ``` PyVarObject_HEAD_INIT(NULL, 0) ``` This line is mandatory boilerplate to initialize the `ob_base` field mentioned above. ``` .tp_name = "custom.Custom", ``` The name of our type. This will appear in the default textual representation of our objects and in some error messages, for example: ``` >>> "" + custom.Custom() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "custom.Custom") to str ``` Note that the name is a dotted name that includes both the module name and the name of the type within the module. The module in this case is `custom` and the type is `Custom`, so we set the type name to `custom.Custom`. Using the real dotted import path is important to make your type compatible with the [`pydoc`](../library/pydoc#module-pydoc "pydoc: Documentation generator and online help system.") and [`pickle`](../library/pickle#module-pickle "pickle: Convert Python objects to streams of bytes and back.") modules. ``` .tp_basicsize = sizeof(CustomObject), .tp_itemsize = 0, ``` This is so that Python knows how much memory to allocate when creating new `Custom` instances. [`tp_itemsize`](../c-api/typeobj#c.PyTypeObject.tp_itemsize "PyTypeObject.tp_itemsize") is only used for variable-sized objects and should otherwise be zero. Note If you want your type to be subclassable from Python, and your type has the same [`tp_basicsize`](../c-api/typeobj#c.PyTypeObject.tp_basicsize "PyTypeObject.tp_basicsize") as its base type, you may have problems with multiple inheritance. A Python subclass of your type will have to list your type first in its [`__bases__`](../library/stdtypes#class.__bases__ "class.__bases__"), or else it will not be able to call your type’s [`__new__()`](../reference/datamodel#object.__new__ "object.__new__") method without getting an error. You can avoid this problem by ensuring that your type has a larger value for [`tp_basicsize`](../c-api/typeobj#c.PyTypeObject.tp_basicsize "PyTypeObject.tp_basicsize") than its base type does. Most of the time, this will be true anyway, because either your base type will be [`object`](../library/functions#object "object"), or else you will be adding data members to your base type, and therefore increasing its size. We set the class flags to [`Py_TPFLAGS_DEFAULT`](../c-api/typeobj#Py_TPFLAGS_DEFAULT "Py_TPFLAGS_DEFAULT"). ``` .tp_flags = Py_TPFLAGS_DEFAULT, ``` All types should include this constant in their flags. It enables all of the members defined until at least Python 3.3. If you need further members, you will need to OR the corresponding flags. We provide a doc string for the type in [`tp_doc`](../c-api/typeobj#c.PyTypeObject.tp_doc "PyTypeObject.tp_doc"). ``` .tp_doc = PyDoc_STR("Custom objects"), ``` To enable object creation, we have to provide a [`tp_new`](../c-api/typeobj#c.PyTypeObject.tp_new "PyTypeObject.tp_new") handler. This is the equivalent of the Python method [`__new__()`](../reference/datamodel#object.__new__ "object.__new__"), but has to be specified explicitly. In this case, we can just use the default implementation provided by the API function [`PyType_GenericNew()`](../c-api/type#c.PyType_GenericNew "PyType_GenericNew"). ``` .tp_new = PyType_GenericNew, ``` Everything else in the file should be familiar, except for some code in `PyInit_custom()`: ``` if (PyType_Ready(&CustomType) < 0) return; ``` This initializes the `Custom` type, filling in a number of members to the appropriate default values, including `ob_type` that we initially set to `NULL`. ``` Py_INCREF(&CustomType); if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) { Py_DECREF(&CustomType); Py_DECREF(m); return NULL; } ``` This adds the type to the module dictionary. This allows us to create `Custom` instances by calling the `Custom` class: ``` >>> import custom >>> mycustom = custom.Custom() ``` That’s it! All that remains is to build it; put the above code in a file called `custom.c` and: ``` from distutils.core import setup, Extension setup(name="custom", version="1.0", ext_modules=[Extension("custom", ["custom.c"])]) ``` in a file called `setup.py`; then typing ``` $ python setup.py build ``` at a shell should produce a file `custom.so` in a subdirectory; move to that directory and fire up Python — you should be able to `import custom` and play around with Custom objects. That wasn’t so hard, was it? Of course, the current Custom type is pretty uninteresting. It has no data and doesn’t do anything. It can’t even be subclassed. Note While this documentation showcases the standard [`distutils`](../library/distutils#module-distutils "distutils: Support for building and installing Python modules into an existing Python installation.") module for building C extensions, it is recommended in real-world use cases to use the newer and better-maintained `setuptools` library. Documentation on how to do this is out of scope for this document and can be found in the [Python Packaging User’s Guide](https://packaging.python.org/tutorials/distributing-packages/). 2.2. Adding data and methods to the Basic example -------------------------------------------------- Let’s extend the basic example to add some data and methods. Let’s also make the type usable as a base class. We’ll create a new module, `custom2` that adds these capabilities: ``` #define PY_SSIZE_T_CLEAN #include <Python.h> #include "structmember.h" typedef struct { PyObject_HEAD PyObject *first; /* first name */ PyObject *last; /* last name */ int number; } CustomObject; static void Custom_dealloc(CustomObject *self) { Py_XDECREF(self->first); Py_XDECREF(self->last); Py_TYPE(self)->tp_free((PyObject *) self); } static PyObject * Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { CustomObject *self; self = (CustomObject *) type->tp_alloc(type, 0); if (self != NULL) { self->first = PyUnicode_FromString(""); if (self->first == NULL) { Py_DECREF(self); return NULL; } self->last = PyUnicode_FromString(""); if (self->last == NULL) { Py_DECREF(self); return NULL; } self->number = 0; } return (PyObject *) self; } static int Custom_init(CustomObject *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"first", "last", "number", NULL}; PyObject *first = NULL, *last = NULL, *tmp; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist, &first, &last, &self->number)) return -1; if (first) { tmp = self->first; Py_INCREF(first); self->first = first; Py_XDECREF(tmp); } if (last) { tmp = self->last; Py_INCREF(last); self->last = last; Py_XDECREF(tmp); } return 0; } static PyMemberDef Custom_members[] = { {"first", T_OBJECT_EX, offsetof(CustomObject, first), 0, "first name"}, {"last", T_OBJECT_EX, offsetof(CustomObject, last), 0, "last name"}, {"number", T_INT, offsetof(CustomObject, number), 0, "custom number"}, {NULL} /* Sentinel */ }; static PyObject * Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored)) { if (self->first == NULL) { PyErr_SetString(PyExc_AttributeError, "first"); return NULL; } if (self->last == NULL) { PyErr_SetString(PyExc_AttributeError, "last"); return NULL; } return PyUnicode_FromFormat("%S %S", self->first, self->last); } static PyMethodDef Custom_methods[] = { {"name", (PyCFunction) Custom_name, METH_NOARGS, "Return the name, combining the first and last name" }, {NULL} /* Sentinel */ }; static PyTypeObject CustomType = { PyVarObject_HEAD_INIT(NULL, 0) .tp_name = "custom2.Custom", .tp_doc = PyDoc_STR("Custom objects"), .tp_basicsize = sizeof(CustomObject), .tp_itemsize = 0, .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, .tp_new = Custom_new, .tp_init = (initproc) Custom_init, .tp_dealloc = (destructor) Custom_dealloc, .tp_members = Custom_members, .tp_methods = Custom_methods, }; static PyModuleDef custommodule = { PyModuleDef_HEAD_INIT, .m_name = "custom2", .m_doc = "Example module that creates an extension type.", .m_size = -1, }; PyMODINIT_FUNC PyInit_custom2(void) { PyObject *m; if (PyType_Ready(&CustomType) < 0) return NULL; m = PyModule_Create(&custommodule); if (m == NULL) return NULL; Py_INCREF(&CustomType); if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) { Py_DECREF(&CustomType); Py_DECREF(m); return NULL; } return m; } ``` This version of the module has a number of changes. We’ve added an extra include: ``` #include <structmember.h> ``` This include provides declarations that we use to handle attributes, as described a bit later. The `Custom` type now has three data attributes in its C struct, *first*, *last*, and *number*. The *first* and *last* variables are Python strings containing first and last names. The *number* attribute is a C integer. The object structure is updated accordingly: ``` typedef struct { PyObject_HEAD PyObject *first; /* first name */ PyObject *last; /* last name */ int number; } CustomObject; ``` Because we now have data to manage, we have to be more careful about object allocation and deallocation. At a minimum, we need a deallocation method: ``` static void Custom_dealloc(CustomObject *self) { Py_XDECREF(self->first); Py_XDECREF(self->last); Py_TYPE(self)->tp_free((PyObject *) self); } ``` which is assigned to the [`tp_dealloc`](../c-api/typeobj#c.PyTypeObject.tp_dealloc "PyTypeObject.tp_dealloc") member: ``` .tp_dealloc = (destructor) Custom_dealloc, ``` This method first clears the reference counts of the two Python attributes. [`Py_XDECREF()`](../c-api/refcounting#c.Py_XDECREF "Py_XDECREF") correctly handles the case where its argument is `NULL` (which might happen here if `tp_new` failed midway). It then calls the [`tp_free`](../c-api/typeobj#c.PyTypeObject.tp_free "PyTypeObject.tp_free") member of the object’s type (computed by `Py_TYPE(self)`) to free the object’s memory. Note that the object’s type might not be `CustomType`, because the object may be an instance of a subclass. Note The explicit cast to `destructor` above is needed because we defined `Custom_dealloc` to take a `CustomObject *` argument, but the `tp_dealloc` function pointer expects to receive a `PyObject *` argument. Otherwise, the compiler will emit a warning. This is object-oriented polymorphism, in C! We want to make sure that the first and last names are initialized to empty strings, so we provide a `tp_new` implementation: ``` static PyObject * Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { CustomObject *self; self = (CustomObject *) type->tp_alloc(type, 0); if (self != NULL) { self->first = PyUnicode_FromString(""); if (self->first == NULL) { Py_DECREF(self); return NULL; } self->last = PyUnicode_FromString(""); if (self->last == NULL) { Py_DECREF(self); return NULL; } self->number = 0; } return (PyObject *) self; } ``` and install it in the [`tp_new`](../c-api/typeobj#c.PyTypeObject.tp_new "PyTypeObject.tp_new") member: ``` .tp_new = Custom_new, ``` The `tp_new` handler is responsible for creating (as opposed to initializing) objects of the type. It is exposed in Python as the [`__new__()`](../reference/datamodel#object.__new__ "object.__new__") method. It is not required to define a `tp_new` member, and indeed many extension types will simply reuse [`PyType_GenericNew()`](../c-api/type#c.PyType_GenericNew "PyType_GenericNew") as done in the first version of the `Custom` type above. In this case, we use the `tp_new` handler to initialize the `first` and `last` attributes to non-`NULL` default values. `tp_new` is passed the type being instantiated (not necessarily `CustomType`, if a subclass is instantiated) and any arguments passed when the type was called, and is expected to return the instance created. `tp_new` handlers always accept positional and keyword arguments, but they often ignore the arguments, leaving the argument handling to initializer (a.k.a. `tp_init` in C or `__init__` in Python) methods. Note `tp_new` shouldn’t call `tp_init` explicitly, as the interpreter will do it itself. The `tp_new` implementation calls the [`tp_alloc`](../c-api/typeobj#c.PyTypeObject.tp_alloc "PyTypeObject.tp_alloc") slot to allocate memory: ``` self = (CustomObject *) type->tp_alloc(type, 0); ``` Since memory allocation may fail, we must check the [`tp_alloc`](../c-api/typeobj#c.PyTypeObject.tp_alloc "PyTypeObject.tp_alloc") result against `NULL` before proceeding. Note We didn’t fill the [`tp_alloc`](../c-api/typeobj#c.PyTypeObject.tp_alloc "PyTypeObject.tp_alloc") slot ourselves. Rather [`PyType_Ready()`](../c-api/type#c.PyType_Ready "PyType_Ready") fills it for us by inheriting it from our base class, which is [`object`](../library/functions#object "object") by default. Most types use the default allocation strategy. Note If you are creating a co-operative [`tp_new`](../c-api/typeobj#c.PyTypeObject.tp_new "PyTypeObject.tp_new") (one that calls a base type’s [`tp_new`](../c-api/typeobj#c.PyTypeObject.tp_new "PyTypeObject.tp_new") or [`__new__()`](../reference/datamodel#object.__new__ "object.__new__")), you must *not* try to determine what method to call using method resolution order at runtime. Always statically determine what type you are going to call, and call its [`tp_new`](../c-api/typeobj#c.PyTypeObject.tp_new "PyTypeObject.tp_new") directly, or via `type->tp_base->tp_new`. If you do not do this, Python subclasses of your type that also inherit from other Python-defined classes may not work correctly. (Specifically, you may not be able to create instances of such subclasses without getting a [`TypeError`](../library/exceptions#TypeError "TypeError").) We also define an initialization function which accepts arguments to provide initial values for our instance: ``` static int Custom_init(CustomObject *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"first", "last", "number", NULL}; PyObject *first = NULL, *last = NULL, *tmp; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist, &first, &last, &self->number)) return -1; if (first) { tmp = self->first; Py_INCREF(first); self->first = first; Py_XDECREF(tmp); } if (last) { tmp = self->last; Py_INCREF(last); self->last = last; Py_XDECREF(tmp); } return 0; } ``` by filling the [`tp_init`](../c-api/typeobj#c.PyTypeObject.tp_init "PyTypeObject.tp_init") slot. ``` .tp_init = (initproc) Custom_init, ``` The [`tp_init`](../c-api/typeobj#c.PyTypeObject.tp_init "PyTypeObject.tp_init") slot is exposed in Python as the [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") method. It is used to initialize an object after it’s created. Initializers always accept positional and keyword arguments, and they should return either `0` on success or `-1` on error. Unlike the `tp_new` handler, there is no guarantee that `tp_init` is called at all (for example, the [`pickle`](../library/pickle#module-pickle "pickle: Convert Python objects to streams of bytes and back.") module by default doesn’t call [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") on unpickled instances). It can also be called multiple times. Anyone can call the [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") method on our objects. For this reason, we have to be extra careful when assigning the new attribute values. We might be tempted, for example to assign the `first` member like this: ``` if (first) { Py_XDECREF(self->first); Py_INCREF(first); self->first = first; } ``` But this would be risky. Our type doesn’t restrict the type of the `first` member, so it could be any kind of object. It could have a destructor that causes code to be executed that tries to access the `first` member; or that destructor could release the [Global interpreter Lock](../glossary#term-gil) and let arbitrary code run in other threads that accesses and modifies our object. To be paranoid and protect ourselves against this possibility, we almost always reassign members before decrementing their reference counts. When don’t we have to do this? * when we absolutely know that the reference count is greater than 1; * when we know that deallocation of the object [1](#id5) will neither release the [GIL](../glossary#term-gil) nor cause any calls back into our type’s code; * when decrementing a reference count in a [`tp_dealloc`](../c-api/typeobj#c.PyTypeObject.tp_dealloc "PyTypeObject.tp_dealloc") handler on a type which doesn’t support cyclic garbage collection [2](#id6). We want to expose our instance variables as attributes. There are a number of ways to do that. The simplest way is to define member definitions: ``` static PyMemberDef Custom_members[] = { {"first", T_OBJECT_EX, offsetof(CustomObject, first), 0, "first name"}, {"last", T_OBJECT_EX, offsetof(CustomObject, last), 0, "last name"}, {"number", T_INT, offsetof(CustomObject, number), 0, "custom number"}, {NULL} /* Sentinel */ }; ``` and put the definitions in the [`tp_members`](../c-api/typeobj#c.PyTypeObject.tp_members "PyTypeObject.tp_members") slot: ``` .tp_members = Custom_members, ``` Each member definition has a member name, type, offset, access flags and documentation string. See the [Generic Attribute Management](newtypes#generic-attribute-management) section below for details. A disadvantage of this approach is that it doesn’t provide a way to restrict the types of objects that can be assigned to the Python attributes. We expect the first and last names to be strings, but any Python objects can be assigned. Further, the attributes can be deleted, setting the C pointers to `NULL`. Even though we can make sure the members are initialized to non-`NULL` values, the members can be set to `NULL` if the attributes are deleted. We define a single method, `Custom.name()`, that outputs the objects name as the concatenation of the first and last names. ``` static PyObject * Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored)) { if (self->first == NULL) { PyErr_SetString(PyExc_AttributeError, "first"); return NULL; } if (self->last == NULL) { PyErr_SetString(PyExc_AttributeError, "last"); return NULL; } return PyUnicode_FromFormat("%S %S", self->first, self->last); } ``` The method is implemented as a C function that takes a `Custom` (or `Custom` subclass) instance as the first argument. Methods always take an instance as the first argument. Methods often take positional and keyword arguments as well, but in this case we don’t take any and don’t need to accept a positional argument tuple or keyword argument dictionary. This method is equivalent to the Python method: ``` def name(self): return "%s %s" % (self.first, self.last) ``` Note that we have to check for the possibility that our `first` and `last` members are `NULL`. This is because they can be deleted, in which case they are set to `NULL`. It would be better to prevent deletion of these attributes and to restrict the attribute values to be strings. We’ll see how to do that in the next section. Now that we’ve defined the method, we need to create an array of method definitions: ``` static PyMethodDef Custom_methods[] = { {"name", (PyCFunction) Custom_name, METH_NOARGS, "Return the name, combining the first and last name" }, {NULL} /* Sentinel */ }; ``` (note that we used the [`METH_NOARGS`](../c-api/structures#METH_NOARGS "METH_NOARGS") flag to indicate that the method is expecting no arguments other than *self*) and assign it to the [`tp_methods`](../c-api/typeobj#c.PyTypeObject.tp_methods "PyTypeObject.tp_methods") slot: ``` .tp_methods = Custom_methods, ``` Finally, we’ll make our type usable as a base class for subclassing. We’ve written our methods carefully so far so that they don’t make any assumptions about the type of the object being created or used, so all we need to do is to add the [`Py_TPFLAGS_BASETYPE`](../c-api/typeobj#Py_TPFLAGS_BASETYPE "Py_TPFLAGS_BASETYPE") to our class flag definition: ``` .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, ``` We rename `PyInit_custom()` to `PyInit_custom2()`, update the module name in the [`PyModuleDef`](../c-api/module#c.PyModuleDef "PyModuleDef") struct, and update the full class name in the [`PyTypeObject`](../c-api/type#c.PyTypeObject "PyTypeObject") struct. Finally, we update our `setup.py` file to build the new module: ``` from distutils.core import setup, Extension setup(name="custom", version="1.0", ext_modules=[ Extension("custom", ["custom.c"]), Extension("custom2", ["custom2.c"]), ]) ``` 2.3. Providing finer control over data attributes -------------------------------------------------- In this section, we’ll provide finer control over how the `first` and `last` attributes are set in the `Custom` example. In the previous version of our module, the instance variables `first` and `last` could be set to non-string values or even deleted. We want to make sure that these attributes always contain strings. ``` #define PY_SSIZE_T_CLEAN #include <Python.h> #include "structmember.h" typedef struct { PyObject_HEAD PyObject *first; /* first name */ PyObject *last; /* last name */ int number; } CustomObject; static void Custom_dealloc(CustomObject *self) { Py_XDECREF(self->first); Py_XDECREF(self->last); Py_TYPE(self)->tp_free((PyObject *) self); } static PyObject * Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { CustomObject *self; self = (CustomObject *) type->tp_alloc(type, 0); if (self != NULL) { self->first = PyUnicode_FromString(""); if (self->first == NULL) { Py_DECREF(self); return NULL; } self->last = PyUnicode_FromString(""); if (self->last == NULL) { Py_DECREF(self); return NULL; } self->number = 0; } return (PyObject *) self; } static int Custom_init(CustomObject *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"first", "last", "number", NULL}; PyObject *first = NULL, *last = NULL, *tmp; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|UUi", kwlist, &first, &last, &self->number)) return -1; if (first) { tmp = self->first; Py_INCREF(first); self->first = first; Py_DECREF(tmp); } if (last) { tmp = self->last; Py_INCREF(last); self->last = last; Py_DECREF(tmp); } return 0; } static PyMemberDef Custom_members[] = { {"number", T_INT, offsetof(CustomObject, number), 0, "custom number"}, {NULL} /* Sentinel */ }; static PyObject * Custom_getfirst(CustomObject *self, void *closure) { Py_INCREF(self->first); return self->first; } static int Custom_setfirst(CustomObject *self, PyObject *value, void *closure) { PyObject *tmp; if (value == NULL) { PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute"); return -1; } if (!PyUnicode_Check(value)) { PyErr_SetString(PyExc_TypeError, "The first attribute value must be a string"); return -1; } tmp = self->first; Py_INCREF(value); self->first = value; Py_DECREF(tmp); return 0; } static PyObject * Custom_getlast(CustomObject *self, void *closure) { Py_INCREF(self->last); return self->last; } static int Custom_setlast(CustomObject *self, PyObject *value, void *closure) { PyObject *tmp; if (value == NULL) { PyErr_SetString(PyExc_TypeError, "Cannot delete the last attribute"); return -1; } if (!PyUnicode_Check(value)) { PyErr_SetString(PyExc_TypeError, "The last attribute value must be a string"); return -1; } tmp = self->last; Py_INCREF(value); self->last = value; Py_DECREF(tmp); return 0; } static PyGetSetDef Custom_getsetters[] = { {"first", (getter) Custom_getfirst, (setter) Custom_setfirst, "first name", NULL}, {"last", (getter) Custom_getlast, (setter) Custom_setlast, "last name", NULL}, {NULL} /* Sentinel */ }; static PyObject * Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored)) { return PyUnicode_FromFormat("%S %S", self->first, self->last); } static PyMethodDef Custom_methods[] = { {"name", (PyCFunction) Custom_name, METH_NOARGS, "Return the name, combining the first and last name" }, {NULL} /* Sentinel */ }; static PyTypeObject CustomType = { PyVarObject_HEAD_INIT(NULL, 0) .tp_name = "custom3.Custom", .tp_doc = PyDoc_STR("Custom objects"), .tp_basicsize = sizeof(CustomObject), .tp_itemsize = 0, .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, .tp_new = Custom_new, .tp_init = (initproc) Custom_init, .tp_dealloc = (destructor) Custom_dealloc, .tp_members = Custom_members, .tp_methods = Custom_methods, .tp_getset = Custom_getsetters, }; static PyModuleDef custommodule = { PyModuleDef_HEAD_INIT, .m_name = "custom3", .m_doc = "Example module that creates an extension type.", .m_size = -1, }; PyMODINIT_FUNC PyInit_custom3(void) { PyObject *m; if (PyType_Ready(&CustomType) < 0) return NULL; m = PyModule_Create(&custommodule); if (m == NULL) return NULL; Py_INCREF(&CustomType); if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) { Py_DECREF(&CustomType); Py_DECREF(m); return NULL; } return m; } ``` To provide greater control, over the `first` and `last` attributes, we’ll use custom getter and setter functions. Here are the functions for getting and setting the `first` attribute: ``` static PyObject * Custom_getfirst(CustomObject *self, void *closure) { Py_INCREF(self->first); return self->first; } static int Custom_setfirst(CustomObject *self, PyObject *value, void *closure) { PyObject *tmp; if (value == NULL) { PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute"); return -1; } if (!PyUnicode_Check(value)) { PyErr_SetString(PyExc_TypeError, "The first attribute value must be a string"); return -1; } tmp = self->first; Py_INCREF(value); self->first = value; Py_DECREF(tmp); return 0; } ``` The getter function is passed a `Custom` object and a “closure”, which is a void pointer. In this case, the closure is ignored. (The closure supports an advanced usage in which definition data is passed to the getter and setter. This could, for example, be used to allow a single set of getter and setter functions that decide the attribute to get or set based on data in the closure.) The setter function is passed the `Custom` object, the new value, and the closure. The new value may be `NULL`, in which case the attribute is being deleted. In our setter, we raise an error if the attribute is deleted or if its new value is not a string. We create an array of [`PyGetSetDef`](../c-api/structures#c.PyGetSetDef "PyGetSetDef") structures: ``` static PyGetSetDef Custom_getsetters[] = { {"first", (getter) Custom_getfirst, (setter) Custom_setfirst, "first name", NULL}, {"last", (getter) Custom_getlast, (setter) Custom_setlast, "last name", NULL}, {NULL} /* Sentinel */ }; ``` and register it in the [`tp_getset`](../c-api/typeobj#c.PyTypeObject.tp_getset "PyTypeObject.tp_getset") slot: ``` .tp_getset = Custom_getsetters, ``` The last item in a [`PyGetSetDef`](../c-api/structures#c.PyGetSetDef "PyGetSetDef") structure is the “closure” mentioned above. In this case, we aren’t using a closure, so we just pass `NULL`. We also remove the member definitions for these attributes: ``` static PyMemberDef Custom_members[] = { {"number", T_INT, offsetof(CustomObject, number), 0, "custom number"}, {NULL} /* Sentinel */ }; ``` We also need to update the [`tp_init`](../c-api/typeobj#c.PyTypeObject.tp_init "PyTypeObject.tp_init") handler to only allow strings [3](#id7) to be passed: ``` static int Custom_init(CustomObject *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"first", "last", "number", NULL}; PyObject *first = NULL, *last = NULL, *tmp; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|UUi", kwlist, &first, &last, &self->number)) return -1; if (first) { tmp = self->first; Py_INCREF(first); self->first = first; Py_DECREF(tmp); } if (last) { tmp = self->last; Py_INCREF(last); self->last = last; Py_DECREF(tmp); } return 0; } ``` With these changes, we can assure that the `first` and `last` members are never `NULL` so we can remove checks for `NULL` values in almost all cases. This means that most of the [`Py_XDECREF()`](../c-api/refcounting#c.Py_XDECREF "Py_XDECREF") calls can be converted to [`Py_DECREF()`](../c-api/refcounting#c.Py_DECREF "Py_DECREF") calls. The only place we can’t change these calls is in the `tp_dealloc` implementation, where there is the possibility that the initialization of these members failed in `tp_new`. We also rename the module initialization function and module name in the initialization function, as we did before, and we add an extra definition to the `setup.py` file. 2.4. Supporting cyclic garbage collection ------------------------------------------ Python has a [cyclic garbage collector (GC)](../glossary#term-garbage-collection) that can identify unneeded objects even when their reference counts are not zero. This can happen when objects are involved in cycles. For example, consider: ``` >>> l = [] >>> l.append(l) >>> del l ``` In this example, we create a list that contains itself. When we delete it, it still has a reference from itself. Its reference count doesn’t drop to zero. Fortunately, Python’s cyclic garbage collector will eventually figure out that the list is garbage and free it. In the second version of the `Custom` example, we allowed any kind of object to be stored in the `first` or `last` attributes [4](#id8). Besides, in the second and third versions, we allowed subclassing `Custom`, and subclasses may add arbitrary attributes. For any of those two reasons, `Custom` objects can participate in cycles: ``` >>> import custom3 >>> class Derived(custom3.Custom): pass ... >>> n = Derived() >>> n.some_attribute = n ``` To allow a `Custom` instance participating in a reference cycle to be properly detected and collected by the cyclic GC, our `Custom` type needs to fill two additional slots and to enable a flag that enables these slots: ``` #define PY_SSIZE_T_CLEAN #include <Python.h> #include "structmember.h" typedef struct { PyObject_HEAD PyObject *first; /* first name */ PyObject *last; /* last name */ int number; } CustomObject; static int Custom_traverse(CustomObject *self, visitproc visit, void *arg) { Py_VISIT(self->first); Py_VISIT(self->last); return 0; } static int Custom_clear(CustomObject *self) { Py_CLEAR(self->first); Py_CLEAR(self->last); return 0; } static void Custom_dealloc(CustomObject *self) { PyObject_GC_UnTrack(self); Custom_clear(self); Py_TYPE(self)->tp_free((PyObject *) self); } static PyObject * Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { CustomObject *self; self = (CustomObject *) type->tp_alloc(type, 0); if (self != NULL) { self->first = PyUnicode_FromString(""); if (self->first == NULL) { Py_DECREF(self); return NULL; } self->last = PyUnicode_FromString(""); if (self->last == NULL) { Py_DECREF(self); return NULL; } self->number = 0; } return (PyObject *) self; } static int Custom_init(CustomObject *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"first", "last", "number", NULL}; PyObject *first = NULL, *last = NULL, *tmp; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|UUi", kwlist, &first, &last, &self->number)) return -1; if (first) { tmp = self->first; Py_INCREF(first); self->first = first; Py_DECREF(tmp); } if (last) { tmp = self->last; Py_INCREF(last); self->last = last; Py_DECREF(tmp); } return 0; } static PyMemberDef Custom_members[] = { {"number", T_INT, offsetof(CustomObject, number), 0, "custom number"}, {NULL} /* Sentinel */ }; static PyObject * Custom_getfirst(CustomObject *self, void *closure) { Py_INCREF(self->first); return self->first; } static int Custom_setfirst(CustomObject *self, PyObject *value, void *closure) { if (value == NULL) { PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute"); return -1; } if (!PyUnicode_Check(value)) { PyErr_SetString(PyExc_TypeError, "The first attribute value must be a string"); return -1; } Py_INCREF(value); Py_CLEAR(self->first); self->first = value; return 0; } static PyObject * Custom_getlast(CustomObject *self, void *closure) { Py_INCREF(self->last); return self->last; } static int Custom_setlast(CustomObject *self, PyObject *value, void *closure) { if (value == NULL) { PyErr_SetString(PyExc_TypeError, "Cannot delete the last attribute"); return -1; } if (!PyUnicode_Check(value)) { PyErr_SetString(PyExc_TypeError, "The last attribute value must be a string"); return -1; } Py_INCREF(value); Py_CLEAR(self->last); self->last = value; return 0; } static PyGetSetDef Custom_getsetters[] = { {"first", (getter) Custom_getfirst, (setter) Custom_setfirst, "first name", NULL}, {"last", (getter) Custom_getlast, (setter) Custom_setlast, "last name", NULL}, {NULL} /* Sentinel */ }; static PyObject * Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored)) { return PyUnicode_FromFormat("%S %S", self->first, self->last); } static PyMethodDef Custom_methods[] = { {"name", (PyCFunction) Custom_name, METH_NOARGS, "Return the name, combining the first and last name" }, {NULL} /* Sentinel */ }; static PyTypeObject CustomType = { PyVarObject_HEAD_INIT(NULL, 0) .tp_name = "custom4.Custom", .tp_doc = PyDoc_STR("Custom objects"), .tp_basicsize = sizeof(CustomObject), .tp_itemsize = 0, .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, .tp_new = Custom_new, .tp_init = (initproc) Custom_init, .tp_dealloc = (destructor) Custom_dealloc, .tp_traverse = (traverseproc) Custom_traverse, .tp_clear = (inquiry) Custom_clear, .tp_members = Custom_members, .tp_methods = Custom_methods, .tp_getset = Custom_getsetters, }; static PyModuleDef custommodule = { PyModuleDef_HEAD_INIT, .m_name = "custom4", .m_doc = "Example module that creates an extension type.", .m_size = -1, }; PyMODINIT_FUNC PyInit_custom4(void) { PyObject *m; if (PyType_Ready(&CustomType) < 0) return NULL; m = PyModule_Create(&custommodule); if (m == NULL) return NULL; Py_INCREF(&CustomType); if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) { Py_DECREF(&CustomType); Py_DECREF(m); return NULL; } return m; } ``` First, the traversal method lets the cyclic GC know about subobjects that could participate in cycles: ``` static int Custom_traverse(CustomObject *self, visitproc visit, void *arg) { int vret; if (self->first) { vret = visit(self->first, arg); if (vret != 0) return vret; } if (self->last) { vret = visit(self->last, arg); if (vret != 0) return vret; } return 0; } ``` For each subobject that can participate in cycles, we need to call the `visit()` function, which is passed to the traversal method. The `visit()` function takes as arguments the subobject and the extra argument *arg* passed to the traversal method. It returns an integer value that must be returned if it is non-zero. Python provides a [`Py_VISIT()`](../c-api/gcsupport#c.Py_VISIT "Py_VISIT") macro that automates calling visit functions. With [`Py_VISIT()`](../c-api/gcsupport#c.Py_VISIT "Py_VISIT"), we can minimize the amount of boilerplate in `Custom_traverse`: ``` static int Custom_traverse(CustomObject *self, visitproc visit, void *arg) { Py_VISIT(self->first); Py_VISIT(self->last); return 0; } ``` Note The [`tp_traverse`](../c-api/typeobj#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse") implementation must name its arguments exactly *visit* and *arg* in order to use [`Py_VISIT()`](../c-api/gcsupport#c.Py_VISIT "Py_VISIT"). Second, we need to provide a method for clearing any subobjects that can participate in cycles: ``` static int Custom_clear(CustomObject *self) { Py_CLEAR(self->first); Py_CLEAR(self->last); return 0; } ``` Notice the use of the [`Py_CLEAR()`](../c-api/refcounting#c.Py_CLEAR "Py_CLEAR") macro. It is the recommended and safe way to clear data attributes of arbitrary types while decrementing their reference counts. If you were to call [`Py_XDECREF()`](../c-api/refcounting#c.Py_XDECREF "Py_XDECREF") instead on the attribute before setting it to `NULL`, there is a possibility that the attribute’s destructor would call back into code that reads the attribute again (*especially* if there is a reference cycle). Note You could emulate [`Py_CLEAR()`](../c-api/refcounting#c.Py_CLEAR "Py_CLEAR") by writing: ``` PyObject *tmp; tmp = self->first; self->first = NULL; Py_XDECREF(tmp); ``` Nevertheless, it is much easier and less error-prone to always use [`Py_CLEAR()`](../c-api/refcounting#c.Py_CLEAR "Py_CLEAR") when deleting an attribute. Don’t try to micro-optimize at the expense of robustness! The deallocator `Custom_dealloc` may call arbitrary code when clearing attributes. It means the circular GC can be triggered inside the function. Since the GC assumes reference count is not zero, we need to untrack the object from the GC by calling [`PyObject_GC_UnTrack()`](../c-api/gcsupport#c.PyObject_GC_UnTrack "PyObject_GC_UnTrack") before clearing members. Here is our reimplemented deallocator using [`PyObject_GC_UnTrack()`](../c-api/gcsupport#c.PyObject_GC_UnTrack "PyObject_GC_UnTrack") and `Custom_clear`: ``` static void Custom_dealloc(CustomObject *self) { PyObject_GC_UnTrack(self); Custom_clear(self); Py_TYPE(self)->tp_free((PyObject *) self); } ``` Finally, we add the [`Py_TPFLAGS_HAVE_GC`](../c-api/typeobj#Py_TPFLAGS_HAVE_GC "Py_TPFLAGS_HAVE_GC") flag to the class flags: ``` .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, ``` That’s pretty much it. If we had written custom [`tp_alloc`](../c-api/typeobj#c.PyTypeObject.tp_alloc "PyTypeObject.tp_alloc") or [`tp_free`](../c-api/typeobj#c.PyTypeObject.tp_free "PyTypeObject.tp_free") handlers, we’d need to modify them for cyclic garbage collection. Most extensions will use the versions automatically provided. 2.5. Subclassing other types ----------------------------- It is possible to create new extension types that are derived from existing types. It is easiest to inherit from the built in types, since an extension can easily use the [`PyTypeObject`](../c-api/type#c.PyTypeObject "PyTypeObject") it needs. It can be difficult to share these [`PyTypeObject`](../c-api/type#c.PyTypeObject "PyTypeObject") structures between extension modules. In this example we will create a `SubList` type that inherits from the built-in [`list`](../library/stdtypes#list "list") type. The new type will be completely compatible with regular lists, but will have an additional `increment()` method that increases an internal counter: ``` >>> import sublist >>> s = sublist.SubList(range(3)) >>> s.extend(s) >>> print(len(s)) 6 >>> print(s.increment()) 1 >>> print(s.increment()) 2 ``` ``` #define PY_SSIZE_T_CLEAN #include <Python.h> typedef struct { PyListObject list; int state; } SubListObject; static PyObject * SubList_increment(SubListObject *self, PyObject *unused) { self->state++; return PyLong_FromLong(self->state); } static PyMethodDef SubList_methods[] = { {"increment", (PyCFunction) SubList_increment, METH_NOARGS, PyDoc_STR("increment state counter")}, {NULL}, }; static int SubList_init(SubListObject *self, PyObject *args, PyObject *kwds) { if (PyList_Type.tp_init((PyObject *) self, args, kwds) < 0) return -1; self->state = 0; return 0; } static PyTypeObject SubListType = { PyVarObject_HEAD_INIT(NULL, 0) .tp_name = "sublist.SubList", .tp_doc = PyDoc_STR("SubList objects"), .tp_basicsize = sizeof(SubListObject), .tp_itemsize = 0, .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, .tp_init = (initproc) SubList_init, .tp_methods = SubList_methods, }; static PyModuleDef sublistmodule = { PyModuleDef_HEAD_INIT, .m_name = "sublist", .m_doc = "Example module that creates an extension type.", .m_size = -1, }; PyMODINIT_FUNC PyInit_sublist(void) { PyObject *m; SubListType.tp_base = &PyList_Type; if (PyType_Ready(&SubListType) < 0) return NULL; m = PyModule_Create(&sublistmodule); if (m == NULL) return NULL; Py_INCREF(&SubListType); if (PyModule_AddObject(m, "SubList", (PyObject *) &SubListType) < 0) { Py_DECREF(&SubListType); Py_DECREF(m); return NULL; } return m; } ``` As you can see, the source code closely resembles the `Custom` examples in previous sections. We will break down the main differences between them. ``` typedef struct { PyListObject list; int state; } SubListObject; ``` The primary difference for derived type objects is that the base type’s object structure must be the first value. The base type will already include the [`PyObject_HEAD()`](../c-api/structures#c.PyObject_HEAD "PyObject_HEAD") at the beginning of its structure. When a Python object is a `SubList` instance, its `PyObject *` pointer can be safely cast to both `PyListObject *` and `SubListObject *`: ``` static int SubList_init(SubListObject *self, PyObject *args, PyObject *kwds) { if (PyList_Type.tp_init((PyObject *) self, args, kwds) < 0) return -1; self->state = 0; return 0; } ``` We see above how to call through to the [`__init__`](../reference/datamodel#object.__init__ "object.__init__") method of the base type. This pattern is important when writing a type with custom [`tp_new`](../c-api/typeobj#c.PyTypeObject.tp_new "PyTypeObject.tp_new") and [`tp_dealloc`](../c-api/typeobj#c.PyTypeObject.tp_dealloc "PyTypeObject.tp_dealloc") members. The [`tp_new`](../c-api/typeobj#c.PyTypeObject.tp_new "PyTypeObject.tp_new") handler should not actually create the memory for the object with its [`tp_alloc`](../c-api/typeobj#c.PyTypeObject.tp_alloc "PyTypeObject.tp_alloc"), but let the base class handle it by calling its own [`tp_new`](../c-api/typeobj#c.PyTypeObject.tp_new "PyTypeObject.tp_new"). The [`PyTypeObject`](../c-api/type#c.PyTypeObject "PyTypeObject") struct supports a [`tp_base`](../c-api/typeobj#c.PyTypeObject.tp_base "PyTypeObject.tp_base") specifying the type’s concrete base class. Due to cross-platform compiler issues, you can’t fill that field directly with a reference to [`PyList_Type`](../c-api/list#c.PyList_Type "PyList_Type"); it should be done later in the module initialization function: ``` PyMODINIT_FUNC PyInit_sublist(void) { PyObject* m; SubListType.tp_base = &PyList_Type; if (PyType_Ready(&SubListType) < 0) return NULL; m = PyModule_Create(&sublistmodule); if (m == NULL) return NULL; Py_INCREF(&SubListType); if (PyModule_AddObject(m, "SubList", (PyObject *) &SubListType) < 0) { Py_DECREF(&SubListType); Py_DECREF(m); return NULL; } return m; } ``` Before calling [`PyType_Ready()`](../c-api/type#c.PyType_Ready "PyType_Ready"), the type structure must have the [`tp_base`](../c-api/typeobj#c.PyTypeObject.tp_base "PyTypeObject.tp_base") slot filled in. When we are deriving an existing type, it is not necessary to fill out the [`tp_alloc`](../c-api/typeobj#c.PyTypeObject.tp_alloc "PyTypeObject.tp_alloc") slot with [`PyType_GenericNew()`](../c-api/type#c.PyType_GenericNew "PyType_GenericNew") – the allocation function from the base type will be inherited. After that, calling [`PyType_Ready()`](../c-api/type#c.PyType_Ready "PyType_Ready") and adding the type object to the module is the same as with the basic `Custom` examples. #### Footnotes `1` This is true when we know that the object is a basic type, like a string or a float. `2` We relied on this in the [`tp_dealloc`](../c-api/typeobj#c.PyTypeObject.tp_dealloc "PyTypeObject.tp_dealloc") handler in this example, because our type doesn’t support garbage collection. `3` We now know that the first and last members are strings, so perhaps we could be less careful about decrementing their reference counts, however, we accept instances of string subclasses. Even though deallocating normal strings won’t call back into our objects, we can’t guarantee that deallocating an instance of a string subclass won’t call back into our objects. `4` Also, even with our attributes restricted to strings instances, the user could pass arbitrary [`str`](../library/stdtypes#str "str") subclasses and therefore still create reference cycles.
programming_docs
python Socket Programming HOWTO Socket Programming HOWTO ======================== Author Gordon McMillan Abstract Sockets are used nearly everywhere, but are one of the most severely misunderstood technologies around. This is a 10,000 foot overview of sockets. It’s not really a tutorial - you’ll still have work to do in getting things operational. It doesn’t cover the fine points (and there are a lot of them), but I hope it will give you enough background to begin using them decently. Sockets ------- I’m only going to talk about INET (i.e. IPv4) sockets, but they account for at least 99% of the sockets in use. And I’ll only talk about STREAM (i.e. TCP) sockets - unless you really know what you’re doing (in which case this HOWTO isn’t for you!), you’ll get better behavior and performance from a STREAM socket than anything else. I will try to clear up the mystery of what a socket is, as well as some hints on how to work with blocking and non-blocking sockets. But I’ll start by talking about blocking sockets. You’ll need to know how they work before dealing with non-blocking sockets. Part of the trouble with understanding these things is that “socket” can mean a number of subtly different things, depending on context. So first, let’s make a distinction between a “client” socket - an endpoint of a conversation, and a “server” socket, which is more like a switchboard operator. The client application (your browser, for example) uses “client” sockets exclusively; the web server it’s talking to uses both “server” sockets and “client” sockets. ### History Of the various forms of IPC, sockets are by far the most popular. On any given platform, there are likely to be other forms of IPC that are faster, but for cross-platform communication, sockets are about the only game in town. They were invented in Berkeley as part of the BSD flavor of Unix. They spread like wildfire with the Internet. With good reason — the combination of sockets with INET makes talking to arbitrary machines around the world unbelievably easy (at least compared to other schemes). Creating a Socket ----------------- Roughly speaking, when you clicked on the link that brought you to this page, your browser did something like the following: ``` # create an INET, STREAMing socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # now connect to the web server on port 80 - the normal http port s.connect(("www.python.org", 80)) ``` When the `connect` completes, the socket `s` can be used to send in a request for the text of the page. The same socket will read the reply, and then be destroyed. That’s right, destroyed. Client sockets are normally only used for one exchange (or a small set of sequential exchanges). What happens in the web server is a bit more complex. First, the web server creates a “server socket”: ``` # create an INET, STREAMing socket serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # bind the socket to a public host, and a well-known port serversocket.bind((socket.gethostname(), 80)) # become a server socket serversocket.listen(5) ``` A couple things to notice: we used `socket.gethostname()` so that the socket would be visible to the outside world. If we had used `s.bind(('localhost', 80))` or `s.bind(('127.0.0.1', 80))` we would still have a “server” socket, but one that was only visible within the same machine. `s.bind(('', 80))` specifies that the socket is reachable by any address the machine happens to have. A second thing to note: low number ports are usually reserved for “well known” services (HTTP, SNMP etc). If you’re playing around, use a nice high number (4 digits). Finally, the argument to `listen` tells the socket library that we want it to queue up as many as 5 connect requests (the normal max) before refusing outside connections. If the rest of the code is written properly, that should be plenty. Now that we have a “server” socket, listening on port 80, we can enter the mainloop of the web server: ``` while True: # accept connections from outside (clientsocket, address) = serversocket.accept() # now do something with the clientsocket # in this case, we'll pretend this is a threaded server ct = client_thread(clientsocket) ct.run() ``` There’s actually 3 general ways in which this loop could work - dispatching a thread to handle `clientsocket`, create a new process to handle `clientsocket`, or restructure this app to use non-blocking sockets, and multiplex between our “server” socket and any active `clientsocket`s using `select`. More about that later. The important thing to understand now is this: this is *all* a “server” socket does. It doesn’t send any data. It doesn’t receive any data. It just produces “client” sockets. Each `clientsocket` is created in response to some *other* “client” socket doing a `connect()` to the host and port we’re bound to. As soon as we’ve created that `clientsocket`, we go back to listening for more connections. The two “clients” are free to chat it up - they are using some dynamically allocated port which will be recycled when the conversation ends. ### IPC If you need fast IPC between two processes on one machine, you should look into pipes or shared memory. If you do decide to use AF\_INET sockets, bind the “server” socket to `'localhost'`. On most platforms, this will take a shortcut around a couple of layers of network code and be quite a bit faster. See also The [`multiprocessing`](../library/multiprocessing#module-multiprocessing "multiprocessing: Process-based parallelism.") integrates cross-platform IPC into a higher-level API. Using a Socket -------------- The first thing to note, is that the web browser’s “client” socket and the web server’s “client” socket are identical beasts. That is, this is a “peer to peer” conversation. Or to put it another way, *as the designer, you will have to decide what the rules of etiquette are for a conversation*. Normally, the `connect`ing socket starts the conversation, by sending in a request, or perhaps a signon. But that’s a design decision - it’s not a rule of sockets. Now there are two sets of verbs to use for communication. You can use `send` and `recv`, or you can transform your client socket into a file-like beast and use `read` and `write`. The latter is the way Java presents its sockets. I’m not going to talk about it here, except to warn you that you need to use `flush` on sockets. These are buffered “files”, and a common mistake is to `write` something, and then `read` for a reply. Without a `flush` in there, you may wait forever for the reply, because the request may still be in your output buffer. Now we come to the major stumbling block of sockets - `send` and `recv` operate on the network buffers. They do not necessarily handle all the bytes you hand them (or expect from them), because their major focus is handling the network buffers. In general, they return when the associated network buffers have been filled (`send`) or emptied (`recv`). They then tell you how many bytes they handled. It is *your* responsibility to call them again until your message has been completely dealt with. When a `recv` returns 0 bytes, it means the other side has closed (or is in the process of closing) the connection. You will not receive any more data on this connection. Ever. You may be able to send data successfully; I’ll talk more about this later. A protocol like HTTP uses a socket for only one transfer. The client sends a request, then reads a reply. That’s it. The socket is discarded. This means that a client can detect the end of the reply by receiving 0 bytes. But if you plan to reuse your socket for further transfers, you need to realize that *there is no* EOT *on a socket.* I repeat: if a socket `send` or `recv` returns after handling 0 bytes, the connection has been broken. If the connection has *not* been broken, you may wait on a `recv` forever, because the socket will *not* tell you that there’s nothing more to read (for now). Now if you think about that a bit, you’ll come to realize a fundamental truth of sockets: *messages must either be fixed length* (yuck), *or be delimited* (shrug), *or indicate how long they are* (much better), *or end by shutting down the connection*. The choice is entirely yours, (but some ways are righter than others). Assuming you don’t want to end the connection, the simplest solution is a fixed length message: ``` class MySocket: """demonstration class only - coded for clarity, not efficiency """ def __init__(self, sock=None): if sock is None: self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM) else: self.sock = sock def connect(self, host, port): self.sock.connect((host, port)) def mysend(self, msg): totalsent = 0 while totalsent < MSGLEN: sent = self.sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError("socket connection broken") totalsent = totalsent + sent def myreceive(self): chunks = [] bytes_recd = 0 while bytes_recd < MSGLEN: chunk = self.sock.recv(min(MSGLEN - bytes_recd, 2048)) if chunk == b'': raise RuntimeError("socket connection broken") chunks.append(chunk) bytes_recd = bytes_recd + len(chunk) return b''.join(chunks) ``` The sending code here is usable for almost any messaging scheme - in Python you send strings, and you can use `len()` to determine its length (even if it has embedded `\0` characters). It’s mostly the receiving code that gets more complex. (And in C, it’s not much worse, except you can’t use `strlen` if the message has embedded `\0`s.) The easiest enhancement is to make the first character of the message an indicator of message type, and have the type determine the length. Now you have two `recv`s - the first to get (at least) that first character so you can look up the length, and the second in a loop to get the rest. If you decide to go the delimited route, you’ll be receiving in some arbitrary chunk size, (4096 or 8192 is frequently a good match for network buffer sizes), and scanning what you’ve received for a delimiter. One complication to be aware of: if your conversational protocol allows multiple messages to be sent back to back (without some kind of reply), and you pass `recv` an arbitrary chunk size, you may end up reading the start of a following message. You’ll need to put that aside and hold onto it, until it’s needed. Prefixing the message with its length (say, as 5 numeric characters) gets more complex, because (believe it or not), you may not get all 5 characters in one `recv`. In playing around, you’ll get away with it; but in high network loads, your code will very quickly break unless you use two `recv` loops - the first to determine the length, the second to get the data part of the message. Nasty. This is also when you’ll discover that `send` does not always manage to get rid of everything in one pass. And despite having read this, you will eventually get bit by it! In the interests of space, building your character, (and preserving my competitive position), these enhancements are left as an exercise for the reader. Lets move on to cleaning up. ### Binary Data It is perfectly possible to send binary data over a socket. The major problem is that not all machines use the same formats for binary data. For example, a Motorola chip will represent a 16 bit integer with the value 1 as the two hex bytes 00 01. Intel and DEC, however, are byte-reversed - that same 1 is 01 00. Socket libraries have calls for converting 16 and 32 bit integers - `ntohl, htonl, ntohs, htons` where “n” means *network* and “h” means *host*, “s” means *short* and “l” means *long*. Where network order is host order, these do nothing, but where the machine is byte-reversed, these swap the bytes around appropriately. In these days of 32 bit machines, the ascii representation of binary data is frequently smaller than the binary representation. That’s because a surprising amount of the time, all those longs have the value 0, or maybe 1. The string “0” would be two bytes, while binary is four. Of course, this doesn’t fit well with fixed-length messages. Decisions, decisions. Disconnecting ------------- Strictly speaking, you’re supposed to use `shutdown` on a socket before you `close` it. The `shutdown` is an advisory to the socket at the other end. Depending on the argument you pass it, it can mean “I’m not going to send anymore, but I’ll still listen”, or “I’m not listening, good riddance!”. Most socket libraries, however, are so used to programmers neglecting to use this piece of etiquette that normally a `close` is the same as `shutdown(); close()`. So in most situations, an explicit `shutdown` is not needed. One way to use `shutdown` effectively is in an HTTP-like exchange. The client sends a request and then does a `shutdown(1)`. This tells the server “This client is done sending, but can still receive.” The server can detect “EOF” by a receive of 0 bytes. It can assume it has the complete request. The server sends a reply. If the `send` completes successfully then, indeed, the client was still receiving. Python takes the automatic shutdown a step further, and says that when a socket is garbage collected, it will automatically do a `close` if it’s needed. But relying on this is a very bad habit. If your socket just disappears without doing a `close`, the socket at the other end may hang indefinitely, thinking you’re just being slow. *Please* `close` your sockets when you’re done. ### When Sockets Die Probably the worst thing about using blocking sockets is what happens when the other side comes down hard (without doing a `close`). Your socket is likely to hang. TCP is a reliable protocol, and it will wait a long, long time before giving up on a connection. If you’re using threads, the entire thread is essentially dead. There’s not much you can do about it. As long as you aren’t doing something dumb, like holding a lock while doing a blocking read, the thread isn’t really consuming much in the way of resources. Do *not* try to kill the thread - part of the reason that threads are more efficient than processes is that they avoid the overhead associated with the automatic recycling of resources. In other words, if you do manage to kill the thread, your whole process is likely to be screwed up. Non-blocking Sockets -------------------- If you’ve understood the preceding, you already know most of what you need to know about the mechanics of using sockets. You’ll still use the same calls, in much the same ways. It’s just that, if you do it right, your app will be almost inside-out. In Python, you use `socket.setblocking(False)` to make it non-blocking. In C, it’s more complex, (for one thing, you’ll need to choose between the BSD flavor `O_NONBLOCK` and the almost indistinguishable POSIX flavor `O_NDELAY`, which is completely different from `TCP_NODELAY`), but it’s the exact same idea. You do this after creating the socket, but before using it. (Actually, if you’re nuts, you can switch back and forth.) The major mechanical difference is that `send`, `recv`, `connect` and `accept` can return without having done anything. You have (of course) a number of choices. You can check return code and error codes and generally drive yourself crazy. If you don’t believe me, try it sometime. Your app will grow large, buggy and suck CPU. So let’s skip the brain-dead solutions and do it right. Use `select`. In C, coding `select` is fairly complex. In Python, it’s a piece of cake, but it’s close enough to the C version that if you understand `select` in Python, you’ll have little trouble with it in C: ``` ready_to_read, ready_to_write, in_error = \ select.select( potential_readers, potential_writers, potential_errs, timeout) ``` You pass `select` three lists: the first contains all sockets that you might want to try reading; the second all the sockets you might want to try writing to, and the last (normally left empty) those that you want to check for errors. You should note that a socket can go into more than one list. The `select` call is blocking, but you can give it a timeout. This is generally a sensible thing to do - give it a nice long timeout (say a minute) unless you have good reason to do otherwise. In return, you will get three lists. They contain the sockets that are actually readable, writable and in error. Each of these lists is a subset (possibly empty) of the corresponding list you passed in. If a socket is in the output readable list, you can be as-close-to-certain-as-we-ever-get-in-this-business that a `recv` on that socket will return *something*. Same idea for the writable list. You’ll be able to send *something*. Maybe not all you want to, but *something* is better than nothing. (Actually, any reasonably healthy socket will return as writable - it just means outbound network buffer space is available.) If you have a “server” socket, put it in the potential\_readers list. If it comes out in the readable list, your `accept` will (almost certainly) work. If you have created a new socket to `connect` to someone else, put it in the potential\_writers list. If it shows up in the writable list, you have a decent chance that it has connected. Actually, `select` can be handy even with blocking sockets. It’s one way of determining whether you will block - the socket returns as readable when there’s something in the buffers. However, this still doesn’t help with the problem of determining whether the other end is done, or just busy with something else. **Portability alert**: On Unix, `select` works both with the sockets and files. Don’t try this on Windows. On Windows, `select` works with sockets only. Also note that in C, many of the more advanced socket options are done differently on Windows. In fact, on Windows I usually use threads (which work very, very well) with my sockets. python Regular Expression HOWTO Regular Expression HOWTO ======================== Author A.M. Kuchling <[[email protected]](mailto:amk%40amk.ca)> Abstract This document is an introductory tutorial to using regular expressions in Python with the [`re`](../library/re#module-re "re: Regular expression operations.") module. It provides a gentler introduction than the corresponding section in the Library Reference. Introduction ------------ Regular expressions (called REs, or regexes, or regex patterns) are essentially a tiny, highly specialized programming language embedded inside Python and made available through the [`re`](../library/re#module-re "re: Regular expression operations.") module. Using this little language, you specify the rules for the set of possible strings that you want to match; this set might contain English sentences, or e-mail addresses, or TeX commands, or anything you like. You can then ask questions such as “Does this string match the pattern?”, or “Is there a match for the pattern anywhere in this string?”. You can also use REs to modify a string or to split it apart in various ways. Regular expression patterns are compiled into a series of bytecodes which are then executed by a matching engine written in C. For advanced use, it may be necessary to pay careful attention to how the engine will execute a given RE, and write the RE in a certain way in order to produce bytecode that runs faster. Optimization isn’t covered in this document, because it requires that you have a good understanding of the matching engine’s internals. The regular expression language is relatively small and restricted, so not all possible string processing tasks can be done using regular expressions. There are also tasks that *can* be done with regular expressions, but the expressions turn out to be very complicated. In these cases, you may be better off writing Python code to do the processing; while Python code will be slower than an elaborate regular expression, it will also probably be more understandable. Simple Patterns --------------- We’ll start by learning about the simplest possible regular expressions. Since regular expressions are used to operate on strings, we’ll begin with the most common task: matching characters. For a detailed explanation of the computer science underlying regular expressions (deterministic and non-deterministic finite automata), you can refer to almost any textbook on writing compilers. ### Matching Characters Most letters and characters will simply match themselves. For example, the regular expression `test` will match the string `test` exactly. (You can enable a case-insensitive mode that would let this RE match `Test` or `TEST` as well; more about this later.) There are exceptions to this rule; some characters are special *metacharacters*, and don’t match themselves. Instead, they signal that some out-of-the-ordinary thing should be matched, or they affect other portions of the RE by repeating them or changing their meaning. Much of this document is devoted to discussing various metacharacters and what they do. Here’s a complete list of the metacharacters; their meanings will be discussed in the rest of this HOWTO. ``` . ^ $ * + ? { } [ ] \ | ( ) ``` The first metacharacters we’ll look at are `[` and `]`. They’re used for specifying a character class, which is a set of characters that you wish to match. Characters can be listed individually, or a range of characters can be indicated by giving two characters and separating them by a `'-'`. For example, `[abc]` will match any of the characters `a`, `b`, or `c`; this is the same as `[a-c]`, which uses a range to express the same set of characters. If you wanted to match only lowercase letters, your RE would be `[a-z]`. Metacharacters (except `\`) are not active inside classes. For example, `[akm$]` will match any of the characters `'a'`, `'k'`, `'m'`, or `'$'`; `'$'` is usually a metacharacter, but inside a character class it’s stripped of its special nature. You can match the characters not listed within the class by *complementing* the set. This is indicated by including a `'^'` as the first character of the class. For example, `[^5]` will match any character except `'5'`. If the caret appears elsewhere in a character class, it does not have special meaning. For example: `[5^]` will match either a `'5'` or a `'^'`. Perhaps the most important metacharacter is the backslash, `\`. As in Python string literals, the backslash can be followed by various characters to signal various special sequences. It’s also used to escape all the metacharacters so you can still match them in patterns; for example, if you need to match a `[` or `\`, you can precede them with a backslash to remove their special meaning: `\[` or `\\`. Some of the special sequences beginning with `'\'` represent predefined sets of characters that are often useful, such as the set of digits, the set of letters, or the set of anything that isn’t whitespace. Let’s take an example: `\w` matches any alphanumeric character. If the regex pattern is expressed in bytes, this is equivalent to the class `[a-zA-Z0-9_]`. If the regex pattern is a string, `\w` will match all the characters marked as letters in the Unicode database provided by the [`unicodedata`](../library/unicodedata#module-unicodedata "unicodedata: Access the Unicode Database.") module. You can use the more restricted definition of `\w` in a string pattern by supplying the [`re.ASCII`](../library/re#re.ASCII "re.ASCII") flag when compiling the regular expression. The following list of special sequences isn’t complete. For a complete list of sequences and expanded class definitions for Unicode string patterns, see the last part of [Regular Expression Syntax](../library/re#re-syntax) in the Standard Library reference. In general, the Unicode versions match any character that’s in the appropriate category in the Unicode database. `\d` Matches any decimal digit; this is equivalent to the class `[0-9]`. `\D` Matches any non-digit character; this is equivalent to the class `[^0-9]`. `\s` Matches any whitespace character; this is equivalent to the class `[ \t\n\r\f\v]`. `\S` Matches any non-whitespace character; this is equivalent to the class `[^ \t\n\r\f\v]`. `\w` Matches any alphanumeric character; this is equivalent to the class `[a-zA-Z0-9_]`. `\W` Matches any non-alphanumeric character; this is equivalent to the class `[^a-zA-Z0-9_]`. These sequences can be included inside a character class. For example, `[\s,.]` is a character class that will match any whitespace character, or `','` or `'.'`. The final metacharacter in this section is `.`. It matches anything except a newline character, and there’s an alternate mode ([`re.DOTALL`](../library/re#re.DOTALL "re.DOTALL")) where it will match even a newline. `.` is often used where you want to match “any character”. ### Repeating Things Being able to match varying sets of characters is the first thing regular expressions can do that isn’t already possible with the methods available on strings. However, if that was the only additional capability of regexes, they wouldn’t be much of an advance. Another capability is that you can specify that portions of the RE must be repeated a certain number of times. The first metacharacter for repeating things that we’ll look at is `*`. `*` doesn’t match the literal character `'*'`; instead, it specifies that the previous character can be matched zero or more times, instead of exactly once. For example, `ca*t` will match `'ct'` (0 `'a'` characters), `'cat'` (1 `'a'`), `'caaat'` (3 `'a'` characters), and so forth. Repetitions such as `*` are *greedy*; when repeating a RE, the matching engine will try to repeat it as many times as possible. If later portions of the pattern don’t match, the matching engine will then back up and try again with fewer repetitions. A step-by-step example will make this more obvious. Let’s consider the expression `a[bcd]*b`. This matches the letter `'a'`, zero or more letters from the class `[bcd]`, and finally ends with a `'b'`. Now imagine matching this RE against the string `'abcbd'`. | Step | Matched | Explanation | | --- | --- | --- | | 1 | `a` | The `a` in the RE matches. | | 2 | `abcbd` | The engine matches `[bcd]*`, going as far as it can, which is to the end of the string. | | 3 | *Failure* | The engine tries to match `b`, but the current position is at the end of the string, so it fails. | | 4 | `abcb` | Back up, so that `[bcd]*` matches one less character. | | 5 | *Failure* | Try `b` again, but the current position is at the last character, which is a `'d'`. | | 6 | `abc` | Back up again, so that `[bcd]*` is only matching `bc`. | | 6 | `abcb` | Try `b` again. This time the character at the current position is `'b'`, so it succeeds. | The end of the RE has now been reached, and it has matched `'abcb'`. This demonstrates how the matching engine goes as far as it can at first, and if no match is found it will then progressively back up and retry the rest of the RE again and again. It will back up until it has tried zero matches for `[bcd]*`, and if that subsequently fails, the engine will conclude that the string doesn’t match the RE at all. Another repeating metacharacter is `+`, which matches one or more times. Pay careful attention to the difference between `*` and `+`; `*` matches *zero* or more times, so whatever’s being repeated may not be present at all, while `+` requires at least *one* occurrence. To use a similar example, `ca+t` will match `'cat'` (1 `'a'`), `'caaat'` (3 `'a'`s), but won’t match `'ct'`. There are two more repeating qualifiers. The question mark character, `?`, matches either once or zero times; you can think of it as marking something as being optional. For example, `home-?brew` matches either `'homebrew'` or `'home-brew'`. The most complicated repeated qualifier is `{m,n}`, where *m* and *n* are decimal integers. This qualifier means there must be at least *m* repetitions, and at most *n*. For example, `a/{1,3}b` will match `'a/b'`, `'a//b'`, and `'a///b'`. It won’t match `'ab'`, which has no slashes, or `'a////b'`, which has four. You can omit either *m* or *n*; in that case, a reasonable value is assumed for the missing value. Omitting *m* is interpreted as a lower limit of 0, while omitting *n* results in an upper bound of infinity. Readers of a reductionist bent may notice that the three other qualifiers can all be expressed using this notation. `{0,}` is the same as `*`, `{1,}` is equivalent to `+`, and `{0,1}` is the same as `?`. It’s better to use `*`, `+`, or `?` when you can, simply because they’re shorter and easier to read. Using Regular Expressions ------------------------- Now that we’ve looked at some simple regular expressions, how do we actually use them in Python? The [`re`](../library/re#module-re "re: Regular expression operations.") module provides an interface to the regular expression engine, allowing you to compile REs into objects and then perform matches with them. ### Compiling Regular Expressions Regular expressions are compiled into pattern objects, which have methods for various operations such as searching for pattern matches or performing string substitutions. ``` >>> import re >>> p = re.compile('ab*') >>> p re.compile('ab*') ``` [`re.compile()`](../library/re#re.compile "re.compile") also accepts an optional *flags* argument, used to enable various special features and syntax variations. We’ll go over the available settings later, but for now a single example will do: ``` >>> p = re.compile('ab*', re.IGNORECASE) ``` The RE is passed to [`re.compile()`](../library/re#re.compile "re.compile") as a string. REs are handled as strings because regular expressions aren’t part of the core Python language, and no special syntax was created for expressing them. (There are applications that don’t need REs at all, so there’s no need to bloat the language specification by including them.) Instead, the [`re`](../library/re#module-re "re: Regular expression operations.") module is simply a C extension module included with Python, just like the [`socket`](../library/socket#module-socket "socket: Low-level networking interface.") or [`zlib`](../library/zlib#module-zlib "zlib: Low-level interface to compression and decompression routines compatible with gzip.") modules. Putting REs in strings keeps the Python language simpler, but has one disadvantage which is the topic of the next section. ### The Backslash Plague As stated earlier, regular expressions use the backslash character (`'\'`) to indicate special forms or to allow special characters to be used without invoking their special meaning. This conflicts with Python’s usage of the same character for the same purpose in string literals. Let’s say you want to write a RE that matches the string `\section`, which might be found in a LaTeX file. To figure out what to write in the program code, start with the desired string to be matched. Next, you must escape any backslashes and other metacharacters by preceding them with a backslash, resulting in the string `\\section`. The resulting string that must be passed to [`re.compile()`](../library/re#re.compile "re.compile") must be `\\section`. However, to express this as a Python string literal, both backslashes must be escaped *again*. | Characters | Stage | | --- | --- | | `\section` | Text string to be matched | | `\\section` | Escaped backslash for [`re.compile()`](../library/re#re.compile "re.compile") | | `"\\\\section"` | Escaped backslashes for a string literal | In short, to match a literal backslash, one has to write `'\\\\'` as the RE string, because the regular expression must be `\\`, and each backslash must be expressed as `\\` inside a regular Python string literal. In REs that feature backslashes repeatedly, this leads to lots of repeated backslashes and makes the resulting strings difficult to understand. The solution is to use Python’s raw string notation for regular expressions; backslashes are not handled in any special way in a string literal prefixed with `'r'`, so `r"\n"` is a two-character string containing `'\'` and `'n'`, while `"\n"` is a one-character string containing a newline. Regular expressions will often be written in Python code using this raw string notation. In addition, special escape sequences that are valid in regular expressions, but not valid as Python string literals, now result in a [`DeprecationWarning`](../library/exceptions#DeprecationWarning "DeprecationWarning") and will eventually become a [`SyntaxError`](../library/exceptions#SyntaxError "SyntaxError"), which means the sequences will be invalid if raw string notation or escaping the backslashes isn’t used. | Regular String | Raw string | | --- | --- | | `"ab*"` | `r"ab*"` | | `"\\\\section"` | `r"\\section"` | | `"\\w+\\s+\\1"` | `r"\w+\s+\1"` | ### Performing Matches Once you have an object representing a compiled regular expression, what do you do with it? Pattern objects have several methods and attributes. Only the most significant ones will be covered here; consult the [`re`](../library/re#module-re "re: Regular expression operations.") docs for a complete listing. | Method/Attribute | Purpose | | --- | --- | | `match()` | Determine if the RE matches at the beginning of the string. | | `search()` | Scan through a string, looking for any location where this RE matches. | | `findall()` | Find all substrings where the RE matches, and returns them as a list. | | `finditer()` | Find all substrings where the RE matches, and returns them as an [iterator](../glossary#term-iterator). | [`match()`](../library/re#re.Pattern.match "re.Pattern.match") and [`search()`](../library/re#re.Pattern.search "re.Pattern.search") return `None` if no match can be found. If they’re successful, a [match object](../library/re#match-objects) instance is returned, containing information about the match: where it starts and ends, the substring it matched, and more. You can learn about this by interactively experimenting with the [`re`](../library/re#module-re "re: Regular expression operations.") module. If you have [`tkinter`](../library/tkinter#module-tkinter "tkinter: Interface to Tcl/Tk for graphical user interfaces") available, you may also want to look at [Tools/demo/redemo.py](https://github.com/python/cpython/tree/3.9/Tools/demo/redemo.py), a demonstration program included with the Python distribution. It allows you to enter REs and strings, and displays whether the RE matches or fails. `redemo.py` can be quite useful when trying to debug a complicated RE. This HOWTO uses the standard Python interpreter for its examples. First, run the Python interpreter, import the [`re`](../library/re#module-re "re: Regular expression operations.") module, and compile a RE: ``` >>> import re >>> p = re.compile('[a-z]+') >>> p re.compile('[a-z]+') ``` Now, you can try matching various strings against the RE `[a-z]+`. An empty string shouldn’t match at all, since `+` means ‘one or more repetitions’. [`match()`](../library/re#re.Pattern.match "re.Pattern.match") should return `None` in this case, which will cause the interpreter to print no output. You can explicitly print the result of `match()` to make this clear. ``` >>> p.match("") >>> print(p.match("")) None ``` Now, let’s try it on a string that it should match, such as `tempo`. In this case, [`match()`](../library/re#re.Pattern.match "re.Pattern.match") will return a [match object](../library/re#match-objects), so you should store the result in a variable for later use. ``` >>> m = p.match('tempo') >>> m <re.Match object; span=(0, 5), match='tempo'> ``` Now you can query the [match object](../library/re#match-objects) for information about the matching string. Match object instances also have several methods and attributes; the most important ones are: | Method/Attribute | Purpose | | --- | --- | | `group()` | Return the string matched by the RE | | `start()` | Return the starting position of the match | | `end()` | Return the ending position of the match | | `span()` | Return a tuple containing the (start, end) positions of the match | Trying these methods will soon clarify their meaning: ``` >>> m.group() 'tempo' >>> m.start(), m.end() (0, 5) >>> m.span() (0, 5) ``` [`group()`](../library/re#re.Match.group "re.Match.group") returns the substring that was matched by the RE. [`start()`](../library/re#re.Match.start "re.Match.start") and [`end()`](../library/re#re.Match.end "re.Match.end") return the starting and ending index of the match. [`span()`](../library/re#re.Match.span "re.Match.span") returns both start and end indexes in a single tuple. Since the [`match()`](../library/re#re.Pattern.match "re.Pattern.match") method only checks if the RE matches at the start of a string, `start()` will always be zero. However, the [`search()`](../library/re#re.Pattern.search "re.Pattern.search") method of patterns scans through the string, so the match may not start at zero in that case. ``` >>> print(p.match('::: message')) None >>> m = p.search('::: message'); print(m) <re.Match object; span=(4, 11), match='message'> >>> m.group() 'message' >>> m.span() (4, 11) ``` In actual programs, the most common style is to store the [match object](../library/re#match-objects) in a variable, and then check if it was `None`. This usually looks like: ``` p = re.compile( ... ) m = p.match( 'string goes here' ) if m: print('Match found: ', m.group()) else: print('No match') ``` Two pattern methods return all of the matches for a pattern. [`findall()`](../library/re#re.Pattern.findall "re.Pattern.findall") returns a list of matching strings: ``` >>> p = re.compile(r'\d+') >>> p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping') ['12', '11', '10'] ``` The `r` prefix, making the literal a raw string literal, is needed in this example because escape sequences in a normal “cooked” string literal that are not recognized by Python, as opposed to regular expressions, now result in a [`DeprecationWarning`](../library/exceptions#DeprecationWarning "DeprecationWarning") and will eventually become a [`SyntaxError`](../library/exceptions#SyntaxError "SyntaxError"). See [The Backslash Plague](#the-backslash-plague). [`findall()`](../library/re#re.Pattern.findall "re.Pattern.findall") has to create the entire list before it can be returned as the result. The [`finditer()`](../library/re#re.Pattern.finditer "re.Pattern.finditer") method returns a sequence of [match object](../library/re#match-objects) instances as an [iterator](../glossary#term-iterator): ``` >>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...') >>> iterator <callable_iterator object at 0x...> >>> for match in iterator: ... print(match.span()) ... (0, 2) (22, 24) (29, 31) ``` ### Module-Level Functions You don’t have to create a pattern object and call its methods; the [`re`](../library/re#module-re "re: Regular expression operations.") module also provides top-level functions called [`match()`](../library/re#re.match "re.match"), [`search()`](../library/re#re.search "re.search"), [`findall()`](../library/re#re.findall "re.findall"), [`sub()`](../library/re#re.sub "re.sub"), and so forth. These functions take the same arguments as the corresponding pattern method with the RE string added as the first argument, and still return either `None` or a [match object](../library/re#match-objects) instance. ``` >>> print(re.match(r'From\s+', 'Fromage amk')) None >>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998') <re.Match object; span=(0, 5), match='From '> ``` Under the hood, these functions simply create a pattern object for you and call the appropriate method on it. They also store the compiled object in a cache, so future calls using the same RE won’t need to parse the pattern again and again. Should you use these module-level functions, or should you get the pattern and call its methods yourself? If you’re accessing a regex within a loop, pre-compiling it will save a few function calls. Outside of loops, there’s not much difference thanks to the internal cache. ### Compilation Flags Compilation flags let you modify some aspects of how regular expressions work. Flags are available in the [`re`](../library/re#module-re "re: Regular expression operations.") module under two names, a long name such as `IGNORECASE` and a short, one-letter form such as `I`. (If you’re familiar with Perl’s pattern modifiers, the one-letter forms use the same letters; the short form of [`re.VERBOSE`](../library/re#re.VERBOSE "re.VERBOSE") is [`re.X`](../library/re#re.X "re.X"), for example.) Multiple flags can be specified by bitwise OR-ing them; `re.I | re.M` sets both the `I` and `M` flags, for example. Here’s a table of the available flags, followed by a more detailed explanation of each one. | Flag | Meaning | | --- | --- | | `ASCII`, `A` | Makes several escapes like `\w`, `\b`, `\s` and `\d` match only on ASCII characters with the respective property. | | `DOTALL`, `S` | Make `.` match any character, including newlines. | | `IGNORECASE`, `I` | Do case-insensitive matches. | | `LOCALE`, `L` | Do a locale-aware match. | | `MULTILINE`, `M` | Multi-line matching, affecting `^` and `$`. | | `VERBOSE`, `X` (for ‘extended’) | Enable verbose REs, which can be organized more cleanly and understandably. | `I` `IGNORECASE` Perform case-insensitive matching; character class and literal strings will match letters by ignoring case. For example, `[A-Z]` will match lowercase letters, too. Full Unicode matching also works unless the `ASCII` flag is used to disable non-ASCII matches. When the Unicode patterns `[a-z]` or `[A-Z]` are used in combination with the `IGNORECASE` flag, they will match the 52 ASCII letters and 4 additional non-ASCII letters: ‘İ’ (U+0130, Latin capital letter I with dot above), ‘ı’ (U+0131, Latin small letter dotless i), ‘ſ’ (U+017F, Latin small letter long s) and ‘K’ (U+212A, Kelvin sign). `Spam` will match `'Spam'`, `'spam'`, `'spAM'`, or `'ſpam'` (the latter is matched only in Unicode mode). This lowercasing doesn’t take the current locale into account; it will if you also set the `LOCALE` flag. `L` `LOCALE` Make `\w`, `\W`, `\b`, `\B` and case-insensitive matching dependent on the current locale instead of the Unicode database. Locales are a feature of the C library intended to help in writing programs that take account of language differences. For example, if you’re processing encoded French text, you’d want to be able to write `\w+` to match words, but `\w` only matches the character class `[A-Za-z]` in bytes patterns; it won’t match bytes corresponding to `é` or `ç`. If your system is configured properly and a French locale is selected, certain C functions will tell the program that the byte corresponding to `é` should also be considered a letter. Setting the `LOCALE` flag when compiling a regular expression will cause the resulting compiled object to use these C functions for `\w`; this is slower, but also enables `\w+` to match French words as you’d expect. The use of this flag is discouraged in Python 3 as the locale mechanism is very unreliable, it only handles one “culture” at a time, and it only works with 8-bit locales. Unicode matching is already enabled by default in Python 3 for Unicode (str) patterns, and it is able to handle different locales/languages. `M` `MULTILINE` (`^` and `$` haven’t been explained yet; they’ll be introduced in section [More Metacharacters](#more-metacharacters).) Usually `^` matches only at the beginning of the string, and `$` matches only at the end of the string and immediately before the newline (if any) at the end of the string. When this flag is specified, `^` matches at the beginning of the string and at the beginning of each line within the string, immediately following each newline. Similarly, the `$` metacharacter matches either at the end of the string and at the end of each line (immediately preceding each newline). `S` `DOTALL` Makes the `'.'` special character match any character at all, including a newline; without this flag, `'.'` will match anything *except* a newline. `A` `ASCII` Make `\w`, `\W`, `\b`, `\B`, `\s` and `\S` perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns. `X` `VERBOSE` This flag allows you to write regular expressions that are more readable by granting you more flexibility in how you can format them. When this flag has been specified, whitespace within the RE string is ignored, except when the whitespace is in a character class or preceded by an unescaped backslash; this lets you organize and indent the RE more clearly. This flag also lets you put comments within a RE that will be ignored by the engine; comments are marked by a `'#'` that’s neither in a character class or preceded by an unescaped backslash. For example, here’s a RE that uses [`re.VERBOSE`](../library/re#re.VERBOSE "re.VERBOSE"); see how much easier it is to read? ``` charref = re.compile(r""" &[#] # Start of a numeric entity reference ( 0[0-7]+ # Octal form | [0-9]+ # Decimal form | x[0-9a-fA-F]+ # Hexadecimal form ) ; # Trailing semicolon """, re.VERBOSE) ``` Without the verbose setting, the RE would look like this: ``` charref = re.compile("&#(0[0-7]+" "|[0-9]+" "|x[0-9a-fA-F]+);") ``` In the above example, Python’s automatic concatenation of string literals has been used to break up the RE into smaller pieces, but it’s still more difficult to understand than the version using [`re.VERBOSE`](../library/re#re.VERBOSE "re.VERBOSE"). More Pattern Power ------------------ So far we’ve only covered a part of the features of regular expressions. In this section, we’ll cover some new metacharacters, and how to use groups to retrieve portions of the text that was matched. ### More Metacharacters There are some metacharacters that we haven’t covered yet. Most of them will be covered in this section. Some of the remaining metacharacters to be discussed are *zero-width assertions*. They don’t cause the engine to advance through the string; instead, they consume no characters at all, and simply succeed or fail. For example, `\b` is an assertion that the current position is located at a word boundary; the position isn’t changed by the `\b` at all. This means that zero-width assertions should never be repeated, because if they match once at a given location, they can obviously be matched an infinite number of times. `|` Alternation, or the “or” operator. If *A* and *B* are regular expressions, `A|B` will match any string that matches either *A* or *B*. `|` has very low precedence in order to make it work reasonably when you’re alternating multi-character strings. `Crow|Servo` will match either `'Crow'` or `'Servo'`, not `'Cro'`, a `'w'` or an `'S'`, and `'ervo'`. To match a literal `'|'`, use `\|`, or enclose it inside a character class, as in `[|]`. `^` Matches at the beginning of lines. Unless the `MULTILINE` flag has been set, this will only match at the beginning of the string. In `MULTILINE` mode, this also matches immediately after each newline within the string. For example, if you wish to match the word `From` only at the beginning of a line, the RE to use is `^From`. ``` >>> print(re.search('^From', 'From Here to Eternity')) <re.Match object; span=(0, 4), match='From'> >>> print(re.search('^From', 'Reciting From Memory')) None ``` To match a literal `'^'`, use `\^`. `$` Matches at the end of a line, which is defined as either the end of the string, or any location followed by a newline character. ``` >>> print(re.search('}$', '{block}')) <re.Match object; span=(6, 7), match='}'> >>> print(re.search('}$', '{block} ')) None >>> print(re.search('}$', '{block}\n')) <re.Match object; span=(6, 7), match='}'> ``` To match a literal `'$'`, use `\$` or enclose it inside a character class, as in `[$]`. `\A` Matches only at the start of the string. When not in `MULTILINE` mode, `\A` and `^` are effectively the same. In `MULTILINE` mode, they’re different: `\A` still matches only at the beginning of the string, but `^` may match at any location inside the string that follows a newline character. `\Z` Matches only at the end of the string. `\b` Word boundary. This is a zero-width assertion that matches only at the beginning or end of a word. A word is defined as a sequence of alphanumeric characters, so the end of a word is indicated by whitespace or a non-alphanumeric character. The following example matches `class` only when it’s a complete word; it won’t match when it’s contained inside another word. ``` >>> p = re.compile(r'\bclass\b') >>> print(p.search('no class at all')) <re.Match object; span=(3, 8), match='class'> >>> print(p.search('the declassified algorithm')) None >>> print(p.search('one subclass is')) None ``` There are two subtleties you should remember when using this special sequence. First, this is the worst collision between Python’s string literals and regular expression sequences. In Python’s string literals, `\b` is the backspace character, ASCII value 8. If you’re not using raw strings, then Python will convert the `\b` to a backspace, and your RE won’t match as you expect it to. The following example looks the same as our previous RE, but omits the `'r'` in front of the RE string. ``` >>> p = re.compile('\bclass\b') >>> print(p.search('no class at all')) None >>> print(p.search('\b' + 'class' + '\b')) <re.Match object; span=(0, 7), match='\x08class\x08'> ``` Second, inside a character class, where there’s no use for this assertion, `\b` represents the backspace character, for compatibility with Python’s string literals. `\B` Another zero-width assertion, this is the opposite of `\b`, only matching when the current position is not at a word boundary. ### Grouping Frequently you need to obtain more information than just whether the RE matched or not. Regular expressions are often used to dissect strings by writing a RE divided into several subgroups which match different components of interest. For example, an RFC-822 header line is divided into a header name and a value, separated by a `':'`, like this: ``` From: [email protected] User-Agent: Thunderbird 1.5.0.9 (X11/20061227) MIME-Version: 1.0 To: [email protected] ``` This can be handled by writing a regular expression which matches an entire header line, and has one group which matches the header name, and another group which matches the header’s value. Groups are marked by the `'('`, `')'` metacharacters. `'('` and `')'` have much the same meaning as they do in mathematical expressions; they group together the expressions contained inside them, and you can repeat the contents of a group with a repeating qualifier, such as `*`, `+`, `?`, or `{m,n}`. For example, `(ab)*` will match zero or more repetitions of `ab`. ``` >>> p = re.compile('(ab)*') >>> print(p.match('ababababab').span()) (0, 10) ``` Groups indicated with `'('`, `')'` also capture the starting and ending index of the text that they match; this can be retrieved by passing an argument to [`group()`](../library/re#re.Match.group "re.Match.group"), [`start()`](../library/re#re.Match.start "re.Match.start"), [`end()`](../library/re#re.Match.end "re.Match.end"), and [`span()`](../library/re#re.Match.span "re.Match.span"). Groups are numbered starting with 0. Group 0 is always present; it’s the whole RE, so [match object](../library/re#match-objects) methods all have group 0 as their default argument. Later we’ll see how to express groups that don’t capture the span of text that they match. ``` >>> p = re.compile('(a)b') >>> m = p.match('ab') >>> m.group() 'ab' >>> m.group(0) 'ab' ``` Subgroups are numbered from left to right, from 1 upward. Groups can be nested; to determine the number, just count the opening parenthesis characters, going from left to right. ``` >>> p = re.compile('(a(b)c)d') >>> m = p.match('abcd') >>> m.group(0) 'abcd' >>> m.group(1) 'abc' >>> m.group(2) 'b' ``` [`group()`](../library/re#re.Match.group "re.Match.group") can be passed multiple group numbers at a time, in which case it will return a tuple containing the corresponding values for those groups. ``` >>> m.group(2,1,2) ('b', 'abc', 'b') ``` The [`groups()`](../library/re#re.Match.groups "re.Match.groups") method returns a tuple containing the strings for all the subgroups, from 1 up to however many there are. ``` >>> m.groups() ('abc', 'b') ``` Backreferences in a pattern allow you to specify that the contents of an earlier capturing group must also be found at the current location in the string. For example, `\1` will succeed if the exact contents of group 1 can be found at the current position, and fails otherwise. Remember that Python’s string literals also use a backslash followed by numbers to allow including arbitrary characters in a string, so be sure to use a raw string when incorporating backreferences in a RE. For example, the following RE detects doubled words in a string. ``` >>> p = re.compile(r'\b(\w+)\s+\1\b') >>> p.search('Paris in the the spring').group() 'the the' ``` Backreferences like this aren’t often useful for just searching through a string — there are few text formats which repeat data in this way — but you’ll soon find out that they’re *very* useful when performing string substitutions. ### Non-capturing and Named Groups Elaborate REs may use many groups, both to capture substrings of interest, and to group and structure the RE itself. In complex REs, it becomes difficult to keep track of the group numbers. There are two features which help with this problem. Both of them use a common syntax for regular expression extensions, so we’ll look at that first. Perl 5 is well known for its powerful additions to standard regular expressions. For these new features the Perl developers couldn’t choose new single-keystroke metacharacters or new special sequences beginning with `\` without making Perl’s regular expressions confusingly different from standard REs. If they chose `&` as a new metacharacter, for example, old expressions would be assuming that `&` was a regular character and wouldn’t have escaped it by writing `\&` or `[&]`. The solution chosen by the Perl developers was to use `(?...)` as the extension syntax. `?` immediately after a parenthesis was a syntax error because the `?` would have nothing to repeat, so this didn’t introduce any compatibility problems. The characters immediately after the `?` indicate what extension is being used, so `(?=foo)` is one thing (a positive lookahead assertion) and `(?:foo)` is something else (a non-capturing group containing the subexpression `foo`). Python supports several of Perl’s extensions and adds an extension syntax to Perl’s extension syntax. If the first character after the question mark is a `P`, you know that it’s an extension that’s specific to Python. Now that we’ve looked at the general extension syntax, we can return to the features that simplify working with groups in complex REs. Sometimes you’ll want to use a group to denote a part of a regular expression, but aren’t interested in retrieving the group’s contents. You can make this fact explicit by using a non-capturing group: `(?:...)`, where you can replace the `...` with any other regular expression. ``` >>> m = re.match("([abc])+", "abc") >>> m.groups() ('c',) >>> m = re.match("(?:[abc])+", "abc") >>> m.groups() () ``` Except for the fact that you can’t retrieve the contents of what the group matched, a non-capturing group behaves exactly the same as a capturing group; you can put anything inside it, repeat it with a repetition metacharacter such as `*`, and nest it within other groups (capturing or non-capturing). `(?:...)` is particularly useful when modifying an existing pattern, since you can add new groups without changing how all the other groups are numbered. It should be mentioned that there’s no performance difference in searching between capturing and non-capturing groups; neither form is any faster than the other. A more significant feature is named groups: instead of referring to them by numbers, groups can be referenced by a name. The syntax for a named group is one of the Python-specific extensions: `(?P<name>...)`. *name* is, obviously, the name of the group. Named groups behave exactly like capturing groups, and additionally associate a name with a group. The [match object](../library/re#match-objects) methods that deal with capturing groups all accept either integers that refer to the group by number or strings that contain the desired group’s name. Named groups are still given numbers, so you can retrieve information about a group in two ways: ``` >>> p = re.compile(r'(?P<word>\b\w+\b)') >>> m = p.search( '(((( Lots of punctuation )))' ) >>> m.group('word') 'Lots' >>> m.group(1) 'Lots' ``` Additionally, you can retrieve named groups as a dictionary with [`groupdict()`](../library/re#re.Match.groupdict "re.Match.groupdict"): ``` >>> m = re.match(r'(?P<first>\w+) (?P<last>\w+)', 'Jane Doe') >>> m.groupdict() {'first': 'Jane', 'last': 'Doe'} ``` Named groups are handy because they let you use easily-remembered names, instead of having to remember numbers. Here’s an example RE from the [`imaplib`](../library/imaplib#module-imaplib "imaplib: IMAP4 protocol client (requires sockets).") module: ``` InternalDate = re.compile(r'INTERNALDATE "' r'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-' r'(?P<year>[0-9][0-9][0-9][0-9])' r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])' r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])' r'"') ``` It’s obviously much easier to retrieve `m.group('zonem')`, instead of having to remember to retrieve group 9. The syntax for backreferences in an expression such as `(...)\1` refers to the number of the group. There’s naturally a variant that uses the group name instead of the number. This is another Python extension: `(?P=name)` indicates that the contents of the group called *name* should again be matched at the current point. The regular expression for finding doubled words, `\b(\w+)\s+\1\b` can also be written as `\b(?P<word>\w+)\s+(?P=word)\b`: ``` >>> p = re.compile(r'\b(?P<word>\w+)\s+(?P=word)\b') >>> p.search('Paris in the the spring').group() 'the the' ``` ### Lookahead Assertions Another zero-width assertion is the lookahead assertion. Lookahead assertions are available in both positive and negative form, and look like this: `(?=...)` Positive lookahead assertion. This succeeds if the contained regular expression, represented here by `...`, successfully matches at the current location, and fails otherwise. But, once the contained expression has been tried, the matching engine doesn’t advance at all; the rest of the pattern is tried right where the assertion started. `(?!...)` Negative lookahead assertion. This is the opposite of the positive assertion; it succeeds if the contained expression *doesn’t* match at the current position in the string. To make this concrete, let’s look at a case where a lookahead is useful. Consider a simple pattern to match a filename and split it apart into a base name and an extension, separated by a `.`. For example, in `news.rc`, `news` is the base name, and `rc` is the filename’s extension. The pattern to match this is quite simple: `.*[.].*$` Notice that the `.` needs to be treated specially because it’s a metacharacter, so it’s inside a character class to only match that specific character. Also notice the trailing `$`; this is added to ensure that all the rest of the string must be included in the extension. This regular expression matches `foo.bar` and `autoexec.bat` and `sendmail.cf` and `printers.conf`. Now, consider complicating the problem a bit; what if you want to match filenames where the extension is not `bat`? Some incorrect attempts: `.*[.][^b].*$` The first attempt above tries to exclude `bat` by requiring that the first character of the extension is not a `b`. This is wrong, because the pattern also doesn’t match `foo.bar`. `.*[.]([^b]..|.[^a].|..[^t])$` The expression gets messier when you try to patch up the first solution by requiring one of the following cases to match: the first character of the extension isn’t `b`; the second character isn’t `a`; or the third character isn’t `t`. This accepts `foo.bar` and rejects `autoexec.bat`, but it requires a three-letter extension and won’t accept a filename with a two-letter extension such as `sendmail.cf`. We’ll complicate the pattern again in an effort to fix it. `.*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$` In the third attempt, the second and third letters are all made optional in order to allow matching extensions shorter than three characters, such as `sendmail.cf`. The pattern’s getting really complicated now, which makes it hard to read and understand. Worse, if the problem changes and you want to exclude both `bat` and `exe` as extensions, the pattern would get even more complicated and confusing. A negative lookahead cuts through all this confusion: `.*[.](?!bat$)[^.]*$` The negative lookahead means: if the expression `bat` doesn’t match at this point, try the rest of the pattern; if `bat$` does match, the whole pattern will fail. The trailing `$` is required to ensure that something like `sample.batch`, where the extension only starts with `bat`, will be allowed. The `[^.]*` makes sure that the pattern works when there are multiple dots in the filename. Excluding another filename extension is now easy; simply add it as an alternative inside the assertion. The following pattern excludes filenames that end in either `bat` or `exe`: `.*[.](?!bat$|exe$)[^.]*$` Modifying Strings ----------------- Up to this point, we’ve simply performed searches against a static string. Regular expressions are also commonly used to modify strings in various ways, using the following pattern methods: | Method/Attribute | Purpose | | --- | --- | | `split()` | Split the string into a list, splitting it wherever the RE matches | | `sub()` | Find all substrings where the RE matches, and replace them with a different string | | `subn()` | Does the same thing as `sub()`, but returns the new string and the number of replacements | ### Splitting Strings The [`split()`](../library/re#re.Pattern.split "re.Pattern.split") method of a pattern splits a string apart wherever the RE matches, returning a list of the pieces. It’s similar to the [`split()`](../library/stdtypes#str.split "str.split") method of strings but provides much more generality in the delimiters that you can split by; string `split()` only supports splitting by whitespace or by a fixed string. As you’d expect, there’s a module-level [`re.split()`](../library/re#re.split "re.split") function, too. `.split(string[, maxsplit=0])` Split *string* by the matches of the regular expression. If capturing parentheses are used in the RE, then their contents will also be returned as part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit* splits are performed. You can limit the number of splits made, by passing a value for *maxsplit*. When *maxsplit* is nonzero, at most *maxsplit* splits will be made, and the remainder of the string is returned as the final element of the list. In the following example, the delimiter is any sequence of non-alphanumeric characters. ``` >>> p = re.compile(r'\W+') >>> p.split('This is a test, short and sweet, of split().') ['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', 'split', ''] >>> p.split('This is a test, short and sweet, of split().', 3) ['This', 'is', 'a', 'test, short and sweet, of split().'] ``` Sometimes you’re not only interested in what the text between delimiters is, but also need to know what the delimiter was. If capturing parentheses are used in the RE, then their values are also returned as part of the list. Compare the following calls: ``` >>> p = re.compile(r'\W+') >>> p2 = re.compile(r'(\W+)') >>> p.split('This... is a test.') ['This', 'is', 'a', 'test', ''] >>> p2.split('This... is a test.') ['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', ''] ``` The module-level function [`re.split()`](../library/re#re.split "re.split") adds the RE to be used as the first argument, but is otherwise the same. ``` >>> re.split(r'[\W]+', 'Words, words, words.') ['Words', 'words', 'words', ''] >>> re.split(r'([\W]+)', 'Words, words, words.') ['Words', ', ', 'words', ', ', 'words', '.', ''] >>> re.split(r'[\W]+', 'Words, words, words.', 1) ['Words', 'words, words.'] ``` ### Search and Replace Another common task is to find all the matches for a pattern, and replace them with a different string. The [`sub()`](../library/re#re.Pattern.sub "re.Pattern.sub") method takes a replacement value, which can be either a string or a function, and the string to be processed. `.sub(replacement, string[, count=0])` Returns the string obtained by replacing the leftmost non-overlapping occurrences of the RE in *string* by the replacement *replacement*. If the pattern isn’t found, *string* is returned unchanged. The optional argument *count* is the maximum number of pattern occurrences to be replaced; *count* must be a non-negative integer. The default value of 0 means to replace all occurrences. Here’s a simple example of using the [`sub()`](../library/re#re.Pattern.sub "re.Pattern.sub") method. It replaces colour names with the word `colour`: ``` >>> p = re.compile('(blue|white|red)') >>> p.sub('colour', 'blue socks and red shoes') 'colour socks and colour shoes' >>> p.sub('colour', 'blue socks and red shoes', count=1) 'colour socks and red shoes' ``` The [`subn()`](../library/re#re.Pattern.subn "re.Pattern.subn") method does the same work, but returns a 2-tuple containing the new string value and the number of replacements that were performed: ``` >>> p = re.compile('(blue|white|red)') >>> p.subn('colour', 'blue socks and red shoes') ('colour socks and colour shoes', 2) >>> p.subn('colour', 'no colours at all') ('no colours at all', 0) ``` Empty matches are replaced only when they’re not adjacent to a previous empty match. ``` >>> p = re.compile('x*') >>> p.sub('-', 'abxd') '-a-b--d-' ``` If *replacement* is a string, any backslash escapes in it are processed. That is, `\n` is converted to a single newline character, `\r` is converted to a carriage return, and so forth. Unknown escapes such as `\&` are left alone. Backreferences, such as `\6`, are replaced with the substring matched by the corresponding group in the RE. This lets you incorporate portions of the original text in the resulting replacement string. This example matches the word `section` followed by a string enclosed in `{`, `}`, and changes `section` to `subsection`: ``` >>> p = re.compile('section{ ( [^}]* ) }', re.VERBOSE) >>> p.sub(r'subsection{\1}','section{First} section{second}') 'subsection{First} subsection{second}' ``` There’s also a syntax for referring to named groups as defined by the `(?P<name>...)` syntax. `\g<name>` will use the substring matched by the group named `name`, and `\g<number>` uses the corresponding group number. `\g<2>` is therefore equivalent to `\2`, but isn’t ambiguous in a replacement string such as `\g<2>0`. (`\20` would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character `'0'`.) The following substitutions are all equivalent, but use all three variations of the replacement string. ``` >>> p = re.compile('section{ (?P<name> [^}]* ) }', re.VERBOSE) >>> p.sub(r'subsection{\1}','section{First}') 'subsection{First}' >>> p.sub(r'subsection{\g<1>}','section{First}') 'subsection{First}' >>> p.sub(r'subsection{\g<name>}','section{First}') 'subsection{First}' ``` *replacement* can also be a function, which gives you even more control. If *replacement* is a function, the function is called for every non-overlapping occurrence of *pattern*. On each call, the function is passed a [match object](../library/re#match-objects) argument for the match and can use this information to compute the desired replacement string and return it. In the following example, the replacement function translates decimals into hexadecimal: ``` >>> def hexrepl(match): ... "Return the hex string for a decimal number" ... value = int(match.group()) ... return hex(value) ... >>> p = re.compile(r'\d+') >>> p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.') 'Call 0xffd2 for printing, 0xc000 for user code.' ``` When using the module-level [`re.sub()`](../library/re#re.sub "re.sub") function, the pattern is passed as the first argument. The pattern may be provided as an object or as a string; if you need to specify regular expression flags, you must either use a pattern object as the first parameter, or use embedded modifiers in the pattern string, e.g. `sub("(?i)b+", "x", "bbbb BBBB")` returns `'x x'`. Common Problems --------------- Regular expressions are a powerful tool for some applications, but in some ways their behaviour isn’t intuitive and at times they don’t behave the way you may expect them to. This section will point out some of the most common pitfalls. ### Use String Methods Sometimes using the [`re`](../library/re#module-re "re: Regular expression operations.") module is a mistake. If you’re matching a fixed string, or a single character class, and you’re not using any [`re`](../library/re#module-re "re: Regular expression operations.") features such as the [`IGNORECASE`](../library/re#re.IGNORECASE "re.IGNORECASE") flag, then the full power of regular expressions may not be required. Strings have several methods for performing operations with fixed strings and they’re usually much faster, because the implementation is a single small C loop that’s been optimized for the purpose, instead of the large, more generalized regular expression engine. One example might be replacing a single fixed string with another one; for example, you might replace `word` with `deed`. [`re.sub()`](../library/re#re.sub "re.sub") seems like the function to use for this, but consider the [`replace()`](../library/stdtypes#str.replace "str.replace") method. Note that `replace()` will also replace `word` inside words, turning `swordfish` into `sdeedfish`, but the naive RE `word` would have done that, too. (To avoid performing the substitution on parts of words, the pattern would have to be `\bword\b`, in order to require that `word` have a word boundary on either side. This takes the job beyond `replace()`’s abilities.) Another common task is deleting every occurrence of a single character from a string or replacing it with another single character. You might do this with something like `re.sub('\n', ' ', S)`, but [`translate()`](../library/stdtypes#str.translate "str.translate") is capable of doing both tasks and will be faster than any regular expression operation can be. In short, before turning to the [`re`](../library/re#module-re "re: Regular expression operations.") module, consider whether your problem can be solved with a faster and simpler string method. ### match() versus search() The [`match()`](../library/re#re.match "re.match") function only checks if the RE matches at the beginning of the string while [`search()`](../library/re#re.search "re.search") will scan forward through the string for a match. It’s important to keep this distinction in mind. Remember, `match()` will only report a successful match which will start at 0; if the match wouldn’t start at zero, `match()` will *not* report it. ``` >>> print(re.match('super', 'superstition').span()) (0, 5) >>> print(re.match('super', 'insuperable')) None ``` On the other hand, [`search()`](../library/re#re.search "re.search") will scan forward through the string, reporting the first match it finds. ``` >>> print(re.search('super', 'superstition').span()) (0, 5) >>> print(re.search('super', 'insuperable').span()) (2, 7) ``` Sometimes you’ll be tempted to keep using [`re.match()`](../library/re#re.match "re.match"), and just add `.*` to the front of your RE. Resist this temptation and use [`re.search()`](../library/re#re.search "re.search") instead. The regular expression compiler does some analysis of REs in order to speed up the process of looking for a match. One such analysis figures out what the first character of a match must be; for example, a pattern starting with `Crow` must match starting with a `'C'`. The analysis lets the engine quickly scan through the string looking for the starting character, only trying the full match if a `'C'` is found. Adding `.*` defeats this optimization, requiring scanning to the end of the string and then backtracking to find a match for the rest of the RE. Use [`re.search()`](../library/re#re.search "re.search") instead. ### Greedy versus Non-Greedy When repeating a regular expression, as in `a*`, the resulting action is to consume as much of the pattern as possible. This fact often bites you when you’re trying to match a pair of balanced delimiters, such as the angle brackets surrounding an HTML tag. The naive pattern for matching a single HTML tag doesn’t work because of the greedy nature of `.*`. ``` >>> s = '<html><head><title>Title</title>' >>> len(s) 32 >>> print(re.match('<.*>', s).span()) (0, 32) >>> print(re.match('<.*>', s).group()) <html><head><title>Title</title> ``` The RE matches the `'<'` in `'<html>'`, and the `.*` consumes the rest of the string. There’s still more left in the RE, though, and the `>` can’t match at the end of the string, so the regular expression engine has to backtrack character by character until it finds a match for the `>`. The final match extends from the `'<'` in `'<html>'` to the `'>'` in `'</title>'`, which isn’t what you want. In this case, the solution is to use the non-greedy qualifiers `*?`, `+?`, `??`, or `{m,n}?`, which match as *little* text as possible. In the above example, the `'>'` is tried immediately after the first `'<'` matches, and when it fails, the engine advances a character at a time, retrying the `'>'` at every step. This produces just the right result: ``` >>> print(re.match('<.*?>', s).group()) <html> ``` (Note that parsing HTML or XML with regular expressions is painful. Quick-and-dirty patterns will handle common cases, but HTML and XML have special cases that will break the obvious regular expression; by the time you’ve written a regular expression that handles all of the possible cases, the patterns will be *very* complicated. Use an HTML or XML parser module for such tasks.) ### Using re.VERBOSE By now you’ve probably noticed that regular expressions are a very compact notation, but they’re not terribly readable. REs of moderate complexity can become lengthy collections of backslashes, parentheses, and metacharacters, making them difficult to read and understand. For such REs, specifying the [`re.VERBOSE`](../library/re#re.VERBOSE "re.VERBOSE") flag when compiling the regular expression can be helpful, because it allows you to format the regular expression more clearly. The `re.VERBOSE` flag has several effects. Whitespace in the regular expression that *isn’t* inside a character class is ignored. This means that an expression such as `dog | cat` is equivalent to the less readable `dog|cat`, but `[a b]` will still match the characters `'a'`, `'b'`, or a space. In addition, you can also put comments inside a RE; comments extend from a `#` character to the next newline. When used with triple-quoted strings, this enables REs to be formatted more neatly: ``` pat = re.compile(r""" \s* # Skip leading whitespace (?P<header>[^:]+) # Header name \s* : # Whitespace, and a colon (?P<value>.*?) # The header's value -- *? used to # lose the following trailing whitespace \s*$ # Trailing whitespace to end-of-line """, re.VERBOSE) ``` This is far more readable than: ``` pat = re.compile(r"\s*(?P<header>[^:]+)\s*:(?P<value>.*?)\s*$") ``` Feedback -------- Regular expressions are a complicated topic. Did this document help you understand them? Were there parts that were unclear, or Problems you encountered that weren’t covered here? If so, please send suggestions for improvements to the author. The most complete book on regular expressions is almost certainly Jeffrey Friedl’s Mastering Regular Expressions, published by O’Reilly. Unfortunately, it exclusively concentrates on Perl and Java’s flavours of regular expressions, and doesn’t contain any Python material at all, so it won’t be useful as a reference for programming in Python. (The first edition covered Python’s now-removed `regex` module, which won’t help you much.) Consider checking it out from your library.
programming_docs
python Curses Programming with Python Curses Programming with Python ============================== Author A.M. Kuchling, Eric S. Raymond Release 2.04 Abstract This document describes how to use the [`curses`](../library/curses#module-curses "curses: An interface to the curses library, providing portable terminal handling. (Unix)") extension module to control text-mode displays. What is curses? --------------- The curses library supplies a terminal-independent screen-painting and keyboard-handling facility for text-based terminals; such terminals include VT100s, the Linux console, and the simulated terminal provided by various programs. Display terminals support various control codes to perform common operations such as moving the cursor, scrolling the screen, and erasing areas. Different terminals use widely differing codes, and often have their own minor quirks. In a world of graphical displays, one might ask “why bother”? It’s true that character-cell display terminals are an obsolete technology, but there are niches in which being able to do fancy things with them are still valuable. One niche is on small-footprint or embedded Unixes that don’t run an X server. Another is tools such as OS installers and kernel configurators that may have to run before any graphical support is available. The curses library provides fairly basic functionality, providing the programmer with an abstraction of a display containing multiple non-overlapping windows of text. The contents of a window can be changed in various ways—adding text, erasing it, changing its appearance—and the curses library will figure out what control codes need to be sent to the terminal to produce the right output. curses doesn’t provide many user-interface concepts such as buttons, checkboxes, or dialogs; if you need such features, consider a user interface library such as [Urwid](https://pypi.org/project/urwid/). The curses library was originally written for BSD Unix; the later System V versions of Unix from AT&T added many enhancements and new functions. BSD curses is no longer maintained, having been replaced by ncurses, which is an open-source implementation of the AT&T interface. If you’re using an open-source Unix such as Linux or FreeBSD, your system almost certainly uses ncurses. Since most current commercial Unix versions are based on System V code, all the functions described here will probably be available. The older versions of curses carried by some proprietary Unixes may not support everything, though. The Windows version of Python doesn’t include the [`curses`](../library/curses#module-curses "curses: An interface to the curses library, providing portable terminal handling. (Unix)") module. A ported version called [UniCurses](https://pypi.org/project/UniCurses) is available. ### The Python curses module The Python module is a fairly simple wrapper over the C functions provided by curses; if you’re already familiar with curses programming in C, it’s really easy to transfer that knowledge to Python. The biggest difference is that the Python interface makes things simpler by merging different C functions such as `addstr()`, `mvaddstr()`, and `mvwaddstr()` into a single [`addstr()`](../library/curses#curses.window.addstr "curses.window.addstr") method. You’ll see this covered in more detail later. This HOWTO is an introduction to writing text-mode programs with curses and Python. It doesn’t attempt to be a complete guide to the curses API; for that, see the Python library guide’s section on ncurses, and the C manual pages for ncurses. It will, however, give you the basic ideas. Starting and ending a curses application ---------------------------------------- Before doing anything, curses must be initialized. This is done by calling the [`initscr()`](../library/curses#curses.initscr "curses.initscr") function, which will determine the terminal type, send any required setup codes to the terminal, and create various internal data structures. If successful, `initscr()` returns a window object representing the entire screen; this is usually called `stdscr` after the name of the corresponding C variable. ``` import curses stdscr = curses.initscr() ``` Usually curses applications turn off automatic echoing of keys to the screen, in order to be able to read keys and only display them under certain circumstances. This requires calling the [`noecho()`](../library/curses#curses.noecho "curses.noecho") function. ``` curses.noecho() ``` Applications will also commonly need to react to keys instantly, without requiring the Enter key to be pressed; this is called cbreak mode, as opposed to the usual buffered input mode. ``` curses.cbreak() ``` Terminals usually return special keys, such as the cursor keys or navigation keys such as Page Up and Home, as a multibyte escape sequence. While you could write your application to expect such sequences and process them accordingly, curses can do it for you, returning a special value such as `curses.KEY_LEFT`. To get curses to do the job, you’ll have to enable keypad mode. ``` stdscr.keypad(True) ``` Terminating a curses application is much easier than starting one. You’ll need to call: ``` curses.nocbreak() stdscr.keypad(False) curses.echo() ``` to reverse the curses-friendly terminal settings. Then call the [`endwin()`](../library/curses#curses.endwin "curses.endwin") function to restore the terminal to its original operating mode. ``` curses.endwin() ``` A common problem when debugging a curses application is to get your terminal messed up when the application dies without restoring the terminal to its previous state. In Python this commonly happens when your code is buggy and raises an uncaught exception. Keys are no longer echoed to the screen when you type them, for example, which makes using the shell difficult. In Python you can avoid these complications and make debugging much easier by importing the [`curses.wrapper()`](../library/curses#curses.wrapper "curses.wrapper") function and using it like this: ``` from curses import wrapper def main(stdscr): # Clear screen stdscr.clear() # This raises ZeroDivisionError when i == 10. for i in range(0, 11): v = i-10 stdscr.addstr(i, 0, '10 divided by {} is {}'.format(v, 10/v)) stdscr.refresh() stdscr.getkey() wrapper(main) ``` The [`wrapper()`](../library/curses#curses.wrapper "curses.wrapper") function takes a callable object and does the initializations described above, also initializing colors if color support is present. `wrapper()` then runs your provided callable. Once the callable returns, `wrapper()` will restore the original state of the terminal. The callable is called inside a [`try`](../reference/compound_stmts#try)…[`except`](../reference/compound_stmts#except) that catches exceptions, restores the state of the terminal, and then re-raises the exception. Therefore your terminal won’t be left in a funny state on exception and you’ll be able to read the exception’s message and traceback. Windows and Pads ---------------- Windows are the basic abstraction in curses. A window object represents a rectangular area of the screen, and supports methods to display text, erase it, allow the user to input strings, and so forth. The `stdscr` object returned by the [`initscr()`](../library/curses#curses.initscr "curses.initscr") function is a window object that covers the entire screen. Many programs may need only this single window, but you might wish to divide the screen into smaller windows, in order to redraw or clear them separately. The [`newwin()`](../library/curses#curses.newwin "curses.newwin") function creates a new window of a given size, returning the new window object. ``` begin_x = 20; begin_y = 7 height = 5; width = 40 win = curses.newwin(height, width, begin_y, begin_x) ``` Note that the coordinate system used in curses is unusual. Coordinates are always passed in the order *y,x*, and the top-left corner of a window is coordinate (0,0). This breaks the normal convention for handling coordinates where the *x* coordinate comes first. This is an unfortunate difference from most other computer applications, but it’s been part of curses since it was first written, and it’s too late to change things now. Your application can determine the size of the screen by using the `curses.LINES` and `curses.COLS` variables to obtain the *y* and *x* sizes. Legal coordinates will then extend from `(0,0)` to `(curses.LINES - 1, curses.COLS - 1)`. When you call a method to display or erase text, the effect doesn’t immediately show up on the display. Instead you must call the [`refresh()`](../library/curses#curses.window.refresh "curses.window.refresh") method of window objects to update the screen. This is because curses was originally written with slow 300-baud terminal connections in mind; with these terminals, minimizing the time required to redraw the screen was very important. Instead curses accumulates changes to the screen and displays them in the most efficient manner when you call `refresh()`. For example, if your program displays some text in a window and then clears the window, there’s no need to send the original text because they’re never visible. In practice, explicitly telling curses to redraw a window doesn’t really complicate programming with curses much. Most programs go into a flurry of activity, and then pause waiting for a keypress or some other action on the part of the user. All you have to do is to be sure that the screen has been redrawn before pausing to wait for user input, by first calling `stdscr.refresh()` or the `refresh()` method of some other relevant window. A pad is a special case of a window; it can be larger than the actual display screen, and only a portion of the pad displayed at a time. Creating a pad requires the pad’s height and width, while refreshing a pad requires giving the coordinates of the on-screen area where a subsection of the pad will be displayed. ``` pad = curses.newpad(100, 100) # These loops fill the pad with letters; addch() is # explained in the next section for y in range(0, 99): for x in range(0, 99): pad.addch(y,x, ord('a') + (x*x+y*y) % 26) # Displays a section of the pad in the middle of the screen. # (0,0) : coordinate of upper-left corner of pad area to display. # (5,5) : coordinate of upper-left corner of window area to be filled # with pad content. # (20, 75) : coordinate of lower-right corner of window area to be # : filled with pad content. pad.refresh( 0,0, 5,5, 20,75) ``` The `refresh()` call displays a section of the pad in the rectangle extending from coordinate (5,5) to coordinate (20,75) on the screen; the upper left corner of the displayed section is coordinate (0,0) on the pad. Beyond that difference, pads are exactly like ordinary windows and support the same methods. If you have multiple windows and pads on screen there is a more efficient way to update the screen and prevent annoying screen flicker as each part of the screen gets updated. `refresh()` actually does two things: 1. Calls the [`noutrefresh()`](../library/curses#curses.window.noutrefresh "curses.window.noutrefresh") method of each window to update an underlying data structure representing the desired state of the screen. 2. Calls the function [`doupdate()`](../library/curses#curses.doupdate "curses.doupdate") function to change the physical screen to match the desired state recorded in the data structure. Instead you can call `noutrefresh()` on a number of windows to update the data structure, and then call `doupdate()` to update the screen. Displaying Text --------------- From a C programmer’s point of view, curses may sometimes look like a twisty maze of functions, all subtly different. For example, `addstr()` displays a string at the current cursor location in the `stdscr` window, while `mvaddstr()` moves to a given y,x coordinate first before displaying the string. `waddstr()` is just like `addstr()`, but allows specifying a window to use instead of using `stdscr` by default. `mvwaddstr()` allows specifying both a window and a coordinate. Fortunately the Python interface hides all these details. `stdscr` is a window object like any other, and methods such as [`addstr()`](../library/curses#curses.window.addstr "curses.window.addstr") accept multiple argument forms. Usually there are four different forms. | Form | Description | | --- | --- | | *str* or *ch* | Display the string *str* or character *ch* at the current position | | *str* or *ch*, *attr* | Display the string *str* or character *ch*, using attribute *attr* at the current position | | *y*, *x*, *str* or *ch* | Move to position *y,x* within the window, and display *str* or *ch* | | *y*, *x*, *str* or *ch*, *attr* | Move to position *y,x* within the window, and display *str* or *ch*, using attribute *attr* | Attributes allow displaying text in highlighted forms such as boldface, underline, reverse code, or in color. They’ll be explained in more detail in the next subsection. The [`addstr()`](../library/curses#curses.window.addstr "curses.window.addstr") method takes a Python string or bytestring as the value to be displayed. The contents of bytestrings are sent to the terminal as-is. Strings are encoded to bytes using the value of the window’s `encoding` attribute; this defaults to the default system encoding as returned by [`locale.getpreferredencoding()`](../library/locale#locale.getpreferredencoding "locale.getpreferredencoding"). The [`addch()`](../library/curses#curses.window.addch "curses.window.addch") methods take a character, which can be either a string of length 1, a bytestring of length 1, or an integer. Constants are provided for extension characters; these constants are integers greater than 255. For example, `ACS_PLMINUS` is a +/- symbol, and `ACS_ULCORNER` is the upper left corner of a box (handy for drawing borders). You can also use the appropriate Unicode character. Windows remember where the cursor was left after the last operation, so if you leave out the *y,x* coordinates, the string or character will be displayed wherever the last operation left off. You can also move the cursor with the `move(y,x)` method. Because some terminals always display a flashing cursor, you may want to ensure that the cursor is positioned in some location where it won’t be distracting; it can be confusing to have the cursor blinking at some apparently random location. If your application doesn’t need a blinking cursor at all, you can call `curs_set(False)` to make it invisible. For compatibility with older curses versions, there’s a `leaveok(bool)` function that’s a synonym for [`curs_set()`](../library/curses#curses.curs_set "curses.curs_set"). When *bool* is true, the curses library will attempt to suppress the flashing cursor, and you won’t need to worry about leaving it in odd locations. ### Attributes and Color Characters can be displayed in different ways. Status lines in a text-based application are commonly shown in reverse video, or a text viewer may need to highlight certain words. curses supports this by allowing you to specify an attribute for each cell on the screen. An attribute is an integer, each bit representing a different attribute. You can try to display text with multiple attribute bits set, but curses doesn’t guarantee that all the possible combinations are available, or that they’re all visually distinct. That depends on the ability of the terminal being used, so it’s safest to stick to the most commonly available attributes, listed here. | Attribute | Description | | --- | --- | | `A_BLINK` | Blinking text | | `A_BOLD` | Extra bright or bold text | | `A_DIM` | Half bright text | | `A_REVERSE` | Reverse-video text | | `A_STANDOUT` | The best highlighting mode available | | `A_UNDERLINE` | Underlined text | So, to display a reverse-video status line on the top line of the screen, you could code: ``` stdscr.addstr(0, 0, "Current mode: Typing mode", curses.A_REVERSE) stdscr.refresh() ``` The curses library also supports color on those terminals that provide it. The most common such terminal is probably the Linux console, followed by color xterms. To use color, you must call the [`start_color()`](../library/curses#curses.start_color "curses.start_color") function soon after calling [`initscr()`](../library/curses#curses.initscr "curses.initscr"), to initialize the default color set (the [`curses.wrapper()`](../library/curses#curses.wrapper "curses.wrapper") function does this automatically). Once that’s done, the [`has_colors()`](../library/curses#curses.has_colors "curses.has_colors") function returns TRUE if the terminal in use can actually display color. (Note: curses uses the American spelling ‘color’, instead of the Canadian/British spelling ‘colour’. If you’re used to the British spelling, you’ll have to resign yourself to misspelling it for the sake of these functions.) The curses library maintains a finite number of color pairs, containing a foreground (or text) color and a background color. You can get the attribute value corresponding to a color pair with the [`color_pair()`](../library/curses#curses.color_pair "curses.color_pair") function; this can be bitwise-OR’ed with other attributes such as `A_REVERSE`, but again, such combinations are not guaranteed to work on all terminals. An example, which displays a line of text using color pair 1: ``` stdscr.addstr("Pretty text", curses.color_pair(1)) stdscr.refresh() ``` As I said before, a color pair consists of a foreground and background color. The `init_pair(n, f, b)` function changes the definition of color pair *n*, to foreground color f and background color b. Color pair 0 is hard-wired to white on black, and cannot be changed. Colors are numbered, and `start_color()` initializes 8 basic colors when it activates color mode. They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white. The [`curses`](../library/curses#module-curses "curses: An interface to the curses library, providing portable terminal handling. (Unix)") module defines named constants for each of these colors: `curses.COLOR_BLACK`, `curses.COLOR_RED`, and so forth. Let’s put all this together. To change color 1 to red text on a white background, you would call: ``` curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE) ``` When you change a color pair, any text already displayed using that color pair will change to the new colors. You can also display new text in this color with: ``` stdscr.addstr(0,0, "RED ALERT!", curses.color_pair(1)) ``` Very fancy terminals can change the definitions of the actual colors to a given RGB value. This lets you change color 1, which is usually red, to purple or blue or any other color you like. Unfortunately, the Linux console doesn’t support this, so I’m unable to try it out, and can’t provide any examples. You can check if your terminal can do this by calling [`can_change_color()`](../library/curses#curses.can_change_color "curses.can_change_color"), which returns `True` if the capability is there. If you’re lucky enough to have such a talented terminal, consult your system’s man pages for more information. User Input ---------- The C curses library offers only very simple input mechanisms. Python’s [`curses`](../library/curses#module-curses "curses: An interface to the curses library, providing portable terminal handling. (Unix)") module adds a basic text-input widget. (Other libraries such as [Urwid](https://pypi.org/project/urwid/) have more extensive collections of widgets.) There are two methods for getting input from a window: * [`getch()`](../library/curses#curses.window.getch "curses.window.getch") refreshes the screen and then waits for the user to hit a key, displaying the key if [`echo()`](../library/curses#curses.echo "curses.echo") has been called earlier. You can optionally specify a coordinate to which the cursor should be moved before pausing. * [`getkey()`](../library/curses#curses.window.getkey "curses.window.getkey") does the same thing but converts the integer to a string. Individual characters are returned as 1-character strings, and special keys such as function keys return longer strings containing a key name such as `KEY_UP` or `^G`. It’s possible to not wait for the user using the [`nodelay()`](../library/curses#curses.window.nodelay "curses.window.nodelay") window method. After `nodelay(True)`, `getch()` and `getkey()` for the window become non-blocking. To signal that no input is ready, `getch()` returns `curses.ERR` (a value of -1) and `getkey()` raises an exception. There’s also a [`halfdelay()`](../library/curses#curses.halfdelay "curses.halfdelay") function, which can be used to (in effect) set a timer on each `getch()`; if no input becomes available within a specified delay (measured in tenths of a second), curses raises an exception. The `getch()` method returns an integer; if it’s between 0 and 255, it represents the ASCII code of the key pressed. Values greater than 255 are special keys such as Page Up, Home, or the cursor keys. You can compare the value returned to constants such as `curses.KEY_PPAGE`, `curses.KEY_HOME`, or `curses.KEY_LEFT`. The main loop of your program may look something like this: ``` while True: c = stdscr.getch() if c == ord('p'): PrintDocument() elif c == ord('q'): break # Exit the while loop elif c == curses.KEY_HOME: x = y = 0 ``` The [`curses.ascii`](../library/curses.ascii#module-curses.ascii "curses.ascii: Constants and set-membership functions for ASCII characters.") module supplies ASCII class membership functions that take either integer or 1-character string arguments; these may be useful in writing more readable tests for such loops. It also supplies conversion functions that take either integer or 1-character-string arguments and return the same type. For example, [`curses.ascii.ctrl()`](../library/curses.ascii#curses.ascii.ctrl "curses.ascii.ctrl") returns the control character corresponding to its argument. There’s also a method to retrieve an entire string, [`getstr()`](../library/curses#curses.window.getstr "curses.window.getstr"). It isn’t used very often, because its functionality is quite limited; the only editing keys available are the backspace key and the Enter key, which terminates the string. It can optionally be limited to a fixed number of characters. ``` curses.echo() # Enable echoing of characters # Get a 15-character string, with the cursor on the top line s = stdscr.getstr(0,0, 15) ``` The [`curses.textpad`](../library/curses#module-curses.textpad "curses.textpad: Emacs-like input editing in a curses window.") module supplies a text box that supports an Emacs-like set of keybindings. Various methods of the [`Textbox`](../library/curses#curses.textpad.Textbox "curses.textpad.Textbox") class support editing with input validation and gathering the edit results either with or without trailing spaces. Here’s an example: ``` import curses from curses.textpad import Textbox, rectangle def main(stdscr): stdscr.addstr(0, 0, "Enter IM message: (hit Ctrl-G to send)") editwin = curses.newwin(5,30, 2,1) rectangle(stdscr, 1,0, 1+5+1, 1+30+1) stdscr.refresh() box = Textbox(editwin) # Let the user edit until Ctrl-G is struck. box.edit() # Get resulting contents message = box.gather() ``` See the library documentation on [`curses.textpad`](../library/curses#module-curses.textpad "curses.textpad: Emacs-like input editing in a curses window.") for more details. For More Information -------------------- This HOWTO doesn’t cover some advanced topics, such as reading the contents of the screen or capturing mouse events from an xterm instance, but the Python library page for the [`curses`](../library/curses#module-curses "curses: An interface to the curses library, providing portable terminal handling. (Unix)") module is now reasonably complete. You should browse it next. If you’re in doubt about the detailed behavior of the curses functions, consult the manual pages for your curses implementation, whether it’s ncurses or a proprietary Unix vendor’s. The manual pages will document any quirks, and provide complete lists of all the functions, attributes, and `ACS_*` characters available to you. Because the curses API is so large, some functions aren’t supported in the Python interface. Often this isn’t because they’re difficult to implement, but because no one has needed them yet. Also, Python doesn’t yet support the menu library associated with ncurses. Patches adding support for these would be welcome; see [the Python Developer’s Guide](https://devguide.python.org/) to learn more about submitting patches to Python. * [Writing Programs with NCURSES](http://invisible-island.net/ncurses/ncurses-intro.html): a lengthy tutorial for C programmers. * [The ncurses man page](https://linux.die.net/man/3/ncurses) * [The ncurses FAQ](http://invisible-island.net/ncurses/ncurses.faq.html) * [“Use curses… don’t swear”](https://www.youtube.com/watch?v=eN1eZtjLEnU): video of a PyCon 2013 talk on controlling terminals using curses or Urwid. * [“Console Applications with Urwid”](http://www.pyvideo.org/video/1568/console-applications-with-urwid): video of a PyCon CA 2012 talk demonstrating some applications written using Urwid.
programming_docs
python Python HOWTOs Python HOWTOs ============= Python HOWTOs are documents that cover a single, specific topic, and attempt to cover it fairly completely. Modelled on the Linux Documentation Project’s HOWTO collection, this collection is an effort to foster documentation that’s more detailed than the Python Library Reference. Currently, the HOWTOs are: * [Porting Python 2 Code to Python 3](pyporting) * [Porting Extension Modules to Python 3](cporting) * [Curses Programming with Python](curses) * [Descriptor HowTo Guide](descriptor) * [Functional Programming HOWTO](functional) * [Logging HOWTO](logging) * [Logging Cookbook](logging-cookbook) * [Regular Expression HOWTO](regex) * [Socket Programming HOWTO](sockets) * [Sorting HOW TO](sorting) * [Unicode HOWTO](unicode) * [HOWTO Fetch Internet Resources Using The urllib Package](urllib2) * [Argparse Tutorial](argparse) * [An introduction to the ipaddress module](ipaddress) * [Argument Clinic How-To](clinic) * [Instrumenting CPython with DTrace and SystemTap](instrumentation) python Argparse Tutorial Argparse Tutorial ================= author Tshepang Lekhonkhobe This tutorial is intended to be a gentle introduction to [`argparse`](../library/argparse#module-argparse "argparse: Command-line option and argument parsing library."), the recommended command-line parsing module in the Python standard library. Note There are two other modules that fulfill the same task, namely [`getopt`](../library/getopt#module-getopt "getopt: Portable parser for command line options; support both short and long option names.") (an equivalent for `getopt()` from the C language) and the deprecated [`optparse`](../library/optparse#module-optparse "optparse: Command-line option parsing library. (deprecated)"). Note also that [`argparse`](../library/argparse#module-argparse "argparse: Command-line option and argument parsing library.") is based on [`optparse`](../library/optparse#module-optparse "optparse: Command-line option parsing library. (deprecated)"), and therefore very similar in terms of usage. Concepts -------- Let’s show the sort of functionality that we are going to explore in this introductory tutorial by making use of the **ls** command: ``` $ ls cpython devguide prog.py pypy rm-unused-function.patch $ ls pypy ctypes_configure demo dotviewer include lib_pypy lib-python ... $ ls -l total 20 drwxr-xr-x 19 wena wena 4096 Feb 18 18:51 cpython drwxr-xr-x 4 wena wena 4096 Feb 8 12:04 devguide -rwxr-xr-x 1 wena wena 535 Feb 19 00:05 prog.py drwxr-xr-x 14 wena wena 4096 Feb 7 00:59 pypy -rw-r--r-- 1 wena wena 741 Feb 18 01:01 rm-unused-function.patch $ ls --help Usage: ls [OPTION]... [FILE]... List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuvSUX nor --sort is specified. ... ``` A few concepts we can learn from the four commands: * The **ls** command is useful when run without any options at all. It defaults to displaying the contents of the current directory. * If we want beyond what it provides by default, we tell it a bit more. In this case, we want it to display a different directory, `pypy`. What we did is specify what is known as a positional argument. It’s named so because the program should know what to do with the value, solely based on where it appears on the command line. This concept is more relevant to a command like **cp**, whose most basic usage is `cp SRC DEST`. The first position is *what you want copied,* and the second position is *where you want it copied to*. * Now, say we want to change behaviour of the program. In our example, we display more info for each file instead of just showing the file names. The `-l` in that case is known as an optional argument. * That’s a snippet of the help text. It’s very useful in that you can come across a program you have never used before, and can figure out how it works simply by reading its help text. The basics ---------- Let us start with a very simple example which does (almost) nothing: ``` import argparse parser = argparse.ArgumentParser() parser.parse_args() ``` Following is a result of running the code: ``` $ python3 prog.py $ python3 prog.py --help usage: prog.py [-h] optional arguments: -h, --help show this help message and exit $ python3 prog.py --verbose usage: prog.py [-h] prog.py: error: unrecognized arguments: --verbose $ python3 prog.py foo usage: prog.py [-h] prog.py: error: unrecognized arguments: foo ``` Here is what is happening: * Running the script without any options results in nothing displayed to stdout. Not so useful. * The second one starts to display the usefulness of the [`argparse`](../library/argparse#module-argparse "argparse: Command-line option and argument parsing library.") module. We have done almost nothing, but already we get a nice help message. * The `--help` option, which can also be shortened to `-h`, is the only option we get for free (i.e. no need to specify it). Specifying anything else results in an error. But even then, we do get a useful usage message, also for free. Introducing Positional arguments -------------------------------- An example: ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("echo") args = parser.parse_args() print(args.echo) ``` And running the code: ``` $ python3 prog.py usage: prog.py [-h] echo prog.py: error: the following arguments are required: echo $ python3 prog.py --help usage: prog.py [-h] echo positional arguments: echo optional arguments: -h, --help show this help message and exit $ python3 prog.py foo foo ``` Here is what’s happening: * We’ve added the `add_argument()` method, which is what we use to specify which command-line options the program is willing to accept. In this case, I’ve named it `echo` so that it’s in line with its function. * Calling our program now requires us to specify an option. * The `parse_args()` method actually returns some data from the options specified, in this case, `echo`. * The variable is some form of ‘magic’ that [`argparse`](../library/argparse#module-argparse "argparse: Command-line option and argument parsing library.") performs for free (i.e. no need to specify which variable that value is stored in). You will also notice that its name matches the string argument given to the method, `echo`. Note however that, although the help display looks nice and all, it currently is not as helpful as it can be. For example we see that we got `echo` as a positional argument, but we don’t know what it does, other than by guessing or by reading the source code. So, let’s make it a bit more useful: ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("echo", help="echo the string you use here") args = parser.parse_args() print(args.echo) ``` And we get: ``` $ python3 prog.py -h usage: prog.py [-h] echo positional arguments: echo echo the string you use here optional arguments: -h, --help show this help message and exit ``` Now, how about doing something even more useful: ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("square", help="display a square of a given number") args = parser.parse_args() print(args.square**2) ``` Following is a result of running the code: ``` $ python3 prog.py 4 Traceback (most recent call last): File "prog.py", line 5, in <module> print(args.square**2) TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int' ``` That didn’t go so well. That’s because [`argparse`](../library/argparse#module-argparse "argparse: Command-line option and argument parsing library.") treats the options we give it as strings, unless we tell it otherwise. So, let’s tell [`argparse`](../library/argparse#module-argparse "argparse: Command-line option and argument parsing library.") to treat that input as an integer: ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("square", help="display a square of a given number", type=int) args = parser.parse_args() print(args.square**2) ``` Following is a result of running the code: ``` $ python3 prog.py 4 16 $ python3 prog.py four usage: prog.py [-h] square prog.py: error: argument square: invalid int value: 'four' ``` That went well. The program now even helpfully quits on bad illegal input before proceeding. Introducing Optional arguments ------------------------------ So far we have been playing with positional arguments. Let us have a look on how to add optional ones: ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("--verbosity", help="increase output verbosity") args = parser.parse_args() if args.verbosity: print("verbosity turned on") ``` And the output: ``` $ python3 prog.py --verbosity 1 verbosity turned on $ python3 prog.py $ python3 prog.py --help usage: prog.py [-h] [--verbosity VERBOSITY] optional arguments: -h, --help show this help message and exit --verbosity VERBOSITY increase output verbosity $ python3 prog.py --verbosity usage: prog.py [-h] [--verbosity VERBOSITY] prog.py: error: argument --verbosity: expected one argument ``` Here is what is happening: * The program is written so as to display something when `--verbosity` is specified and display nothing when not. * To show that the option is actually optional, there is no error when running the program without it. Note that by default, if an optional argument isn’t used, the relevant variable, in this case `args.verbosity`, is given `None` as a value, which is the reason it fails the truth test of the [`if`](../reference/compound_stmts#if) statement. * The help message is a bit different. * When using the `--verbosity` option, one must also specify some value, any value. The above example accepts arbitrary integer values for `--verbosity`, but for our simple program, only two values are actually useful, `True` or `False`. Let’s modify the code accordingly: ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() if args.verbose: print("verbosity turned on") ``` And the output: ``` $ python3 prog.py --verbose verbosity turned on $ python3 prog.py --verbose 1 usage: prog.py [-h] [--verbose] prog.py: error: unrecognized arguments: 1 $ python3 prog.py --help usage: prog.py [-h] [--verbose] optional arguments: -h, --help show this help message and exit --verbose increase output verbosity ``` Here is what is happening: * The option is now more of a flag than something that requires a value. We even changed the name of the option to match that idea. Note that we now specify a new keyword, `action`, and give it the value `"store_true"`. This means that, if the option is specified, assign the value `True` to `args.verbose`. Not specifying it implies `False`. * It complains when you specify a value, in true spirit of what flags actually are. * Notice the different help text. ### Short options If you are familiar with command line usage, you will notice that I haven’t yet touched on the topic of short versions of the options. It’s quite simple: ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() if args.verbose: print("verbosity turned on") ``` And here goes: ``` $ python3 prog.py -v verbosity turned on $ python3 prog.py --help usage: prog.py [-h] [-v] optional arguments: -h, --help show this help message and exit -v, --verbose increase output verbosity ``` Note that the new ability is also reflected in the help text. Combining Positional and Optional arguments ------------------------------------------- Our program keeps growing in complexity: ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("square", type=int, help="display a square of a given number") parser.add_argument("-v", "--verbose", action="store_true", help="increase output verbosity") args = parser.parse_args() answer = args.square**2 if args.verbose: print("the square of {} equals {}".format(args.square, answer)) else: print(answer) ``` And now the output: ``` $ python3 prog.py usage: prog.py [-h] [-v] square prog.py: error: the following arguments are required: square $ python3 prog.py 4 16 $ python3 prog.py 4 --verbose the square of 4 equals 16 $ python3 prog.py --verbose 4 the square of 4 equals 16 ``` * We’ve brought back a positional argument, hence the complaint. * Note that the order does not matter. How about we give this program of ours back the ability to have multiple verbosity values, and actually get to use them: ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("square", type=int, help="display a square of a given number") parser.add_argument("-v", "--verbosity", type=int, help="increase output verbosity") args = parser.parse_args() answer = args.square**2 if args.verbosity == 2: print("the square of {} equals {}".format(args.square, answer)) elif args.verbosity == 1: print("{}^2 == {}".format(args.square, answer)) else: print(answer) ``` And the output: ``` $ python3 prog.py 4 16 $ python3 prog.py 4 -v usage: prog.py [-h] [-v VERBOSITY] square prog.py: error: argument -v/--verbosity: expected one argument $ python3 prog.py 4 -v 1 4^2 == 16 $ python3 prog.py 4 -v 2 the square of 4 equals 16 $ python3 prog.py 4 -v 3 16 ``` These all look good except the last one, which exposes a bug in our program. Let’s fix it by restricting the values the `--verbosity` option can accept: ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("square", type=int, help="display a square of a given number") parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2], help="increase output verbosity") args = parser.parse_args() answer = args.square**2 if args.verbosity == 2: print("the square of {} equals {}".format(args.square, answer)) elif args.verbosity == 1: print("{}^2 == {}".format(args.square, answer)) else: print(answer) ``` And the output: ``` $ python3 prog.py 4 -v 3 usage: prog.py [-h] [-v {0,1,2}] square prog.py: error: argument -v/--verbosity: invalid choice: 3 (choose from 0, 1, 2) $ python3 prog.py 4 -h usage: prog.py [-h] [-v {0,1,2}] square positional arguments: square display a square of a given number optional arguments: -h, --help show this help message and exit -v {0,1,2}, --verbosity {0,1,2} increase output verbosity ``` Note that the change also reflects both in the error message as well as the help string. Now, let’s use a different approach of playing with verbosity, which is pretty common. It also matches the way the CPython executable handles its own verbosity argument (check the output of `python --help`): ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("square", type=int, help="display the square of a given number") parser.add_argument("-v", "--verbosity", action="count", help="increase output verbosity") args = parser.parse_args() answer = args.square**2 if args.verbosity == 2: print("the square of {} equals {}".format(args.square, answer)) elif args.verbosity == 1: print("{}^2 == {}".format(args.square, answer)) else: print(answer) ``` We have introduced another action, “count”, to count the number of occurrences of a specific optional arguments: ``` $ python3 prog.py 4 16 $ python3 prog.py 4 -v 4^2 == 16 $ python3 prog.py 4 -vv the square of 4 equals 16 $ python3 prog.py 4 --verbosity --verbosity the square of 4 equals 16 $ python3 prog.py 4 -v 1 usage: prog.py [-h] [-v] square prog.py: error: unrecognized arguments: 1 $ python3 prog.py 4 -h usage: prog.py [-h] [-v] square positional arguments: square display a square of a given number optional arguments: -h, --help show this help message and exit -v, --verbosity increase output verbosity $ python3 prog.py 4 -vvv 16 ``` * Yes, it’s now more of a flag (similar to `action="store_true"`) in the previous version of our script. That should explain the complaint. * It also behaves similar to “store\_true” action. * Now here’s a demonstration of what the “count” action gives. You’ve probably seen this sort of usage before. * And if you don’t specify the `-v` flag, that flag is considered to have `None` value. * As should be expected, specifying the long form of the flag, we should get the same output. * Sadly, our help output isn’t very informative on the new ability our script has acquired, but that can always be fixed by improving the documentation for our script (e.g. via the `help` keyword argument). * That last output exposes a bug in our program. Let’s fix: ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("square", type=int, help="display a square of a given number") parser.add_argument("-v", "--verbosity", action="count", help="increase output verbosity") args = parser.parse_args() answer = args.square**2 # bugfix: replace == with >= if args.verbosity >= 2: print("the square of {} equals {}".format(args.square, answer)) elif args.verbosity >= 1: print("{}^2 == {}".format(args.square, answer)) else: print(answer) ``` And this is what it gives: ``` $ python3 prog.py 4 -vvv the square of 4 equals 16 $ python3 prog.py 4 -vvvv the square of 4 equals 16 $ python3 prog.py 4 Traceback (most recent call last): File "prog.py", line 11, in <module> if args.verbosity >= 2: TypeError: '>=' not supported between instances of 'NoneType' and 'int' ``` * First output went well, and fixes the bug we had before. That is, we want any value >= 2 to be as verbose as possible. * Third output not so good. Let’s fix that bug: ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("square", type=int, help="display a square of a given number") parser.add_argument("-v", "--verbosity", action="count", default=0, help="increase output verbosity") args = parser.parse_args() answer = args.square**2 if args.verbosity >= 2: print("the square of {} equals {}".format(args.square, answer)) elif args.verbosity >= 1: print("{}^2 == {}".format(args.square, answer)) else: print(answer) ``` We’ve just introduced yet another keyword, `default`. We’ve set it to `0` in order to make it comparable to the other int values. Remember that by default, if an optional argument isn’t specified, it gets the `None` value, and that cannot be compared to an int value (hence the [`TypeError`](../library/exceptions#TypeError "TypeError") exception). And: ``` $ python3 prog.py 4 16 ``` You can go quite far just with what we’ve learned so far, and we have only scratched the surface. The [`argparse`](../library/argparse#module-argparse "argparse: Command-line option and argument parsing library.") module is very powerful, and we’ll explore a bit more of it before we end this tutorial. Getting a little more advanced ------------------------------ What if we wanted to expand our tiny program to perform other powers, not just squares: ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("x", type=int, help="the base") parser.add_argument("y", type=int, help="the exponent") parser.add_argument("-v", "--verbosity", action="count", default=0) args = parser.parse_args() answer = args.x**args.y if args.verbosity >= 2: print("{} to the power {} equals {}".format(args.x, args.y, answer)) elif args.verbosity >= 1: print("{}^{} == {}".format(args.x, args.y, answer)) else: print(answer) ``` Output: ``` $ python3 prog.py usage: prog.py [-h] [-v] x y prog.py: error: the following arguments are required: x, y $ python3 prog.py -h usage: prog.py [-h] [-v] x y positional arguments: x the base y the exponent optional arguments: -h, --help show this help message and exit -v, --verbosity $ python3 prog.py 4 2 -v 4^2 == 16 ``` Notice that so far we’ve been using verbosity level to *change* the text that gets displayed. The following example instead uses verbosity level to display *more* text instead: ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("x", type=int, help="the base") parser.add_argument("y", type=int, help="the exponent") parser.add_argument("-v", "--verbosity", action="count", default=0) args = parser.parse_args() answer = args.x**args.y if args.verbosity >= 2: print("Running '{}'".format(__file__)) if args.verbosity >= 1: print("{}^{} == ".format(args.x, args.y), end="") print(answer) ``` Output: ``` $ python3 prog.py 4 2 16 $ python3 prog.py 4 2 -v 4^2 == 16 $ python3 prog.py 4 2 -vv Running 'prog.py' 4^2 == 16 ``` ### Conflicting options So far, we have been working with two methods of an [`argparse.ArgumentParser`](../library/argparse#argparse.ArgumentParser "argparse.ArgumentParser") instance. Let’s introduce a third one, `add_mutually_exclusive_group()`. It allows for us to specify options that conflict with each other. Let’s also change the rest of the program so that the new functionality makes more sense: we’ll introduce the `--quiet` option, which will be the opposite of the `--verbose` one: ``` import argparse parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument("-v", "--verbose", action="store_true") group.add_argument("-q", "--quiet", action="store_true") parser.add_argument("x", type=int, help="the base") parser.add_argument("y", type=int, help="the exponent") args = parser.parse_args() answer = args.x**args.y if args.quiet: print(answer) elif args.verbose: print("{} to the power {} equals {}".format(args.x, args.y, answer)) else: print("{}^{} == {}".format(args.x, args.y, answer)) ``` Our program is now simpler, and we’ve lost some functionality for the sake of demonstration. Anyways, here’s the output: ``` $ python3 prog.py 4 2 4^2 == 16 $ python3 prog.py 4 2 -q 16 $ python3 prog.py 4 2 -v 4 to the power 2 equals 16 $ python3 prog.py 4 2 -vq usage: prog.py [-h] [-v | -q] x y prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose $ python3 prog.py 4 2 -v --quiet usage: prog.py [-h] [-v | -q] x y prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose ``` That should be easy to follow. I’ve added that last output so you can see the sort of flexibility you get, i.e. mixing long form options with short form ones. Before we conclude, you probably want to tell your users the main purpose of your program, just in case they don’t know: ``` import argparse parser = argparse.ArgumentParser(description="calculate X to the power of Y") group = parser.add_mutually_exclusive_group() group.add_argument("-v", "--verbose", action="store_true") group.add_argument("-q", "--quiet", action="store_true") parser.add_argument("x", type=int, help="the base") parser.add_argument("y", type=int, help="the exponent") args = parser.parse_args() answer = args.x**args.y if args.quiet: print(answer) elif args.verbose: print("{} to the power {} equals {}".format(args.x, args.y, answer)) else: print("{}^{} == {}".format(args.x, args.y, answer)) ``` Note that slight difference in the usage text. Note the `[-v | -q]`, which tells us that we can either use `-v` or `-q`, but not both at the same time: ``` $ python3 prog.py --help usage: prog.py [-h] [-v | -q] x y calculate X to the power of Y positional arguments: x the base y the exponent optional arguments: -h, --help show this help message and exit -v, --verbose -q, --quiet ``` Conclusion ---------- The [`argparse`](../library/argparse#module-argparse "argparse: Command-line option and argument parsing library.") module offers a lot more than shown here. Its docs are quite detailed and thorough, and full of examples. Having gone through this tutorial, you should easily digest them without feeling overwhelmed.
programming_docs
python Descriptor HowTo Guide Descriptor HowTo Guide ====================== Author Raymond Hettinger Contact <python at rcn dot com> * [Primer](#primer) + [Simple example: A descriptor that returns a constant](#simple-example-a-descriptor-that-returns-a-constant) + [Dynamic lookups](#dynamic-lookups) + [Managed attributes](#managed-attributes) + [Customized names](#customized-names) + [Closing thoughts](#closing-thoughts) * [Complete Practical Example](#complete-practical-example) + [Validator class](#validator-class) + [Custom validators](#custom-validators) + [Practical application](#practical-application) * [Technical Tutorial](#technical-tutorial) + [Abstract](#abstract) + [Definition and introduction](#definition-and-introduction) + [Descriptor protocol](#descriptor-protocol) + [Overview of descriptor invocation](#overview-of-descriptor-invocation) + [Invocation from an instance](#invocation-from-an-instance) + [Invocation from a class](#invocation-from-a-class) + [Invocation from super](#invocation-from-super) + [Summary of invocation logic](#summary-of-invocation-logic) + [Automatic name notification](#automatic-name-notification) + [ORM example](#orm-example) * [Pure Python Equivalents](#pure-python-equivalents) + [Properties](#properties) + [Functions and methods](#functions-and-methods) + [Kinds of methods](#kinds-of-methods) + [Static methods](#static-methods) + [Class methods](#class-methods) + [Member objects and \_\_slots\_\_](#member-objects-and-slots) [Descriptors](../glossary#term-descriptor) let objects customize attribute lookup, storage, and deletion. This guide has four major sections: 1. The “primer” gives a basic overview, moving gently from simple examples, adding one feature at a time. Start here if you’re new to descriptors. 2. The second section shows a complete, practical descriptor example. If you already know the basics, start there. 3. The third section provides a more technical tutorial that goes into the detailed mechanics of how descriptors work. Most people don’t need this level of detail. 4. The last section has pure Python equivalents for built-in descriptors that are written in C. Read this if you’re curious about how functions turn into bound methods or about the implementation of common tools like [`classmethod()`](../library/functions#classmethod "classmethod"), [`staticmethod()`](../library/functions#staticmethod "staticmethod"), [`property()`](../library/functions#property "property"), and [\_\_slots\_\_](../glossary#term-slots). Primer ------ In this primer, we start with the most basic possible example and then we’ll add new capabilities one by one. ### Simple example: A descriptor that returns a constant The `Ten` class is a descriptor that always returns the constant `10` from its [`__get__()`](../reference/datamodel#object.__get__ "object.__get__") method: ``` class Ten: def __get__(self, obj, objtype=None): return 10 ``` To use the descriptor, it must be stored as a class variable in another class: ``` class A: x = 5 # Regular class attribute y = Ten() # Descriptor instance ``` An interactive session shows the difference between normal attribute lookup and descriptor lookup: ``` >>> a = A() # Make an instance of class A >>> a.x # Normal attribute lookup 5 >>> a.y # Descriptor lookup 10 ``` In the `a.x` attribute lookup, the dot operator finds the key `x` and the value `5` in the class dictionary. In the `a.y` lookup, the dot operator finds a descriptor instance, recognized by its `__get__` method, and calls that method which returns `10`. Note that the value `10` is not stored in either the class dictionary or the instance dictionary. Instead, the value `10` is computed on demand. This example shows how a simple descriptor works, but it isn’t very useful. For retrieving constants, normal attribute lookup would be better. In the next section, we’ll create something more useful, a dynamic lookup. ### Dynamic lookups Interesting descriptors typically run computations instead of returning constants: ``` import os class DirectorySize: def __get__(self, obj, objtype=None): return len(os.listdir(obj.dirname)) class Directory: size = DirectorySize() # Descriptor instance def __init__(self, dirname): self.dirname = dirname # Regular instance attribute ``` An interactive session shows that the lookup is dynamic — it computes different, updated answers each time: ``` >>> s = Directory('songs') >>> g = Directory('games') >>> s.size # The songs directory has twenty files 20 >>> g.size # The games directory has three files 3 >>> os.remove('games/chess') # Delete a game >>> g.size # File count is automatically updated 2 ``` Besides showing how descriptors can run computations, this example also reveals the purpose of the parameters to [`__get__()`](../reference/datamodel#object.__get__ "object.__get__"). The *self* parameter is *size*, an instance of *DirectorySize*. The *obj* parameter is either *g* or *s*, an instance of *Directory*. It is the *obj* parameter that lets the [`__get__()`](../reference/datamodel#object.__get__ "object.__get__") method learn the target directory. The *objtype* parameter is the class *Directory*. ### Managed attributes A popular use for descriptors is managing access to instance data. The descriptor is assigned to a public attribute in the class dictionary while the actual data is stored as a private attribute in the instance dictionary. The descriptor’s [`__get__()`](../reference/datamodel#object.__get__ "object.__get__") and [`__set__()`](../reference/datamodel#object.__set__ "object.__set__") methods are triggered when the public attribute is accessed. In the following example, *age* is the public attribute and *\_age* is the private attribute. When the public attribute is accessed, the descriptor logs the lookup or update: ``` import logging logging.basicConfig(level=logging.INFO) class LoggedAgeAccess: def __get__(self, obj, objtype=None): value = obj._age logging.info('Accessing %r giving %r', 'age', value) return value def __set__(self, obj, value): logging.info('Updating %r to %r', 'age', value) obj._age = value class Person: age = LoggedAgeAccess() # Descriptor instance def __init__(self, name, age): self.name = name # Regular instance attribute self.age = age # Calls __set__() def birthday(self): self.age += 1 # Calls both __get__() and __set__() ``` An interactive session shows that all access to the managed attribute *age* is logged, but that the regular attribute *name* is not logged: ``` >>> mary = Person('Mary M', 30) # The initial age update is logged INFO:root:Updating 'age' to 30 >>> dave = Person('David D', 40) INFO:root:Updating 'age' to 40 >>> vars(mary) # The actual data is in a private attribute {'name': 'Mary M', '_age': 30} >>> vars(dave) {'name': 'David D', '_age': 40} >>> mary.age # Access the data and log the lookup INFO:root:Accessing 'age' giving 30 30 >>> mary.birthday() # Updates are logged as well INFO:root:Accessing 'age' giving 30 INFO:root:Updating 'age' to 31 >>> dave.name # Regular attribute lookup isn't logged 'David D' >>> dave.age # Only the managed attribute is logged INFO:root:Accessing 'age' giving 40 40 ``` One major issue with this example is that the private name *\_age* is hardwired in the *LoggedAgeAccess* class. That means that each instance can only have one logged attribute and that its name is unchangeable. In the next example, we’ll fix that problem. ### Customized names When a class uses descriptors, it can inform each descriptor about which variable name was used. In this example, the `Person` class has two descriptor instances, *name* and *age*. When the `Person` class is defined, it makes a callback to [`__set_name__()`](../reference/datamodel#object.__set_name__ "object.__set_name__") in *LoggedAccess* so that the field names can be recorded, giving each descriptor its own *public\_name* and *private\_name*: ``` import logging logging.basicConfig(level=logging.INFO) class LoggedAccess: def __set_name__(self, owner, name): self.public_name = name self.private_name = '_' + name def __get__(self, obj, objtype=None): value = getattr(obj, self.private_name) logging.info('Accessing %r giving %r', self.public_name, value) return value def __set__(self, obj, value): logging.info('Updating %r to %r', self.public_name, value) setattr(obj, self.private_name, value) class Person: name = LoggedAccess() # First descriptor instance age = LoggedAccess() # Second descriptor instance def __init__(self, name, age): self.name = name # Calls the first descriptor self.age = age # Calls the second descriptor def birthday(self): self.age += 1 ``` An interactive session shows that the `Person` class has called [`__set_name__()`](../reference/datamodel#object.__set_name__ "object.__set_name__") so that the field names would be recorded. Here we call [`vars()`](../library/functions#vars "vars") to look up the descriptor without triggering it: ``` >>> vars(vars(Person)['name']) {'public_name': 'name', 'private_name': '_name'} >>> vars(vars(Person)['age']) {'public_name': 'age', 'private_name': '_age'} ``` The new class now logs access to both *name* and *age*: ``` >>> pete = Person('Peter P', 10) INFO:root:Updating 'name' to 'Peter P' INFO:root:Updating 'age' to 10 >>> kate = Person('Catherine C', 20) INFO:root:Updating 'name' to 'Catherine C' INFO:root:Updating 'age' to 20 ``` The two *Person* instances contain only the private names: ``` >>> vars(pete) {'_name': 'Peter P', '_age': 10} >>> vars(kate) {'_name': 'Catherine C', '_age': 20} ``` ### Closing thoughts A [descriptor](../glossary#term-descriptor) is what we call any object that defines [`__get__()`](../reference/datamodel#object.__get__ "object.__get__"), [`__set__()`](../reference/datamodel#object.__set__ "object.__set__"), or [`__delete__()`](../reference/datamodel#object.__delete__ "object.__delete__"). Optionally, descriptors can have a [`__set_name__()`](../reference/datamodel#object.__set_name__ "object.__set_name__") method. This is only used in cases where a descriptor needs to know either the class where it was created or the name of class variable it was assigned to. (This method, if present, is called even if the class is not a descriptor.) Descriptors get invoked by the dot “operator” during attribute lookup. If a descriptor is accessed indirectly with `vars(some_class)[descriptor_name]`, the descriptor instance is returned without invoking it. Descriptors only work when used as class variables. When put in instances, they have no effect. The main motivation for descriptors is to provide a hook allowing objects stored in class variables to control what happens during attribute lookup. Traditionally, the calling class controls what happens during lookup. Descriptors invert that relationship and allow the data being looked-up to have a say in the matter. Descriptors are used throughout the language. It is how functions turn into bound methods. Common tools like [`classmethod()`](../library/functions#classmethod "classmethod"), [`staticmethod()`](../library/functions#staticmethod "staticmethod"), [`property()`](../library/functions#property "property"), and [`functools.cached_property()`](../library/functools#functools.cached_property "functools.cached_property") are all implemented as descriptors. Complete Practical Example -------------------------- In this example, we create a practical and powerful tool for locating notoriously hard to find data corruption bugs. ### Validator class A validator is a descriptor for managed attribute access. Prior to storing any data, it verifies that the new value meets various type and range restrictions. If those restrictions aren’t met, it raises an exception to prevent data corruption at its source. This `Validator` class is both an [abstract base class](../glossary#term-abstract-base-class) and a managed attribute descriptor: ``` from abc import ABC, abstractmethod class Validator(ABC): def __set_name__(self, owner, name): self.private_name = '_' + name def __get__(self, obj, objtype=None): return getattr(obj, self.private_name) def __set__(self, obj, value): self.validate(value) setattr(obj, self.private_name, value) @abstractmethod def validate(self, value): pass ``` Custom validators need to inherit from `Validator` and must supply a `validate()` method to test various restrictions as needed. ### Custom validators Here are three practical data validation utilities: 1. `OneOf` verifies that a value is one of a restricted set of options. 2. `Number` verifies that a value is either an [`int`](../library/functions#int "int") or [`float`](../library/functions#float "float"). Optionally, it verifies that a value is between a given minimum or maximum. 3. `String` verifies that a value is a [`str`](../library/stdtypes#str "str"). Optionally, it validates a given minimum or maximum length. It can validate a user-defined [predicate](https://en.wikipedia.org/wiki/Predicate_(mathematical_logic)) as well. ``` class OneOf(Validator): def __init__(self, *options): self.options = set(options) def validate(self, value): if value not in self.options: raise ValueError(f'Expected {value!r} to be one of {self.options!r}') class Number(Validator): def __init__(self, minvalue=None, maxvalue=None): self.minvalue = minvalue self.maxvalue = maxvalue def validate(self, value): if not isinstance(value, (int, float)): raise TypeError(f'Expected {value!r} to be an int or float') if self.minvalue is not None and value < self.minvalue: raise ValueError( f'Expected {value!r} to be at least {self.minvalue!r}' ) if self.maxvalue is not None and value > self.maxvalue: raise ValueError( f'Expected {value!r} to be no more than {self.maxvalue!r}' ) class String(Validator): def __init__(self, minsize=None, maxsize=None, predicate=None): self.minsize = minsize self.maxsize = maxsize self.predicate = predicate def validate(self, value): if not isinstance(value, str): raise TypeError(f'Expected {value!r} to be an str') if self.minsize is not None and len(value) < self.minsize: raise ValueError( f'Expected {value!r} to be no smaller than {self.minsize!r}' ) if self.maxsize is not None and len(value) > self.maxsize: raise ValueError( f'Expected {value!r} to be no bigger than {self.maxsize!r}' ) if self.predicate is not None and not self.predicate(value): raise ValueError( f'Expected {self.predicate} to be true for {value!r}' ) ``` ### Practical application Here’s how the data validators can be used in a real class: ``` class Component: name = String(minsize=3, maxsize=10, predicate=str.isupper) kind = OneOf('wood', 'metal', 'plastic') quantity = Number(minvalue=0) def __init__(self, name, kind, quantity): self.name = name self.kind = kind self.quantity = quantity ``` The descriptors prevent invalid instances from being created: ``` >>> Component('Widget', 'metal', 5) # Blocked: 'Widget' is not all uppercase Traceback (most recent call last): ... ValueError: Expected <method 'isupper' of 'str' objects> to be true for 'Widget' >>> Component('WIDGET', 'metle', 5) # Blocked: 'metle' is misspelled Traceback (most recent call last): ... ValueError: Expected 'metle' to be one of {'metal', 'plastic', 'wood'} >>> Component('WIDGET', 'metal', -5) # Blocked: -5 is negative Traceback (most recent call last): ... ValueError: Expected -5 to be at least 0 >>> Component('WIDGET', 'metal', 'V') # Blocked: 'V' isn't a number Traceback (most recent call last): ... TypeError: Expected 'V' to be an int or float >>> c = Component('WIDGET', 'metal', 5) # Allowed: The inputs are valid ``` Technical Tutorial ------------------ What follows is a more technical tutorial for the mechanics and details of how descriptors work. ### Abstract Defines descriptors, summarizes the protocol, and shows how descriptors are called. Provides an example showing how object relational mappings work. Learning about descriptors not only provides access to a larger toolset, it creates a deeper understanding of how Python works. ### Definition and introduction In general, a descriptor is an attribute value that has one of the methods in the descriptor protocol. Those methods are [`__get__()`](../reference/datamodel#object.__get__ "object.__get__"), [`__set__()`](../reference/datamodel#object.__set__ "object.__set__"), and [`__delete__()`](../reference/datamodel#object.__delete__ "object.__delete__"). If any of those methods are defined for an attribute, it is said to be a [descriptor](../glossary#term-descriptor). The default behavior for attribute access is to get, set, or delete the attribute from an object’s dictionary. For instance, `a.x` has a lookup chain starting with `a.__dict__['x']`, then `type(a).__dict__['x']`, and continuing through the method resolution order of `type(a)`. If the looked-up value is an object defining one of the descriptor methods, then Python may override the default behavior and invoke the descriptor method instead. Where this occurs in the precedence chain depends on which descriptor methods were defined. Descriptors are a powerful, general purpose protocol. They are the mechanism behind properties, methods, static methods, class methods, and [`super()`](../library/functions#super "super"). They are used throughout Python itself. Descriptors simplify the underlying C code and offer a flexible set of new tools for everyday Python programs. ### Descriptor protocol `descr.__get__(self, obj, type=None) -> value` `descr.__set__(self, obj, value) -> None` `descr.__delete__(self, obj) -> None` That is all there is to it. Define any of these methods and an object is considered a descriptor and can override default behavior upon being looked up as an attribute. If an object defines [`__set__()`](../reference/datamodel#object.__set__ "object.__set__") or [`__delete__()`](../reference/datamodel#object.__delete__ "object.__delete__"), it is considered a data descriptor. Descriptors that only define [`__get__()`](../reference/datamodel#object.__get__ "object.__get__") are called non-data descriptors (they are often used for methods but other uses are possible). Data and non-data descriptors differ in how overrides are calculated with respect to entries in an instance’s dictionary. If an instance’s dictionary has an entry with the same name as a data descriptor, the data descriptor takes precedence. If an instance’s dictionary has an entry with the same name as a non-data descriptor, the dictionary entry takes precedence. To make a read-only data descriptor, define both [`__get__()`](../reference/datamodel#object.__get__ "object.__get__") and [`__set__()`](../reference/datamodel#object.__set__ "object.__set__") with the [`__set__()`](../reference/datamodel#object.__set__ "object.__set__") raising an [`AttributeError`](../library/exceptions#AttributeError "AttributeError") when called. Defining the [`__set__()`](../reference/datamodel#object.__set__ "object.__set__") method with an exception raising placeholder is enough to make it a data descriptor. ### Overview of descriptor invocation A descriptor can be called directly with `desc.__get__(obj)` or `desc.__get__(None, cls)`. But it is more common for a descriptor to be invoked automatically from attribute access. The expression `obj.x` looks up the attribute `x` in the chain of namespaces for `obj`. If the search finds a descriptor outside of the instance `__dict__`, its [`__get__()`](../reference/datamodel#object.__get__ "object.__get__") method is invoked according to the precedence rules listed below. The details of invocation depend on whether `obj` is an object, class, or instance of super. ### Invocation from an instance Instance lookup scans through a chain of namespaces giving data descriptors the highest priority, followed by instance variables, then non-data descriptors, then class variables, and lastly [`__getattr__()`](../reference/datamodel#object.__getattr__ "object.__getattr__") if it is provided. If a descriptor is found for `a.x`, then it is invoked with: `desc.__get__(a, type(a))`. The logic for a dotted lookup is in [`object.__getattribute__()`](../reference/datamodel#object.__getattribute__ "object.__getattribute__"). Here is a pure Python equivalent: ``` def object_getattribute(obj, name): "Emulate PyObject_GenericGetAttr() in Objects/object.c" null = object() objtype = type(obj) cls_var = getattr(objtype, name, null) descr_get = getattr(type(cls_var), '__get__', null) if descr_get is not null: if (hasattr(type(cls_var), '__set__') or hasattr(type(cls_var), '__delete__')): return descr_get(cls_var, obj, objtype) # data descriptor if hasattr(obj, '__dict__') and name in vars(obj): return vars(obj)[name] # instance variable if descr_get is not null: return descr_get(cls_var, obj, objtype) # non-data descriptor if cls_var is not null: return cls_var # class variable raise AttributeError(name) ``` Note, there is no [`__getattr__()`](../reference/datamodel#object.__getattr__ "object.__getattr__") hook in the [`__getattribute__()`](../reference/datamodel#object.__getattribute__ "object.__getattribute__") code. That is why calling [`__getattribute__()`](../reference/datamodel#object.__getattribute__ "object.__getattribute__") directly or with `super().__getattribute__` will bypass [`__getattr__()`](../reference/datamodel#object.__getattr__ "object.__getattr__") entirely. Instead, it is the dot operator and the [`getattr()`](../library/functions#getattr "getattr") function that are responsible for invoking [`__getattr__()`](../reference/datamodel#object.__getattr__ "object.__getattr__") whenever [`__getattribute__()`](../reference/datamodel#object.__getattribute__ "object.__getattribute__") raises an [`AttributeError`](../library/exceptions#AttributeError "AttributeError"). Their logic is encapsulated in a helper function: ``` def getattr_hook(obj, name): "Emulate slot_tp_getattr_hook() in Objects/typeobject.c" try: return obj.__getattribute__(name) except AttributeError: if not hasattr(type(obj), '__getattr__'): raise return type(obj).__getattr__(obj, name) # __getattr__ ``` ### Invocation from a class The logic for a dotted lookup such as `A.x` is in `type.__getattribute__()`. The steps are similar to those for [`object.__getattribute__()`](../reference/datamodel#object.__getattribute__ "object.__getattribute__") but the instance dictionary lookup is replaced by a search through the class’s [method resolution order](../glossary#term-method-resolution-order). If a descriptor is found, it is invoked with `desc.__get__(None, A)`. The full C implementation can be found in `type_getattro()` and `_PyType_Lookup()` in [Objects/typeobject.c](https://github.com/python/cpython/tree/3.9/Objects/typeobject.c). ### Invocation from super The logic for super’s dotted lookup is in the [`__getattribute__()`](../reference/datamodel#object.__getattribute__ "object.__getattribute__") method for object returned by [`super()`](../library/functions#super "super"). A dotted lookup such as `super(A, obj).m` searches `obj.__class__.__mro__` for the base class `B` immediately following `A` and then returns `B.__dict__['m'].__get__(obj, A)`. If not a descriptor, `m` is returned unchanged. The full C implementation can be found in `super_getattro()` in [Objects/typeobject.c](https://github.com/python/cpython/tree/3.9/Objects/typeobject.c). A pure Python equivalent can be found in [Guido’s Tutorial](https://www.python.org/download/releases/2.2.3/descrintro/#cooperation). ### Summary of invocation logic The mechanism for descriptors is embedded in the [`__getattribute__()`](../reference/datamodel#object.__getattribute__ "object.__getattribute__") methods for [`object`](../library/functions#object "object"), [`type`](../library/functions#type "type"), and [`super()`](../library/functions#super "super"). The important points to remember are: * Descriptors are invoked by the [`__getattribute__()`](../reference/datamodel#object.__getattribute__ "object.__getattribute__") method. * Classes inherit this machinery from [`object`](../library/functions#object "object"), [`type`](../library/functions#type "type"), or [`super()`](../library/functions#super "super"). * Overriding [`__getattribute__()`](../reference/datamodel#object.__getattribute__ "object.__getattribute__") prevents automatic descriptor calls because all the descriptor logic is in that method. * [`object.__getattribute__()`](../reference/datamodel#object.__getattribute__ "object.__getattribute__") and `type.__getattribute__()` make different calls to [`__get__()`](../reference/datamodel#object.__get__ "object.__get__"). The first includes the instance and may include the class. The second puts in `None` for the instance and always includes the class. * Data descriptors always override instance dictionaries. * Non-data descriptors may be overridden by instance dictionaries. ### Automatic name notification Sometimes it is desirable for a descriptor to know what class variable name it was assigned to. When a new class is created, the [`type`](../library/functions#type "type") metaclass scans the dictionary of the new class. If any of the entries are descriptors and if they define [`__set_name__()`](../reference/datamodel#object.__set_name__ "object.__set_name__"), that method is called with two arguments. The *owner* is the class where the descriptor is used, and the *name* is the class variable the descriptor was assigned to. The implementation details are in `type_new()` and `set_names()` in [Objects/typeobject.c](https://github.com/python/cpython/tree/3.9/Objects/typeobject.c). Since the update logic is in `type.__new__()`, notifications only take place at the time of class creation. If descriptors are added to the class afterwards, [`__set_name__()`](../reference/datamodel#object.__set_name__ "object.__set_name__") will need to be called manually. ### ORM example The following code is simplified skeleton showing how data descriptors could be used to implement an [object relational mapping](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping). The essential idea is that the data is stored in an external database. The Python instances only hold keys to the database’s tables. Descriptors take care of lookups or updates: ``` class Field: def __set_name__(self, owner, name): self.fetch = f'SELECT {name} FROM {owner.table} WHERE {owner.key}=?;' self.store = f'UPDATE {owner.table} SET {name}=? WHERE {owner.key}=?;' def __get__(self, obj, objtype=None): return conn.execute(self.fetch, [obj.key]).fetchone()[0] def __set__(self, obj, value): conn.execute(self.store, [value, obj.key]) conn.commit() ``` We can use the `Field` class to define [models](https://en.wikipedia.org/wiki/Database_model) that describe the schema for each table in a database: ``` class Movie: table = 'Movies' # Table name key = 'title' # Primary key director = Field() year = Field() def __init__(self, key): self.key = key class Song: table = 'Music' key = 'title' artist = Field() year = Field() genre = Field() def __init__(self, key): self.key = key ``` To use the models, first connect to the database: ``` >>> import sqlite3 >>> conn = sqlite3.connect('entertainment.db') ``` An interactive session shows how data is retrieved from the database and how it can be updated: ``` >>> Movie('Star Wars').director 'George Lucas' >>> jaws = Movie('Jaws') >>> f'Released in {jaws.year} by {jaws.director}' 'Released in 1975 by Steven Spielberg' >>> Song('Country Roads').artist 'John Denver' >>> Movie('Star Wars').director = 'J.J. Abrams' >>> Movie('Star Wars').director 'J.J. Abrams' ``` Pure Python Equivalents ----------------------- The descriptor protocol is simple and offers exciting possibilities. Several use cases are so common that they have been prepackaged into built-in tools. Properties, bound methods, static methods, class methods, and \_\_slots\_\_ are all based on the descriptor protocol. ### Properties Calling [`property()`](../library/functions#property "property") is a succinct way of building a data descriptor that triggers a function call upon access to an attribute. Its signature is: ``` property(fget=None, fset=None, fdel=None, doc=None) -> property ``` The documentation shows a typical use to define a managed attribute `x`: ``` class C: def getx(self): return self.__x def setx(self, value): self.__x = value def delx(self): del self.__x x = property(getx, setx, delx, "I'm the 'x' property.") ``` To see how [`property()`](../library/functions#property "property") is implemented in terms of the descriptor protocol, here is a pure Python equivalent: ``` class Property: "Emulate PyProperty_Type() in Objects/descrobject.c" def __init__(self, fget=None, fset=None, fdel=None, doc=None): self.fget = fget self.fset = fset self.fdel = fdel if doc is None and fget is not None: doc = fget.__doc__ self.__doc__ = doc def __get__(self, obj, objtype=None): if obj is None: return self if self.fget is None: raise AttributeError("unreadable attribute") return self.fget(obj) def __set__(self, obj, value): if self.fset is None: raise AttributeError("can't set attribute") self.fset(obj, value) def __delete__(self, obj): if self.fdel is None: raise AttributeError("can't delete attribute") self.fdel(obj) def getter(self, fget): return type(self)(fget, self.fset, self.fdel, self.__doc__) def setter(self, fset): return type(self)(self.fget, fset, self.fdel, self.__doc__) def deleter(self, fdel): return type(self)(self.fget, self.fset, fdel, self.__doc__) ``` The [`property()`](../library/functions#property "property") builtin helps whenever a user interface has granted attribute access and then subsequent changes require the intervention of a method. For instance, a spreadsheet class may grant access to a cell value through `Cell('b10').value`. Subsequent improvements to the program require the cell to be recalculated on every access; however, the programmer does not want to affect existing client code accessing the attribute directly. The solution is to wrap access to the value attribute in a property data descriptor: ``` class Cell: ... @property def value(self): "Recalculate the cell before returning value" self.recalc() return self._value ``` Either the built-in [`property()`](../library/functions#property "property") or our `Property()` equivalent would work in this example. ### Functions and methods Python’s object oriented features are built upon a function based environment. Using non-data descriptors, the two are merged seamlessly. Functions stored in class dictionaries get turned into methods when invoked. Methods only differ from regular functions in that the object instance is prepended to the other arguments. By convention, the instance is called *self* but could be called *this* or any other variable name. Methods can be created manually with [`types.MethodType`](../library/types#types.MethodType "types.MethodType") which is roughly equivalent to: ``` class MethodType: "Emulate PyMethod_Type in Objects/classobject.c" def __init__(self, func, obj): self.__func__ = func self.__self__ = obj def __call__(self, *args, **kwargs): func = self.__func__ obj = self.__self__ return func(obj, *args, **kwargs) ``` To support automatic creation of methods, functions include the [`__get__()`](../reference/datamodel#object.__get__ "object.__get__") method for binding methods during attribute access. This means that functions are non-data descriptors that return bound methods during dotted lookup from an instance. Here’s how it works: ``` class Function: ... def __get__(self, obj, objtype=None): "Simulate func_descr_get() in Objects/funcobject.c" if obj is None: return self return MethodType(self, obj) ``` Running the following class in the interpreter shows how the function descriptor works in practice: ``` class D: def f(self, x): return x ``` The function has a [qualified name](../glossary#term-qualified-name) attribute to support introspection: ``` >>> D.f.__qualname__ 'D.f' ``` Accessing the function through the class dictionary does not invoke [`__get__()`](../reference/datamodel#object.__get__ "object.__get__"). Instead, it just returns the underlying function object: ``` >>> D.__dict__['f'] <function D.f at 0x00C45070> ``` Dotted access from a class calls [`__get__()`](../reference/datamodel#object.__get__ "object.__get__") which just returns the underlying function unchanged: ``` >>> D.f <function D.f at 0x00C45070> ``` The interesting behavior occurs during dotted access from an instance. The dotted lookup calls [`__get__()`](../reference/datamodel#object.__get__ "object.__get__") which returns a bound method object: ``` >>> d = D() >>> d.f <bound method D.f of <__main__.D object at 0x00B18C90>> ``` Internally, the bound method stores the underlying function and the bound instance: ``` >>> d.f.__func__ <function D.f at 0x00C45070> >>> d.f.__self__ <__main__.D object at 0x1012e1f98> ``` If you have ever wondered where *self* comes from in regular methods or where *cls* comes from in class methods, this is it! ### Kinds of methods Non-data descriptors provide a simple mechanism for variations on the usual patterns of binding functions into methods. To recap, functions have a [`__get__()`](../reference/datamodel#object.__get__ "object.__get__") method so that they can be converted to a method when accessed as attributes. The non-data descriptor transforms an `obj.f(*args)` call into `f(obj, *args)`. Calling `cls.f(*args)` becomes `f(*args)`. This chart summarizes the binding and its two most useful variants: | Transformation | Called from an object | Called from a class | | --- | --- | --- | | function | f(obj, \*args) | f(\*args) | | staticmethod | f(\*args) | f(\*args) | | classmethod | f(type(obj), \*args) | f(cls, \*args) | ### Static methods Static methods return the underlying function without changes. Calling either `c.f` or `C.f` is the equivalent of a direct lookup into `object.__getattribute__(c, "f")` or `object.__getattribute__(C, "f")`. As a result, the function becomes identically accessible from either an object or a class. Good candidates for static methods are methods that do not reference the `self` variable. For instance, a statistics package may include a container class for experimental data. The class provides normal methods for computing the average, mean, median, and other descriptive statistics that depend on the data. However, there may be useful functions which are conceptually related but do not depend on the data. For instance, `erf(x)` is handy conversion routine that comes up in statistical work but does not directly depend on a particular dataset. It can be called either from an object or the class: `s.erf(1.5) --> .9332` or `Sample.erf(1.5) --> .9332`. Since static methods return the underlying function with no changes, the example calls are unexciting: ``` class E: @staticmethod def f(x): return x * 10 ``` ``` >>> E.f(3) 30 >>> E().f(3) 30 ``` Using the non-data descriptor protocol, a pure Python version of [`staticmethod()`](../library/functions#staticmethod "staticmethod") would look like this: ``` class StaticMethod: "Emulate PyStaticMethod_Type() in Objects/funcobject.c" def __init__(self, f): self.f = f def __get__(self, obj, objtype=None): return self.f ``` ### Class methods Unlike static methods, class methods prepend the class reference to the argument list before calling the function. This format is the same for whether the caller is an object or a class: ``` class F: @classmethod def f(cls, x): return cls.__name__, x ``` ``` >>> F.f(3) ('F', 3) >>> F().f(3) ('F', 3) ``` This behavior is useful whenever the method only needs to have a class reference and does not rely on data stored in a specific instance. One use for class methods is to create alternate class constructors. For example, the classmethod [`dict.fromkeys()`](../library/stdtypes#dict.fromkeys "dict.fromkeys") creates a new dictionary from a list of keys. The pure Python equivalent is: ``` class Dict(dict): @classmethod def fromkeys(cls, iterable, value=None): "Emulate dict_fromkeys() in Objects/dictobject.c" d = cls() for key in iterable: d[key] = value return d ``` Now a new dictionary of unique keys can be constructed like this: ``` >>> d = Dict.fromkeys('abracadabra') >>> type(d) is Dict True >>> d {'a': None, 'b': None, 'r': None, 'c': None, 'd': None} ``` Using the non-data descriptor protocol, a pure Python version of [`classmethod()`](../library/functions#classmethod "classmethod") would look like this: ``` class ClassMethod: "Emulate PyClassMethod_Type() in Objects/funcobject.c" def __init__(self, f): self.f = f def __get__(self, obj, cls=None): if cls is None: cls = type(obj) if hasattr(type(self.f), '__get__'): return self.f.__get__(cls) return MethodType(self.f, cls) ``` The code path for `hasattr(type(self.f), '__get__')` was added in Python 3.9 and makes it possible for [`classmethod()`](../library/functions#classmethod "classmethod") to support chained decorators. For example, a classmethod and property could be chained together: ``` class G: @classmethod @property def __doc__(cls): return f'A doc for {cls.__name__!r}' ``` ``` >>> G.__doc__ "A doc for 'G'" ``` ### Member objects and \_\_slots\_\_ When a class defines `__slots__`, it replaces instance dictionaries with a fixed-length array of slot values. From a user point of view that has several effects: 1. Provides immediate detection of bugs due to misspelled attribute assignments. Only attribute names specified in `__slots__` are allowed: ``` class Vehicle: __slots__ = ('id_number', 'make', 'model') ``` ``` >>> auto = Vehicle() >>> auto.id_nubmer = 'VYE483814LQEX' Traceback (most recent call last): ... AttributeError: 'Vehicle' object has no attribute 'id_nubmer' ``` 2. Helps create immutable objects where descriptors manage access to private attributes stored in `__slots__`: ``` class Immutable: __slots__ = ('_dept', '_name') # Replace the instance dictionary def __init__(self, dept, name): self._dept = dept # Store to private attribute self._name = name # Store to private attribute @property # Read-only descriptor def dept(self): return self._dept @property def name(self): # Read-only descriptor return self._name ``` ``` >>> mark = Immutable('Botany', 'Mark Watney') >>> mark.dept 'Botany' >>> mark.dept = 'Space Pirate' Traceback (most recent call last): ... AttributeError: can't set attribute >>> mark.location = 'Mars' Traceback (most recent call last): ... AttributeError: 'Immutable' object has no attribute 'location' ``` 3. Saves memory. On a 64-bit Linux build, an instance with two attributes takes 48 bytes with `__slots__` and 152 bytes without. This [flyweight design pattern](https://en.wikipedia.org/wiki/Flyweight_pattern) likely only matters when a large number of instances are going to be created. 4. Blocks tools like [`functools.cached_property()`](../library/functools#functools.cached_property "functools.cached_property") which require an instance dictionary to function correctly: ``` from functools import cached_property class CP: __slots__ = () # Eliminates the instance dict @cached_property # Requires an instance dict def pi(self): return 4 * sum((-1.0)**n / (2.0*n + 1.0) for n in reversed(range(100_000))) ``` ``` >>> CP().pi Traceback (most recent call last): ... TypeError: No '__dict__' attribute on 'CP' instance to cache 'pi' property. ``` It is not possible to create an exact drop-in pure Python version of `__slots__` because it requires direct access to C structures and control over object memory allocation. However, we can build a mostly faithful simulation where the actual C structure for slots is emulated by a private `_slotvalues` list. Reads and writes to that private structure are managed by member descriptors: ``` null = object() class Member: def __init__(self, name, clsname, offset): 'Emulate PyMemberDef in Include/structmember.h' # Also see descr_new() in Objects/descrobject.c self.name = name self.clsname = clsname self.offset = offset def __get__(self, obj, objtype=None): 'Emulate member_get() in Objects/descrobject.c' # Also see PyMember_GetOne() in Python/structmember.c value = obj._slotvalues[self.offset] if value is null: raise AttributeError(self.name) return value def __set__(self, obj, value): 'Emulate member_set() in Objects/descrobject.c' obj._slotvalues[self.offset] = value def __delete__(self, obj): 'Emulate member_delete() in Objects/descrobject.c' value = obj._slotvalues[self.offset] if value is null: raise AttributeError(self.name) obj._slotvalues[self.offset] = null def __repr__(self): 'Emulate member_repr() in Objects/descrobject.c' return f'<Member {self.name!r} of {self.clsname!r}>' ``` The `type.__new__()` method takes care of adding member objects to class variables: ``` class Type(type): 'Simulate how the type metaclass adds member objects for slots' def __new__(mcls, clsname, bases, mapping): 'Emuluate type_new() in Objects/typeobject.c' # type_new() calls PyTypeReady() which calls add_methods() slot_names = mapping.get('slot_names', []) for offset, name in enumerate(slot_names): mapping[name] = Member(name, clsname, offset) return type.__new__(mcls, clsname, bases, mapping) ``` The [`object.__new__()`](../reference/datamodel#object.__new__ "object.__new__") method takes care of creating instances that have slots instead of an instance dictionary. Here is a rough simulation in pure Python: ``` class Object: 'Simulate how object.__new__() allocates memory for __slots__' def __new__(cls, *args): 'Emulate object_new() in Objects/typeobject.c' inst = super().__new__(cls) if hasattr(cls, 'slot_names'): empty_slots = [null] * len(cls.slot_names) object.__setattr__(inst, '_slotvalues', empty_slots) return inst def __setattr__(self, name, value): 'Emulate _PyObject_GenericSetAttrWithDict() Objects/object.c' cls = type(self) if hasattr(cls, 'slot_names') and name not in cls.slot_names: raise AttributeError( f'{type(self).__name__!r} object has no attribute {name!r}' ) super().__setattr__(name, value) def __delattr__(self, name): 'Emulate _PyObject_GenericSetAttrWithDict() Objects/object.c' cls = type(self) if hasattr(cls, 'slot_names') and name not in cls.slot_names: raise AttributeError( f'{type(self).__name__!r} object has no attribute {name!r}' ) super().__delattr__(name) ``` To use the simulation in a real class, just inherit from `Object` and set the [metaclass](../glossary#term-metaclass) to `Type`: ``` class H(Object, metaclass=Type): 'Instance variables stored in slots' slot_names = ['x', 'y'] def __init__(self, x, y): self.x = x self.y = y ``` At this point, the metaclass has loaded member objects for *x* and *y*: ``` >>> from pprint import pp >>> pp(dict(vars(H))) {'__module__': '__main__', '__doc__': 'Instance variables stored in slots', 'slot_names': ['x', 'y'], '__init__': <function H.__init__ at 0x7fb5d302f9d0>, 'x': <Member 'x' of 'H'>, 'y': <Member 'y' of 'H'>} ``` When instances are created, they have a `slot_values` list where the attributes are stored: ``` >>> h = H(10, 20) >>> vars(h) {'_slotvalues': [10, 20]} >>> h.x = 55 >>> vars(h) {'_slotvalues': [55, 20]} ``` Misspelled or unassigned attributes will raise an exception: ``` >>> h.xz Traceback (most recent call last): ... AttributeError: 'H' object has no attribute 'xz' ```
programming_docs
python HOWTO Fetch Internet Resources Using The urllib Package HOWTO Fetch Internet Resources Using The urllib Package ======================================================= Author [Michael Foord](http://www.voidspace.org.uk/python/index.shtml) Note There is a French translation of an earlier revision of this HOWTO, available at [urllib2 - Le Manuel manquant](http://www.voidspace.org.uk/python/articles/urllib2_francais.shtml). Introduction ------------ **urllib.request** is a Python module for fetching URLs (Uniform Resource Locators). It offers a very simple interface, in the form of the *urlopen* function. This is capable of fetching URLs using a variety of different protocols. It also offers a slightly more complex interface for handling common situations - like basic authentication, cookies, proxies and so on. These are provided by objects called handlers and openers. urllib.request supports fetching URLs for many “URL schemes” (identified by the string before the `":"` in URL - for example `"ftp"` is the URL scheme of `"ftp://python.org/"`) using their associated network protocols (e.g. FTP, HTTP). This tutorial focuses on the most common case, HTTP. For straightforward situations *urlopen* is very easy to use. But as soon as you encounter errors or non-trivial cases when opening HTTP URLs, you will need some understanding of the HyperText Transfer Protocol. The most comprehensive and authoritative reference to HTTP is [**RFC 2616**](https://tools.ietf.org/html/rfc2616.html). This is a technical document and not intended to be easy to read. This HOWTO aims to illustrate using *urllib*, with enough detail about HTTP to help you through. It is not intended to replace the [`urllib.request`](../library/urllib.request#module-urllib.request "urllib.request: Extensible library for opening URLs.") docs, but is supplementary to them. Fetching URLs ------------- The simplest way to use urllib.request is as follows: ``` import urllib.request with urllib.request.urlopen('http://python.org/') as response: html = response.read() ``` If you wish to retrieve a resource via URL and store it in a temporary location, you can do so via the [`shutil.copyfileobj()`](../library/shutil#shutil.copyfileobj "shutil.copyfileobj") and [`tempfile.NamedTemporaryFile()`](../library/tempfile#tempfile.NamedTemporaryFile "tempfile.NamedTemporaryFile") functions: ``` import shutil import tempfile import urllib.request with urllib.request.urlopen('http://python.org/') as response: with tempfile.NamedTemporaryFile(delete=False) as tmp_file: shutil.copyfileobj(response, tmp_file) with open(tmp_file.name) as html: pass ``` Many uses of urllib will be that simple (note that instead of an ‘http:’ URL we could have used a URL starting with ‘ftp:’, ‘file:’, etc.). However, it’s the purpose of this tutorial to explain the more complicated cases, concentrating on HTTP. HTTP is based on requests and responses - the client makes requests and servers send responses. urllib.request mirrors this with a `Request` object which represents the HTTP request you are making. In its simplest form you create a Request object that specifies the URL you want to fetch. Calling `urlopen` with this Request object returns a response object for the URL requested. This response is a file-like object, which means you can for example call `.read()` on the response: ``` import urllib.request req = urllib.request.Request('http://www.voidspace.org.uk') with urllib.request.urlopen(req) as response: the_page = response.read() ``` Note that urllib.request makes use of the same Request interface to handle all URL schemes. For example, you can make an FTP request like so: ``` req = urllib.request.Request('ftp://example.com/') ``` In the case of HTTP, there are two extra things that Request objects allow you to do: First, you can pass data to be sent to the server. Second, you can pass extra information (“metadata”) *about* the data or about the request itself, to the server - this information is sent as HTTP “headers”. Let’s look at each of these in turn. ### Data Sometimes you want to send data to a URL (often the URL will refer to a CGI (Common Gateway Interface) script or other web application). With HTTP, this is often done using what’s known as a **POST** request. This is often what your browser does when you submit a HTML form that you filled in on the web. Not all POSTs have to come from forms: you can use a POST to transmit arbitrary data to your own application. In the common case of HTML forms, the data needs to be encoded in a standard way, and then passed to the Request object as the `data` argument. The encoding is done using a function from the [`urllib.parse`](../library/urllib.parse#module-urllib.parse "urllib.parse: Parse URLs into or assemble them from components.") library. ``` import urllib.parse import urllib.request url = 'http://www.someserver.com/cgi-bin/register.cgi' values = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' } data = urllib.parse.urlencode(values) data = data.encode('ascii') # data should be bytes req = urllib.request.Request(url, data) with urllib.request.urlopen(req) as response: the_page = response.read() ``` Note that other encodings are sometimes required (e.g. for file upload from HTML forms - see [HTML Specification, Form Submission](https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13) for more details). If you do not pass the `data` argument, urllib uses a **GET** request. One way in which GET and POST requests differ is that POST requests often have “side-effects”: they change the state of the system in some way (for example by placing an order with the website for a hundredweight of tinned spam to be delivered to your door). Though the HTTP standard makes it clear that POSTs are intended to *always* cause side-effects, and GET requests *never* to cause side-effects, nothing prevents a GET request from having side-effects, nor a POST requests from having no side-effects. Data can also be passed in an HTTP GET request by encoding it in the URL itself. This is done as follows: ``` >>> import urllib.request >>> import urllib.parse >>> data = {} >>> data['name'] = 'Somebody Here' >>> data['location'] = 'Northampton' >>> data['language'] = 'Python' >>> url_values = urllib.parse.urlencode(data) >>> print(url_values) # The order may differ from below. name=Somebody+Here&language=Python&location=Northampton >>> url = 'http://www.example.com/example.cgi' >>> full_url = url + '?' + url_values >>> data = urllib.request.urlopen(full_url) ``` Notice that the full URL is created by adding a `?` to the URL, followed by the encoded values. ### Headers We’ll discuss here one particular HTTP header, to illustrate how to add headers to your HTTP request. Some websites [1](#id8) dislike being browsed by programs, or send different versions to different browsers [2](#id9). By default urllib identifies itself as `Python-urllib/x.y` (where `x` and `y` are the major and minor version numbers of the Python release, e.g. `Python-urllib/2.5`), which may confuse the site, or just plain not work. The way a browser identifies itself is through the `User-Agent` header [3](#id10). When you create a Request object you can pass a dictionary of headers in. The following example makes the same request as above, but identifies itself as a version of Internet Explorer [4](#id11). ``` import urllib.parse import urllib.request url = 'http://www.someserver.com/cgi-bin/register.cgi' user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' values = {'name': 'Michael Foord', 'location': 'Northampton', 'language': 'Python' } headers = {'User-Agent': user_agent} data = urllib.parse.urlencode(values) data = data.encode('ascii') req = urllib.request.Request(url, data, headers) with urllib.request.urlopen(req) as response: the_page = response.read() ``` The response also has two useful methods. See the section on [info and geturl](#info-and-geturl) which comes after we have a look at what happens when things go wrong. Handling Exceptions ------------------- *urlopen* raises `URLError` when it cannot handle a response (though as usual with Python APIs, built-in exceptions such as [`ValueError`](../library/exceptions#ValueError "ValueError"), [`TypeError`](../library/exceptions#TypeError "TypeError") etc. may also be raised). `HTTPError` is the subclass of `URLError` raised in the specific case of HTTP URLs. The exception classes are exported from the [`urllib.error`](../library/urllib.error#module-urllib.error "urllib.error: Exception classes raised by urllib.request.") module. ### URLError Often, URLError is raised because there is no network connection (no route to the specified server), or the specified server doesn’t exist. In this case, the exception raised will have a ‘reason’ attribute, which is a tuple containing an error code and a text error message. e.g. ``` >>> req = urllib.request.Request('http://www.pretend_server.org') >>> try: urllib.request.urlopen(req) ... except urllib.error.URLError as e: ... print(e.reason) ... (4, 'getaddrinfo failed') ``` ### HTTPError Every HTTP response from the server contains a numeric “status code”. Sometimes the status code indicates that the server is unable to fulfil the request. The default handlers will handle some of these responses for you (for example, if the response is a “redirection” that requests the client fetch the document from a different URL, urllib will handle that for you). For those it can’t handle, urlopen will raise an `HTTPError`. Typical errors include ‘404’ (page not found), ‘403’ (request forbidden), and ‘401’ (authentication required). See section 10 of [**RFC 2616**](https://tools.ietf.org/html/rfc2616.html) for a reference on all the HTTP error codes. The `HTTPError` instance raised will have an integer ‘code’ attribute, which corresponds to the error sent by the server. #### Error Codes Because the default handlers handle redirects (codes in the 300 range), and codes in the 100–299 range indicate success, you will usually only see error codes in the 400–599 range. [`http.server.BaseHTTPRequestHandler.responses`](../library/http.server#http.server.BaseHTTPRequestHandler.responses "http.server.BaseHTTPRequestHandler.responses") is a useful dictionary of response codes in that shows all the response codes used by [**RFC 2616**](https://tools.ietf.org/html/rfc2616.html). The dictionary is reproduced here for convenience ``` # Table mapping response codes to messages; entries have the # form {code: (shortmessage, longmessage)}. responses = { 100: ('Continue', 'Request received, please continue'), 101: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'), 200: ('OK', 'Request fulfilled, document follows'), 201: ('Created', 'Document created, URL follows'), 202: ('Accepted', 'Request accepted, processing continues off-line'), 203: ('Non-Authoritative Information', 'Request fulfilled from cache'), 204: ('No Content', 'Request fulfilled, nothing follows'), 205: ('Reset Content', 'Clear input form for further input.'), 206: ('Partial Content', 'Partial content follows.'), 300: ('Multiple Choices', 'Object has several resources -- see URI list'), 301: ('Moved Permanently', 'Object moved permanently -- see URI list'), 302: ('Found', 'Object moved temporarily -- see URI list'), 303: ('See Other', 'Object moved -- see Method and URL list'), 304: ('Not Modified', 'Document has not changed since given time'), 305: ('Use Proxy', 'You must use proxy specified in Location to access this ' 'resource.'), 307: ('Temporary Redirect', 'Object moved temporarily -- see URI list'), 400: ('Bad Request', 'Bad request syntax or unsupported method'), 401: ('Unauthorized', 'No permission -- see authorization schemes'), 402: ('Payment Required', 'No payment -- see charging schemes'), 403: ('Forbidden', 'Request forbidden -- authorization will not help'), 404: ('Not Found', 'Nothing matches the given URI'), 405: ('Method Not Allowed', 'Specified method is invalid for this server.'), 406: ('Not Acceptable', 'URI not available in preferred format.'), 407: ('Proxy Authentication Required', 'You must authenticate with ' 'this proxy before proceeding.'), 408: ('Request Timeout', 'Request timed out; try again later.'), 409: ('Conflict', 'Request conflict.'), 410: ('Gone', 'URI no longer exists and has been permanently removed.'), 411: ('Length Required', 'Client must specify Content-Length.'), 412: ('Precondition Failed', 'Precondition in headers is false.'), 413: ('Request Entity Too Large', 'Entity is too large.'), 414: ('Request-URI Too Long', 'URI is too long.'), 415: ('Unsupported Media Type', 'Entity body in unsupported format.'), 416: ('Requested Range Not Satisfiable', 'Cannot satisfy request range.'), 417: ('Expectation Failed', 'Expect condition could not be satisfied.'), 500: ('Internal Server Error', 'Server got itself in trouble'), 501: ('Not Implemented', 'Server does not support this operation'), 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'), 503: ('Service Unavailable', 'The server cannot process the request due to a high load'), 504: ('Gateway Timeout', 'The gateway server did not receive a timely response'), 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'), } ``` When an error is raised the server responds by returning an HTTP error code *and* an error page. You can use the `HTTPError` instance as a response on the page returned. This means that as well as the code attribute, it also has read, geturl, and info, methods as returned by the `urllib.response` module: ``` >>> req = urllib.request.Request('http://www.python.org/fish.html') >>> try: ... urllib.request.urlopen(req) ... except urllib.error.HTTPError as e: ... print(e.code) ... print(e.read()) ... 404 b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n<html ... <title>Page Not Found</title>\n ... ``` ### Wrapping it Up So if you want to be prepared for `HTTPError` *or* `URLError` there are two basic approaches. I prefer the second approach. #### Number 1 ``` from urllib.request import Request, urlopen from urllib.error import URLError, HTTPError req = Request(someurl) try: response = urlopen(req) except HTTPError as e: print('The server couldn\'t fulfill the request.') print('Error code: ', e.code) except URLError as e: print('We failed to reach a server.') print('Reason: ', e.reason) else: # everything is fine ``` Note The `except HTTPError` *must* come first, otherwise `except URLError` will *also* catch an `HTTPError`. #### Number 2 ``` from urllib.request import Request, urlopen from urllib.error import URLError req = Request(someurl) try: response = urlopen(req) except URLError as e: if hasattr(e, 'reason'): print('We failed to reach a server.') print('Reason: ', e.reason) elif hasattr(e, 'code'): print('The server couldn\'t fulfill the request.') print('Error code: ', e.code) else: # everything is fine ``` info and geturl --------------- The response returned by urlopen (or the `HTTPError` instance) has two useful methods `info()` and `geturl()` and is defined in the module [`urllib.response`](../library/urllib.request#module-urllib.response "urllib.response: Response classes used by urllib.").. **geturl** - this returns the real URL of the page fetched. This is useful because `urlopen` (or the opener object used) may have followed a redirect. The URL of the page fetched may not be the same as the URL requested. **info** - this returns a dictionary-like object that describes the page fetched, particularly the headers sent by the server. It is currently an `http.client.HTTPMessage` instance. Typical headers include ‘Content-length’, ‘Content-type’, and so on. See the [Quick Reference to HTTP Headers](http://jkorpela.fi/http.html) for a useful listing of HTTP headers with brief explanations of their meaning and use. Openers and Handlers -------------------- When you fetch a URL you use an opener (an instance of the perhaps confusingly-named [`urllib.request.OpenerDirector`](../library/urllib.request#urllib.request.OpenerDirector "urllib.request.OpenerDirector")). Normally we have been using the default opener - via `urlopen` - but you can create custom openers. Openers use handlers. All the “heavy lifting” is done by the handlers. Each handler knows how to open URLs for a particular URL scheme (http, ftp, etc.), or how to handle an aspect of URL opening, for example HTTP redirections or HTTP cookies. You will want to create openers if you want to fetch URLs with specific handlers installed, for example to get an opener that handles cookies, or to get an opener that does not handle redirections. To create an opener, instantiate an `OpenerDirector`, and then call `.add_handler(some_handler_instance)` repeatedly. Alternatively, you can use `build_opener`, which is a convenience function for creating opener objects with a single function call. `build_opener` adds several handlers by default, but provides a quick way to add more and/or override the default handlers. Other sorts of handlers you might want to can handle proxies, authentication, and other common but slightly specialised situations. `install_opener` can be used to make an `opener` object the (global) default opener. This means that calls to `urlopen` will use the opener you have installed. Opener objects have an `open` method, which can be called directly to fetch urls in the same way as the `urlopen` function: there’s no need to call `install_opener`, except as a convenience. Basic Authentication -------------------- To illustrate creating and installing a handler we will use the `HTTPBasicAuthHandler`. For a more detailed discussion of this subject – including an explanation of how Basic Authentication works - see the [Basic Authentication Tutorial](http://www.voidspace.org.uk/python/articles/authentication.shtml). When authentication is required, the server sends a header (as well as the 401 error code) requesting authentication. This specifies the authentication scheme and a ‘realm’. The header looks like: `WWW-Authenticate: SCHEME realm="REALM"`. e.g. ``` WWW-Authenticate: Basic realm="cPanel Users" ``` The client should then retry the request with the appropriate name and password for the realm included as a header in the request. This is ‘basic authentication’. In order to simplify this process we can create an instance of `HTTPBasicAuthHandler` and an opener to use this handler. The `HTTPBasicAuthHandler` uses an object called a password manager to handle the mapping of URLs and realms to passwords and usernames. If you know what the realm is (from the authentication header sent by the server), then you can use a `HTTPPasswordMgr`. Frequently one doesn’t care what the realm is. In that case, it is convenient to use `HTTPPasswordMgrWithDefaultRealm`. This allows you to specify a default username and password for a URL. This will be supplied in the absence of you providing an alternative combination for a specific realm. We indicate this by providing `None` as the realm argument to the `add_password` method. The top-level URL is the first URL that requires authentication. URLs “deeper” than the URL you pass to .add\_password() will also match. ``` # create a password manager password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm() # Add the username and password. # If we knew the realm, we could use it instead of None. top_level_url = "http://example.com/foo/" password_mgr.add_password(None, top_level_url, username, password) handler = urllib.request.HTTPBasicAuthHandler(password_mgr) # create "opener" (OpenerDirector instance) opener = urllib.request.build_opener(handler) # use the opener to fetch a URL opener.open(a_url) # Install the opener. # Now all calls to urllib.request.urlopen use our opener. urllib.request.install_opener(opener) ``` Note In the above example we only supplied our `HTTPBasicAuthHandler` to `build_opener`. By default openers have the handlers for normal situations – `ProxyHandler` (if a proxy setting such as an `http_proxy` environment variable is set), `UnknownHandler`, `HTTPHandler`, `HTTPDefaultErrorHandler`, `HTTPRedirectHandler`, `FTPHandler`, `FileHandler`, `DataHandler`, `HTTPErrorProcessor`. `top_level_url` is in fact *either* a full URL (including the ‘http:’ scheme component and the hostname and optionally the port number) e.g. `"http://example.com/"` *or* an “authority” (i.e. the hostname, optionally including the port number) e.g. `"example.com"` or `"example.com:8080"` (the latter example includes a port number). The authority, if present, must NOT contain the “userinfo” component - for example `"joe:[email protected]"` is not correct. Proxies ------- **urllib** will auto-detect your proxy settings and use those. This is through the `ProxyHandler`, which is part of the normal handler chain when a proxy setting is detected. Normally that’s a good thing, but there are occasions when it may not be helpful [5](#id12). One way to do this is to setup our own `ProxyHandler`, with no proxies defined. This is done using similar steps to setting up a [Basic Authentication](http://www.voidspace.org.uk/python/articles/authentication.shtml) handler: ``` >>> proxy_support = urllib.request.ProxyHandler({}) >>> opener = urllib.request.build_opener(proxy_support) >>> urllib.request.install_opener(opener) ``` Note Currently `urllib.request` *does not* support fetching of `https` locations through a proxy. However, this can be enabled by extending urllib.request as shown in the recipe [6](#id13). Note `HTTP_PROXY` will be ignored if a variable `REQUEST_METHOD` is set; see the documentation on [`getproxies()`](../library/urllib.request#urllib.request.getproxies "urllib.request.getproxies"). Sockets and Layers ------------------ The Python support for fetching resources from the web is layered. urllib uses the [`http.client`](../library/http.client#module-http.client "http.client: HTTP and HTTPS protocol client (requires sockets).") library, which in turn uses the socket library. As of Python 2.3 you can specify how long a socket should wait for a response before timing out. This can be useful in applications which have to fetch web pages. By default the socket module has *no timeout* and can hang. Currently, the socket timeout is not exposed at the http.client or urllib.request levels. However, you can set the default timeout globally for all sockets using ``` import socket import urllib.request # timeout in seconds timeout = 10 socket.setdefaulttimeout(timeout) # this call to urllib.request.urlopen now uses the default timeout # we have set in the socket module req = urllib.request.Request('http://www.voidspace.org.uk') response = urllib.request.urlopen(req) ``` Footnotes --------- This document was reviewed and revised by John Lee. `1` Google for example. `2` Browser sniffing is a very bad practice for website design - building sites using web standards is much more sensible. Unfortunately a lot of sites still send different versions to different browsers. `3` The user agent for MSIE 6 is *‘Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)’* `4` For details of more HTTP request headers, see [Quick Reference to HTTP Headers](http://jkorpela.fi/http.html). `5` In my case I have to use a proxy to access the internet at work. If you attempt to fetch *localhost* URLs through this proxy it blocks them. IE is set to use the proxy, which urllib picks up on. In order to test scripts with a localhost server, I have to prevent urllib from using the proxy. `6` urllib opener for SSL proxy (CONNECT method): [ASPN Cookbook Recipe](https://code.activestate.com/recipes/456195/).
programming_docs
python Functional Programming HOWTO Functional Programming HOWTO ============================ Author A. M. Kuchling Release 0.32 In this document, we’ll take a tour of Python’s features suitable for implementing programs in a functional style. After an introduction to the concepts of functional programming, we’ll look at language features such as [iterator](../glossary#term-iterator)s and [generator](../glossary#term-generator)s and relevant library modules such as [`itertools`](../library/itertools#module-itertools "itertools: Functions creating iterators for efficient looping.") and [`functools`](../library/functools#module-functools "functools: Higher-order functions and operations on callable objects."). Introduction ------------ This section explains the basic concept of functional programming; if you’re just interested in learning about Python language features, skip to the next section on [Iterators](#functional-howto-iterators). Programming languages support decomposing problems in several different ways: * Most programming languages are **procedural**: programs are lists of instructions that tell the computer what to do with the program’s input. C, Pascal, and even Unix shells are procedural languages. * In **declarative** languages, you write a specification that describes the problem to be solved, and the language implementation figures out how to perform the computation efficiently. SQL is the declarative language you’re most likely to be familiar with; a SQL query describes the data set you want to retrieve, and the SQL engine decides whether to scan tables or use indexes, which subclauses should be performed first, etc. * **Object-oriented** programs manipulate collections of objects. Objects have internal state and support methods that query or modify this internal state in some way. Smalltalk and Java are object-oriented languages. C++ and Python are languages that support object-oriented programming, but don’t force the use of object-oriented features. * **Functional** programming decomposes a problem into a set of functions. Ideally, functions only take inputs and produce outputs, and don’t have any internal state that affects the output produced for a given input. Well-known functional languages include the ML family (Standard ML, OCaml, and other variants) and Haskell. The designers of some computer languages choose to emphasize one particular approach to programming. This often makes it difficult to write programs that use a different approach. Other languages are multi-paradigm languages that support several different approaches. Lisp, C++, and Python are multi-paradigm; you can write programs or libraries that are largely procedural, object-oriented, or functional in all of these languages. In a large program, different sections might be written using different approaches; the GUI might be object-oriented while the processing logic is procedural or functional, for example. In a functional program, input flows through a set of functions. Each function operates on its input and produces some output. Functional style discourages functions with side effects that modify internal state or make other changes that aren’t visible in the function’s return value. Functions that have no side effects at all are called **purely functional**. Avoiding side effects means not using data structures that get updated as a program runs; every function’s output must only depend on its input. Some languages are very strict about purity and don’t even have assignment statements such as `a=3` or `c = a + b`, but it’s difficult to avoid all side effects, such as printing to the screen or writing to a disk file. Another example is a call to the [`print()`](../library/functions#print "print") or [`time.sleep()`](../library/time#time.sleep "time.sleep") function, neither of which returns a useful value. Both are called only for their side effects of sending some text to the screen or pausing execution for a second. Python programs written in functional style usually won’t go to the extreme of avoiding all I/O or all assignments; instead, they’ll provide a functional-appearing interface but will use non-functional features internally. For example, the implementation of a function will still use assignments to local variables, but won’t modify global variables or have other side effects. Functional programming can be considered the opposite of object-oriented programming. Objects are little capsules containing some internal state along with a collection of method calls that let you modify this state, and programs consist of making the right set of state changes. Functional programming wants to avoid state changes as much as possible and works with data flowing between functions. In Python you might combine the two approaches by writing functions that take and return instances representing objects in your application (e-mail messages, transactions, etc.). Functional design may seem like an odd constraint to work under. Why should you avoid objects and side effects? There are theoretical and practical advantages to the functional style: * Formal provability. * Modularity. * Composability. * Ease of debugging and testing. ### Formal provability A theoretical benefit is that it’s easier to construct a mathematical proof that a functional program is correct. For a long time researchers have been interested in finding ways to mathematically prove programs correct. This is different from testing a program on numerous inputs and concluding that its output is usually correct, or reading a program’s source code and concluding that the code looks right; the goal is instead a rigorous proof that a program produces the right result for all possible inputs. The technique used to prove programs correct is to write down **invariants**, properties of the input data and of the program’s variables that are always true. For each line of code, you then show that if invariants X and Y are true **before** the line is executed, the slightly different invariants X’ and Y’ are true **after** the line is executed. This continues until you reach the end of the program, at which point the invariants should match the desired conditions on the program’s output. Functional programming’s avoidance of assignments arose because assignments are difficult to handle with this technique; assignments can break invariants that were true before the assignment without producing any new invariants that can be propagated onward. Unfortunately, proving programs correct is largely impractical and not relevant to Python software. Even trivial programs require proofs that are several pages long; the proof of correctness for a moderately complicated program would be enormous, and few or none of the programs you use daily (the Python interpreter, your XML parser, your web browser) could be proven correct. Even if you wrote down or generated a proof, there would then be the question of verifying the proof; maybe there’s an error in it, and you wrongly believe you’ve proved the program correct. ### Modularity A more practical benefit of functional programming is that it forces you to break apart your problem into small pieces. Programs are more modular as a result. It’s easier to specify and write a small function that does one thing than a large function that performs a complicated transformation. Small functions are also easier to read and to check for errors. ### Ease of debugging and testing Testing and debugging a functional-style program is easier. Debugging is simplified because functions are generally small and clearly specified. When a program doesn’t work, each function is an interface point where you can check that the data are correct. You can look at the intermediate inputs and outputs to quickly isolate the function that’s responsible for a bug. Testing is easier because each function is a potential subject for a unit test. Functions don’t depend on system state that needs to be replicated before running a test; instead you only have to synthesize the right input and then check that the output matches expectations. ### Composability As you work on a functional-style program, you’ll write a number of functions with varying inputs and outputs. Some of these functions will be unavoidably specialized to a particular application, but others will be useful in a wide variety of programs. For example, a function that takes a directory path and returns all the XML files in the directory, or a function that takes a filename and returns its contents, can be applied to many different situations. Over time you’ll form a personal library of utilities. Often you’ll assemble new programs by arranging existing functions in a new configuration and writing a few functions specialized for the current task. Iterators --------- I’ll start by looking at a Python language feature that’s an important foundation for writing functional-style programs: iterators. An iterator is an object representing a stream of data; this object returns the data one element at a time. A Python iterator must support a method called [`__next__()`](../library/stdtypes#iterator.__next__ "iterator.__next__") that takes no arguments and always returns the next element of the stream. If there are no more elements in the stream, [`__next__()`](../library/stdtypes#iterator.__next__ "iterator.__next__") must raise the [`StopIteration`](../library/exceptions#StopIteration "StopIteration") exception. Iterators don’t have to be finite, though; it’s perfectly reasonable to write an iterator that produces an infinite stream of data. The built-in [`iter()`](../library/functions#iter "iter") function takes an arbitrary object and tries to return an iterator that will return the object’s contents or elements, raising [`TypeError`](../library/exceptions#TypeError "TypeError") if the object doesn’t support iteration. Several of Python’s built-in data types support iteration, the most common being lists and dictionaries. An object is called [iterable](../glossary#term-iterable) if you can get an iterator for it. You can experiment with the iteration interface manually: ``` >>> L = [1, 2, 3] >>> it = iter(L) >>> it <...iterator object at ...> >>> it.__next__() # same as next(it) 1 >>> next(it) 2 >>> next(it) 3 >>> next(it) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>> ``` Python expects iterable objects in several different contexts, the most important being the [`for`](../reference/compound_stmts#for) statement. In the statement `for X in Y`, Y must be an iterator or some object for which [`iter()`](../library/functions#iter "iter") can create an iterator. These two statements are equivalent: ``` for i in iter(obj): print(i) for i in obj: print(i) ``` Iterators can be materialized as lists or tuples by using the [`list()`](../library/stdtypes#list "list") or [`tuple()`](../library/stdtypes#tuple "tuple") constructor functions: ``` >>> L = [1, 2, 3] >>> iterator = iter(L) >>> t = tuple(iterator) >>> t (1, 2, 3) ``` Sequence unpacking also supports iterators: if you know an iterator will return N elements, you can unpack them into an N-tuple: ``` >>> L = [1, 2, 3] >>> iterator = iter(L) >>> a, b, c = iterator >>> a, b, c (1, 2, 3) ``` Built-in functions such as [`max()`](../library/functions#max "max") and [`min()`](../library/functions#min "min") can take a single iterator argument and will return the largest or smallest element. The `"in"` and `"not in"` operators also support iterators: `X in iterator` is true if X is found in the stream returned by the iterator. You’ll run into obvious problems if the iterator is infinite; [`max()`](../library/functions#max "max"), [`min()`](../library/functions#min "min") will never return, and if the element X never appears in the stream, the `"in"` and `"not in"` operators won’t return either. Note that you can only go forward in an iterator; there’s no way to get the previous element, reset the iterator, or make a copy of it. Iterator objects can optionally provide these additional capabilities, but the iterator protocol only specifies the [`__next__()`](../library/stdtypes#iterator.__next__ "iterator.__next__") method. Functions may therefore consume all of the iterator’s output, and if you need to do something different with the same stream, you’ll have to create a new iterator. ### Data Types That Support Iterators We’ve already seen how lists and tuples support iterators. In fact, any Python sequence type, such as strings, will automatically support creation of an iterator. Calling [`iter()`](../library/functions#iter "iter") on a dictionary returns an iterator that will loop over the dictionary’s keys: ``` >>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6, ... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12} >>> for key in m: ... print(key, m[key]) Jan 1 Feb 2 Mar 3 Apr 4 May 5 Jun 6 Jul 7 Aug 8 Sep 9 Oct 10 Nov 11 Dec 12 ``` Note that starting with Python 3.7, dictionary iteration order is guaranteed to be the same as the insertion order. In earlier versions, the behaviour was unspecified and could vary between implementations. Applying [`iter()`](../library/functions#iter "iter") to a dictionary always loops over the keys, but dictionaries have methods that return other iterators. If you want to iterate over values or key/value pairs, you can explicitly call the [`values()`](../library/stdtypes#dict.values "dict.values") or [`items()`](../library/stdtypes#dict.items "dict.items") methods to get an appropriate iterator. The [`dict()`](../library/stdtypes#dict "dict") constructor can accept an iterator that returns a finite stream of `(key, value)` tuples: ``` >>> L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')] >>> dict(iter(L)) {'Italy': 'Rome', 'France': 'Paris', 'US': 'Washington DC'} ``` Files also support iteration by calling the [`readline()`](../library/io#io.TextIOBase.readline "io.TextIOBase.readline") method until there are no more lines in the file. This means you can read each line of a file like this: ``` for line in file: # do something for each line ... ``` Sets can take their contents from an iterable and let you iterate over the set’s elements: ``` S = {2, 3, 5, 7, 11, 13} for i in S: print(i) ``` Generator expressions and list comprehensions --------------------------------------------- Two common operations on an iterator’s output are 1) performing some operation for every element, 2) selecting a subset of elements that meet some condition. For example, given a list of strings, you might want to strip off trailing whitespace from each line or extract all the strings containing a given substring. List comprehensions and generator expressions (short form: “listcomps” and “genexps”) are a concise notation for such operations, borrowed from the functional programming language Haskell (<https://www.haskell.org/>). You can strip all the whitespace from a stream of strings with the following code: ``` line_list = [' line 1\n', 'line 2 \n', ...] # Generator expression -- returns iterator stripped_iter = (line.strip() for line in line_list) # List comprehension -- returns list stripped_list = [line.strip() for line in line_list] ``` You can select only certain elements by adding an `"if"` condition: ``` stripped_list = [line.strip() for line in line_list if line != ""] ``` With a list comprehension, you get back a Python list; `stripped_list` is a list containing the resulting lines, not an iterator. Generator expressions return an iterator that computes the values as necessary, not needing to materialize all the values at once. This means that list comprehensions aren’t useful if you’re working with iterators that return an infinite stream or a very large amount of data. Generator expressions are preferable in these situations. Generator expressions are surrounded by parentheses (“()”) and list comprehensions are surrounded by square brackets (“[]”). Generator expressions have the form: ``` ( expression for expr in sequence1 if condition1 for expr2 in sequence2 if condition2 for expr3 in sequence3 ... if condition3 for exprN in sequenceN if conditionN ) ``` Again, for a list comprehension only the outside brackets are different (square brackets instead of parentheses). The elements of the generated output will be the successive values of `expression`. The `if` clauses are all optional; if present, `expression` is only evaluated and added to the result when `condition` is true. Generator expressions always have to be written inside parentheses, but the parentheses signalling a function call also count. If you want to create an iterator that will be immediately passed to a function you can write: ``` obj_total = sum(obj.count for obj in list_all_objects()) ``` The `for...in` clauses contain the sequences to be iterated over. The sequences do not have to be the same length, because they are iterated over from left to right, **not** in parallel. For each element in `sequence1`, `sequence2` is looped over from the beginning. `sequence3` is then looped over for each resulting pair of elements from `sequence1` and `sequence2`. To put it another way, a list comprehension or generator expression is equivalent to the following Python code: ``` for expr1 in sequence1: if not (condition1): continue # Skip this element for expr2 in sequence2: if not (condition2): continue # Skip this element ... for exprN in sequenceN: if not (conditionN): continue # Skip this element # Output the value of # the expression. ``` This means that when there are multiple `for...in` clauses but no `if` clauses, the length of the resulting output will be equal to the product of the lengths of all the sequences. If you have two lists of length 3, the output list is 9 elements long: ``` >>> seq1 = 'abc' >>> seq2 = (1, 2, 3) >>> [(x, y) for x in seq1 for y in seq2] [('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1), ('c', 2), ('c', 3)] ``` To avoid introducing an ambiguity into Python’s grammar, if `expression` is creating a tuple, it must be surrounded with parentheses. The first list comprehension below is a syntax error, while the second one is correct: ``` # Syntax error [x, y for x in seq1 for y in seq2] # Correct [(x, y) for x in seq1 for y in seq2] ``` Generators ---------- Generators are a special class of functions that simplify the task of writing iterators. Regular functions compute a value and return it, but generators return an iterator that returns a stream of values. You’re doubtless familiar with how regular function calls work in Python or C. When you call a function, it gets a private namespace where its local variables are created. When the function reaches a `return` statement, the local variables are destroyed and the value is returned to the caller. A later call to the same function creates a new private namespace and a fresh set of local variables. But, what if the local variables weren’t thrown away on exiting a function? What if you could later resume the function where it left off? This is what generators provide; they can be thought of as resumable functions. Here’s the simplest example of a generator function: ``` >>> def generate_ints(N): ... for i in range(N): ... yield i ``` Any function containing a [`yield`](../reference/simple_stmts#yield) keyword is a generator function; this is detected by Python’s [bytecode](../glossary#term-bytecode) compiler which compiles the function specially as a result. When you call a generator function, it doesn’t return a single value; instead it returns a generator object that supports the iterator protocol. On executing the `yield` expression, the generator outputs the value of `i`, similar to a `return` statement. The big difference between `yield` and a `return` statement is that on reaching a `yield` the generator’s state of execution is suspended and local variables are preserved. On the next call to the generator’s [`__next__()`](../reference/expressions#generator.__next__ "generator.__next__") method, the function will resume executing. Here’s a sample usage of the `generate_ints()` generator: ``` >>> gen = generate_ints(3) >>> gen <generator object generate_ints at ...> >>> next(gen) 0 >>> next(gen) 1 >>> next(gen) 2 >>> next(gen) Traceback (most recent call last): File "stdin", line 1, in <module> File "stdin", line 2, in generate_ints StopIteration ``` You could equally write `for i in generate_ints(5)`, or `a, b, c = generate_ints(3)`. Inside a generator function, `return value` causes `StopIteration(value)` to be raised from the [`__next__()`](../reference/expressions#generator.__next__ "generator.__next__") method. Once this happens, or the bottom of the function is reached, the procession of values ends and the generator cannot yield any further values. You could achieve the effect of generators manually by writing your own class and storing all the local variables of the generator as instance variables. For example, returning a list of integers could be done by setting `self.count` to 0, and having the [`__next__()`](../library/stdtypes#iterator.__next__ "iterator.__next__") method increment `self.count` and return it. However, for a moderately complicated generator, writing a corresponding class can be much messier. The test suite included with Python’s library, [Lib/test/test\_generators.py](https://github.com/python/cpython/tree/3.9/Lib/test/test_generators.py), contains a number of more interesting examples. Here’s one generator that implements an in-order traversal of a tree using generators recursively. ``` # A recursive generator that generates Tree leaves in in-order. def inorder(t): if t: for x in inorder(t.left): yield x yield t.label for x in inorder(t.right): yield x ``` Two other examples in `test_generators.py` produce solutions for the N-Queens problem (placing N queens on an NxN chess board so that no queen threatens another) and the Knight’s Tour (finding a route that takes a knight to every square of an NxN chessboard without visiting any square twice). ### Passing values into a generator In Python 2.4 and earlier, generators only produced output. Once a generator’s code was invoked to create an iterator, there was no way to pass any new information into the function when its execution is resumed. You could hack together this ability by making the generator look at a global variable or by passing in some mutable object that callers then modify, but these approaches are messy. In Python 2.5 there’s a simple way to pass values into a generator. [`yield`](../reference/simple_stmts#yield) became an expression, returning a value that can be assigned to a variable or otherwise operated on: ``` val = (yield i) ``` I recommend that you **always** put parentheses around a `yield` expression when you’re doing something with the returned value, as in the above example. The parentheses aren’t always necessary, but it’s easier to always add them instead of having to remember when they’re needed. ([**PEP 342**](https://www.python.org/dev/peps/pep-0342) explains the exact rules, which are that a `yield`-expression must always be parenthesized except when it occurs at the top-level expression on the right-hand side of an assignment. This means you can write `val = yield i` but have to use parentheses when there’s an operation, as in `val = (yield i) + 12`.) Values are sent into a generator by calling its [`send(value)`](../reference/expressions#generator.send "generator.send") method. This method resumes the generator’s code and the `yield` expression returns the specified value. If the regular [`__next__()`](../reference/expressions#generator.__next__ "generator.__next__") method is called, the `yield` returns `None`. Here’s a simple counter that increments by 1 and allows changing the value of the internal counter. ``` def counter(maximum): i = 0 while i < maximum: val = (yield i) # If value provided, change counter if val is not None: i = val else: i += 1 ``` And here’s an example of changing the counter: ``` >>> it = counter(10) >>> next(it) 0 >>> next(it) 1 >>> it.send(8) 8 >>> next(it) 9 >>> next(it) Traceback (most recent call last): File "t.py", line 15, in <module> it.next() StopIteration ``` Because `yield` will often be returning `None`, you should always check for this case. Don’t just use its value in expressions unless you’re sure that the [`send()`](../reference/expressions#generator.send "generator.send") method will be the only method used to resume your generator function. In addition to [`send()`](../reference/expressions#generator.send "generator.send"), there are two other methods on generators: * [`throw(value)`](../reference/expressions#generator.throw "generator.throw") is used to raise an exception inside the generator; the exception is raised by the `yield` expression where the generator’s execution is paused. * [`close()`](../reference/expressions#generator.close "generator.close") raises a [`GeneratorExit`](../library/exceptions#GeneratorExit "GeneratorExit") exception inside the generator to terminate the iteration. On receiving this exception, the generator’s code must either raise [`GeneratorExit`](../library/exceptions#GeneratorExit "GeneratorExit") or [`StopIteration`](../library/exceptions#StopIteration "StopIteration"); catching the exception and doing anything else is illegal and will trigger a [`RuntimeError`](../library/exceptions#RuntimeError "RuntimeError"). [`close()`](../reference/expressions#generator.close "generator.close") will also be called by Python’s garbage collector when the generator is garbage-collected. If you need to run cleanup code when a [`GeneratorExit`](../library/exceptions#GeneratorExit "GeneratorExit") occurs, I suggest using a `try: ... finally:` suite instead of catching [`GeneratorExit`](../library/exceptions#GeneratorExit "GeneratorExit"). The cumulative effect of these changes is to turn generators from one-way producers of information into both producers and consumers. Generators also become **coroutines**, a more generalized form of subroutines. Subroutines are entered at one point and exited at another point (the top of the function, and a `return` statement), but coroutines can be entered, exited, and resumed at many different points (the `yield` statements). Built-in functions ------------------ Let’s look in more detail at built-in functions often used with iterators. Two of Python’s built-in functions, [`map()`](../library/functions#map "map") and [`filter()`](../library/functions#filter "filter") duplicate the features of generator expressions: `map(f, iterA, iterB, ...) returns an iterator over the sequence` `f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...`. ``` >>> def upper(s): ... return s.upper() ``` ``` >>> list(map(upper, ['sentence', 'fragment'])) ['SENTENCE', 'FRAGMENT'] >>> [upper(s) for s in ['sentence', 'fragment']] ['SENTENCE', 'FRAGMENT'] ``` You can of course achieve the same effect with a list comprehension. [`filter(predicate, iter)`](../library/functions#filter "filter") returns an iterator over all the sequence elements that meet a certain condition, and is similarly duplicated by list comprehensions. A **predicate** is a function that returns the truth value of some condition; for use with [`filter()`](../library/functions#filter "filter"), the predicate must take a single value. ``` >>> def is_even(x): ... return (x % 2) == 0 ``` ``` >>> list(filter(is_even, range(10))) [0, 2, 4, 6, 8] ``` This can also be written as a list comprehension: ``` >>> list(x for x in range(10) if is_even(x)) [0, 2, 4, 6, 8] ``` [`enumerate(iter, start=0)`](../library/functions#enumerate "enumerate") counts off the elements in the iterable returning 2-tuples containing the count (from *start*) and each element. ``` >>> for item in enumerate(['subject', 'verb', 'object']): ... print(item) (0, 'subject') (1, 'verb') (2, 'object') ``` [`enumerate()`](../library/functions#enumerate "enumerate") is often used when looping through a list and recording the indexes at which certain conditions are met: ``` f = open('data.txt', 'r') for i, line in enumerate(f): if line.strip() == '': print('Blank line at line #%i' % i) ``` [`sorted(iterable, key=None, reverse=False)`](../library/functions#sorted "sorted") collects all the elements of the iterable into a list, sorts the list, and returns the sorted result. The *key* and *reverse* arguments are passed through to the constructed list’s [`sort()`](../library/stdtypes#list.sort "list.sort") method. ``` >>> import random >>> # Generate 8 random numbers between [0, 10000) >>> rand_list = random.sample(range(10000), 8) >>> rand_list [769, 7953, 9828, 6431, 8442, 9878, 6213, 2207] >>> sorted(rand_list) [769, 2207, 6213, 6431, 7953, 8442, 9828, 9878] >>> sorted(rand_list, reverse=True) [9878, 9828, 8442, 7953, 6431, 6213, 2207, 769] ``` (For a more detailed discussion of sorting, see the [Sorting HOW TO](sorting#sortinghowto).) The [`any(iter)`](../library/functions#any "any") and [`all(iter)`](../library/functions#all "all") built-ins look at the truth values of an iterable’s contents. [`any()`](../library/functions#any "any") returns `True` if any element in the iterable is a true value, and [`all()`](../library/functions#all "all") returns `True` if all of the elements are true values: ``` >>> any([0, 1, 0]) True >>> any([0, 0, 0]) False >>> any([1, 1, 1]) True >>> all([0, 1, 0]) False >>> all([0, 0, 0]) False >>> all([1, 1, 1]) True ``` [`zip(iterA, iterB, ...)`](../library/functions#zip "zip") takes one element from each iterable and returns them in a tuple: ``` zip(['a', 'b', 'c'], (1, 2, 3)) => ('a', 1), ('b', 2), ('c', 3) ``` It doesn’t construct an in-memory list and exhaust all the input iterators before returning; instead tuples are constructed and returned only if they’re requested. (The technical term for this behaviour is [lazy evaluation](https://en.wikipedia.org/wiki/Lazy_evaluation).) This iterator is intended to be used with iterables that are all of the same length. If the iterables are of different lengths, the resulting stream will be the same length as the shortest iterable. ``` zip(['a', 'b'], (1, 2, 3)) => ('a', 1), ('b', 2) ``` You should avoid doing this, though, because an element may be taken from the longer iterators and discarded. This means you can’t go on to use the iterators further because you risk skipping a discarded element. The itertools module -------------------- The [`itertools`](../library/itertools#module-itertools "itertools: Functions creating iterators for efficient looping.") module contains a number of commonly-used iterators as well as functions for combining several iterators. This section will introduce the module’s contents by showing small examples. The module’s functions fall into a few broad classes: * Functions that create a new iterator based on an existing iterator. * Functions for treating an iterator’s elements as function arguments. * Functions for selecting portions of an iterator’s output. * A function for grouping an iterator’s output. ### Creating new iterators [`itertools.count(start, step)`](../library/itertools#itertools.count "itertools.count") returns an infinite stream of evenly spaced values. You can optionally supply the starting number, which defaults to 0, and the interval between numbers, which defaults to 1: ``` itertools.count() => 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... itertools.count(10) => 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ... itertools.count(10, 5) => 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, ... ``` [`itertools.cycle(iter)`](../library/itertools#itertools.cycle "itertools.cycle") saves a copy of the contents of a provided iterable and returns a new iterator that returns its elements from first to last. The new iterator will repeat these elements infinitely. ``` itertools.cycle([1, 2, 3, 4, 5]) => 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ... ``` [`itertools.repeat(elem, [n])`](../library/itertools#itertools.repeat "itertools.repeat") returns the provided element *n* times, or returns the element endlessly if *n* is not provided. ``` itertools.repeat('abc') => abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ... itertools.repeat('abc', 5) => abc, abc, abc, abc, abc ``` [`itertools.chain(iterA, iterB, ...)`](../library/itertools#itertools.chain "itertools.chain") takes an arbitrary number of iterables as input, and returns all the elements of the first iterator, then all the elements of the second, and so on, until all of the iterables have been exhausted. ``` itertools.chain(['a', 'b', 'c'], (1, 2, 3)) => a, b, c, 1, 2, 3 ``` [`itertools.islice(iter, [start], stop, [step])`](../library/itertools#itertools.islice "itertools.islice") returns a stream that’s a slice of the iterator. With a single *stop* argument, it will return the first *stop* elements. If you supply a starting index, you’ll get *stop-start* elements, and if you supply a value for *step*, elements will be skipped accordingly. Unlike Python’s string and list slicing, you can’t use negative values for *start*, *stop*, or *step*. ``` itertools.islice(range(10), 8) => 0, 1, 2, 3, 4, 5, 6, 7 itertools.islice(range(10), 2, 8) => 2, 3, 4, 5, 6, 7 itertools.islice(range(10), 2, 8, 2) => 2, 4, 6 ``` [`itertools.tee(iter, [n])`](../library/itertools#itertools.tee "itertools.tee") replicates an iterator; it returns *n* independent iterators that will all return the contents of the source iterator. If you don’t supply a value for *n*, the default is 2. Replicating iterators requires saving some of the contents of the source iterator, so this can consume significant memory if the iterator is large and one of the new iterators is consumed more than the others. ``` itertools.tee( itertools.count() ) => iterA, iterB where iterA -> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... and iterB -> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... ``` ### Calling functions on elements The [`operator`](../library/operator#module-operator "operator: Functions corresponding to the standard operators.") module contains a set of functions corresponding to Python’s operators. Some examples are [`operator.add(a, b)`](../library/operator#operator.add "operator.add") (adds two values), [`operator.ne(a, b)`](../library/operator#operator.ne "operator.ne") (same as `a != b`), and [`operator.attrgetter('id')`](../library/operator#operator.attrgetter "operator.attrgetter") (returns a callable that fetches the `.id` attribute). [`itertools.starmap(func, iter)`](../library/itertools#itertools.starmap "itertools.starmap") assumes that the iterable will return a stream of tuples, and calls *func* using these tuples as the arguments: ``` itertools.starmap(os.path.join, [('/bin', 'python'), ('/usr', 'bin', 'java'), ('/usr', 'bin', 'perl'), ('/usr', 'bin', 'ruby')]) => /bin/python, /usr/bin/java, /usr/bin/perl, /usr/bin/ruby ``` ### Selecting elements Another group of functions chooses a subset of an iterator’s elements based on a predicate. [`itertools.filterfalse(predicate, iter)`](../library/itertools#itertools.filterfalse "itertools.filterfalse") is the opposite of [`filter()`](../library/functions#filter "filter"), returning all elements for which the predicate returns false: ``` itertools.filterfalse(is_even, itertools.count()) => 1, 3, 5, 7, 9, 11, 13, 15, ... ``` [`itertools.takewhile(predicate, iter)`](../library/itertools#itertools.takewhile "itertools.takewhile") returns elements for as long as the predicate returns true. Once the predicate returns false, the iterator will signal the end of its results. ``` def less_than_10(x): return x < 10 itertools.takewhile(less_than_10, itertools.count()) => 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 itertools.takewhile(is_even, itertools.count()) => 0 ``` [`itertools.dropwhile(predicate, iter)`](../library/itertools#itertools.dropwhile "itertools.dropwhile") discards elements while the predicate returns true, and then returns the rest of the iterable’s results. ``` itertools.dropwhile(less_than_10, itertools.count()) => 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ... itertools.dropwhile(is_even, itertools.count()) => 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ... ``` [`itertools.compress(data, selectors)`](../library/itertools#itertools.compress "itertools.compress") takes two iterators and returns only those elements of *data* for which the corresponding element of *selectors* is true, stopping whenever either one is exhausted: ``` itertools.compress([1, 2, 3, 4, 5], [True, True, False, False, True]) => 1, 2, 5 ``` ### Combinatoric functions The [`itertools.combinations(iterable, r)`](../library/itertools#itertools.combinations "itertools.combinations") returns an iterator giving all possible *r*-tuple combinations of the elements contained in *iterable*. ``` itertools.combinations([1, 2, 3, 4, 5], 2) => (1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5) itertools.combinations([1, 2, 3, 4, 5], 3) => (1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5), (2, 4, 5), (3, 4, 5) ``` The elements within each tuple remain in the same order as *iterable* returned them. For example, the number 1 is always before 2, 3, 4, or 5 in the examples above. A similar function, [`itertools.permutations(iterable, r=None)`](../library/itertools#itertools.permutations "itertools.permutations"), removes this constraint on the order, returning all possible arrangements of length *r*: ``` itertools.permutations([1, 2, 3, 4, 5], 2) => (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4) itertools.permutations([1, 2, 3, 4, 5]) => (1, 2, 3, 4, 5), (1, 2, 3, 5, 4), (1, 2, 4, 3, 5), ... (5, 4, 3, 2, 1) ``` If you don’t supply a value for *r* the length of the iterable is used, meaning that all the elements are permuted. Note that these functions produce all of the possible combinations by position and don’t require that the contents of *iterable* are unique: ``` itertools.permutations('aba', 3) => ('a', 'b', 'a'), ('a', 'a', 'b'), ('b', 'a', 'a'), ('b', 'a', 'a'), ('a', 'a', 'b'), ('a', 'b', 'a') ``` The identical tuple `('a', 'a', 'b')` occurs twice, but the two ‘a’ strings came from different positions. The [`itertools.combinations_with_replacement(iterable, r)`](../library/itertools#itertools.combinations_with_replacement "itertools.combinations_with_replacement") function relaxes a different constraint: elements can be repeated within a single tuple. Conceptually an element is selected for the first position of each tuple and then is replaced before the second element is selected. ``` itertools.combinations_with_replacement([1, 2, 3, 4, 5], 2) => (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 3), (3, 4), (3, 5), (4, 4), (4, 5), (5, 5) ``` ### Grouping elements The last function I’ll discuss, [`itertools.groupby(iter, key_func=None)`](../library/itertools#itertools.groupby "itertools.groupby"), is the most complicated. `key_func(elem)` is a function that can compute a key value for each element returned by the iterable. If you don’t supply a key function, the key is simply each element itself. [`groupby()`](../library/itertools#itertools.groupby "itertools.groupby") collects all the consecutive elements from the underlying iterable that have the same key value, and returns a stream of 2-tuples containing a key value and an iterator for the elements with that key. ``` city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'), ('Anchorage', 'AK'), ('Nome', 'AK'), ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'), ... ] def get_state(city_state): return city_state[1] itertools.groupby(city_list, get_state) => ('AL', iterator-1), ('AK', iterator-2), ('AZ', iterator-3), ... where iterator-1 => ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL') iterator-2 => ('Anchorage', 'AK'), ('Nome', 'AK') iterator-3 => ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ') ``` [`groupby()`](../library/itertools#itertools.groupby "itertools.groupby") assumes that the underlying iterable’s contents will already be sorted based on the key. Note that the returned iterators also use the underlying iterable, so you have to consume the results of iterator-1 before requesting iterator-2 and its corresponding key. The functools module -------------------- The [`functools`](../library/functools#module-functools "functools: Higher-order functions and operations on callable objects.") module in Python 2.5 contains some higher-order functions. A **higher-order function** takes one or more functions as input and returns a new function. The most useful tool in this module is the [`functools.partial()`](../library/functools#functools.partial "functools.partial") function. For programs written in a functional style, you’ll sometimes want to construct variants of existing functions that have some of the parameters filled in. Consider a Python function `f(a, b, c)`; you may wish to create a new function `g(b, c)` that’s equivalent to `f(1, b, c)`; you’re filling in a value for one of `f()`’s parameters. This is called “partial function application”. The constructor for [`partial()`](../library/functools#functools.partial "functools.partial") takes the arguments `(function, arg1, arg2, ..., kwarg1=value1, kwarg2=value2)`. The resulting object is callable, so you can just call it to invoke `function` with the filled-in arguments. Here’s a small but realistic example: ``` import functools def log(message, subsystem): """Write the contents of 'message' to the specified subsystem.""" print('%s: %s' % (subsystem, message)) ... server_log = functools.partial(log, subsystem='server') server_log('Unable to open socket') ``` [`functools.reduce(func, iter, [initial_value])`](../library/functools#functools.reduce "functools.reduce") cumulatively performs an operation on all the iterable’s elements and, therefore, can’t be applied to infinite iterables. *func* must be a function that takes two elements and returns a single value. [`functools.reduce()`](../library/functools#functools.reduce "functools.reduce") takes the first two elements A and B returned by the iterator and calculates `func(A, B)`. It then requests the third element, C, calculates `func(func(A, B), C)`, combines this result with the fourth element returned, and continues until the iterable is exhausted. If the iterable returns no values at all, a [`TypeError`](../library/exceptions#TypeError "TypeError") exception is raised. If the initial value is supplied, it’s used as a starting point and `func(initial_value, A)` is the first calculation. ``` >>> import operator, functools >>> functools.reduce(operator.concat, ['A', 'BB', 'C']) 'ABBC' >>> functools.reduce(operator.concat, []) Traceback (most recent call last): ... TypeError: reduce() of empty sequence with no initial value >>> functools.reduce(operator.mul, [1, 2, 3], 1) 6 >>> functools.reduce(operator.mul, [], 1) 1 ``` If you use [`operator.add()`](../library/operator#operator.add "operator.add") with [`functools.reduce()`](../library/functools#functools.reduce "functools.reduce"), you’ll add up all the elements of the iterable. This case is so common that there’s a special built-in called [`sum()`](../library/functions#sum "sum") to compute it: ``` >>> import functools, operator >>> functools.reduce(operator.add, [1, 2, 3, 4], 0) 10 >>> sum([1, 2, 3, 4]) 10 >>> sum([]) 0 ``` For many uses of [`functools.reduce()`](../library/functools#functools.reduce "functools.reduce"), though, it can be clearer to just write the obvious [`for`](../reference/compound_stmts#for) loop: ``` import functools # Instead of: product = functools.reduce(operator.mul, [1, 2, 3], 1) # You can write: product = 1 for i in [1, 2, 3]: product *= i ``` A related function is [`itertools.accumulate(iterable, func=operator.add)`](../library/itertools#itertools.accumulate "itertools.accumulate"). It performs the same calculation, but instead of returning only the final result, `accumulate()` returns an iterator that also yields each partial result: ``` itertools.accumulate([1, 2, 3, 4, 5]) => 1, 3, 6, 10, 15 itertools.accumulate([1, 2, 3, 4, 5], operator.mul) => 1, 2, 6, 24, 120 ``` ### The operator module The [`operator`](../library/operator#module-operator "operator: Functions corresponding to the standard operators.") module was mentioned earlier. It contains a set of functions corresponding to Python’s operators. These functions are often useful in functional-style code because they save you from writing trivial functions that perform a single operation. Some of the functions in this module are: * Math operations: `add()`, `sub()`, `mul()`, `floordiv()`, `abs()`, … * Logical operations: `not_()`, `truth()`. * Bitwise operations: `and_()`, `or_()`, `invert()`. * Comparisons: `eq()`, `ne()`, `lt()`, `le()`, `gt()`, and `ge()`. * Object identity: `is_()`, `is_not()`. Consult the operator module’s documentation for a complete list. Small functions and the lambda expression ----------------------------------------- When writing functional-style programs, you’ll often need little functions that act as predicates or that combine elements in some way. If there’s a Python built-in or a module function that’s suitable, you don’t need to define a new function at all: ``` stripped_lines = [line.strip() for line in lines] existing_files = filter(os.path.exists, file_list) ``` If the function you need doesn’t exist, you need to write it. One way to write small functions is to use the [`lambda`](../reference/expressions#lambda) expression. `lambda` takes a number of parameters and an expression combining these parameters, and creates an anonymous function that returns the value of the expression: ``` adder = lambda x, y: x+y print_assign = lambda name, value: name + '=' + str(value) ``` An alternative is to just use the `def` statement and define a function in the usual way: ``` def adder(x, y): return x + y def print_assign(name, value): return name + '=' + str(value) ``` Which alternative is preferable? That’s a style question; my usual course is to avoid using `lambda`. One reason for my preference is that `lambda` is quite limited in the functions it can define. The result has to be computable as a single expression, which means you can’t have multiway `if... elif... else` comparisons or `try... except` statements. If you try to do too much in a `lambda` statement, you’ll end up with an overly complicated expression that’s hard to read. Quick, what’s the following code doing? ``` import functools total = functools.reduce(lambda a, b: (0, a[1] + b[1]), items)[1] ``` You can figure it out, but it takes time to disentangle the expression to figure out what’s going on. Using a short nested `def` statements makes things a little bit better: ``` import functools def combine(a, b): return 0, a[1] + b[1] total = functools.reduce(combine, items)[1] ``` But it would be best of all if I had simply used a `for` loop: ``` total = 0 for a, b in items: total += b ``` Or the [`sum()`](../library/functions#sum "sum") built-in and a generator expression: ``` total = sum(b for a, b in items) ``` Many uses of [`functools.reduce()`](../library/functools#functools.reduce "functools.reduce") are clearer when written as `for` loops. Fredrik Lundh once suggested the following set of rules for refactoring uses of `lambda`: 1. Write a lambda function. 2. Write a comment explaining what the heck that lambda does. 3. Study the comment for a while, and think of a name that captures the essence of the comment. 4. Convert the lambda to a def statement, using that name. 5. Remove the comment. I really like these rules, but you’re free to disagree about whether this lambda-free style is better. Revision History and Acknowledgements ------------------------------------- The author would like to thank the following people for offering suggestions, corrections and assistance with various drafts of this article: Ian Bicking, Nick Coghlan, Nick Efford, Raymond Hettinger, Jim Jewett, Mike Krell, Leandro Lameiro, Jussi Salmela, Collin Winter, Blake Winton. Version 0.1: posted June 30 2006. Version 0.11: posted July 1 2006. Typo fixes. Version 0.2: posted July 10 2006. Merged genexp and listcomp sections into one. Typo fixes. Version 0.21: Added more references suggested on the tutor mailing list. Version 0.30: Adds a section on the `functional` module written by Collin Winter; adds short section on the operator module; a few other edits. References ---------- ### General **Structure and Interpretation of Computer Programs**, by Harold Abelson and Gerald Jay Sussman with Julie Sussman. Full text at <https://mitpress.mit.edu/sicp/>. In this classic textbook of computer science, chapters 2 and 3 discuss the use of sequences and streams to organize the data flow inside a program. The book uses Scheme for its examples, but many of the design approaches described in these chapters are applicable to functional-style Python code. <http://www.defmacro.org/ramblings/fp.html>: A general introduction to functional programming that uses Java examples and has a lengthy historical introduction. <https://en.wikipedia.org/wiki/Functional_programming>: General Wikipedia entry describing functional programming. <https://en.wikipedia.org/wiki/Coroutine>: Entry for coroutines. <https://en.wikipedia.org/wiki/Currying>: Entry for the concept of currying. ### Python-specific <http://gnosis.cx/TPiP/>: The first chapter of David Mertz’s book `Text Processing in Python` discusses functional programming for text processing, in the section titled “Utilizing Higher-Order Functions in Text Processing”. Mertz also wrote a 3-part series of articles on functional programming for IBM’s DeveloperWorks site; see [part 1](https://developer.ibm.com/articles/l-prog/), [part 2](https://developer.ibm.com/tutorials/l-prog2/), and [part 3](https://developer.ibm.com/tutorials/l-prog3/), ### Python documentation Documentation for the [`itertools`](../library/itertools#module-itertools "itertools: Functions creating iterators for efficient looping.") module. Documentation for the [`functools`](../library/functools#module-functools "functools: Higher-order functions and operations on callable objects.") module. Documentation for the [`operator`](../library/operator#module-operator "operator: Functions corresponding to the standard operators.") module. [**PEP 289**](https://www.python.org/dev/peps/pep-0289): “Generator Expressions” [**PEP 342**](https://www.python.org/dev/peps/pep-0342): “Coroutines via Enhanced Generators” describes the new generator features in Python 2.5.
programming_docs
python Argument Clinic How-To Argument Clinic How-To ====================== author Larry Hastings Abstract Argument Clinic is a preprocessor for CPython C files. Its purpose is to automate all the boilerplate involved with writing argument parsing code for “builtins”. This document shows you how to convert your first C function to work with Argument Clinic, and then introduces some advanced topics on Argument Clinic usage. Currently Argument Clinic is considered internal-only for CPython. Its use is not supported for files outside CPython, and no guarantees are made regarding backwards compatibility for future versions. In other words: if you maintain an external C extension for CPython, you’re welcome to experiment with Argument Clinic in your own code. But the version of Argument Clinic that ships with the next version of CPython *could* be totally incompatible and break all your code. The Goals Of Argument Clinic ---------------------------- Argument Clinic’s primary goal is to take over responsibility for all argument parsing code inside CPython. This means that, when you convert a function to work with Argument Clinic, that function should no longer do any of its own argument parsing—the code generated by Argument Clinic should be a “black box” to you, where CPython calls in at the top, and your code gets called at the bottom, with `PyObject *args` (and maybe `PyObject *kwargs`) magically converted into the C variables and types you need. In order for Argument Clinic to accomplish its primary goal, it must be easy to use. Currently, working with CPython’s argument parsing library is a chore, requiring maintaining redundant information in a surprising number of places. When you use Argument Clinic, you don’t have to repeat yourself. Obviously, no one would want to use Argument Clinic unless it’s solving their problem—and without creating new problems of its own. So it’s paramount that Argument Clinic generate correct code. It’d be nice if the code was faster, too, but at the very least it should not introduce a major speed regression. (Eventually Argument Clinic *should* make a major speedup possible—we could rewrite its code generator to produce tailor-made argument parsing code, rather than calling the general-purpose CPython argument parsing library. That would make for the fastest argument parsing possible!) Additionally, Argument Clinic must be flexible enough to work with any approach to argument parsing. Python has some functions with some very strange parsing behaviors; Argument Clinic’s goal is to support all of them. Finally, the original motivation for Argument Clinic was to provide introspection “signatures” for CPython builtins. It used to be, the introspection query functions would throw an exception if you passed in a builtin. With Argument Clinic, that’s a thing of the past! One idea you should keep in mind, as you work with Argument Clinic: the more information you give it, the better job it’ll be able to do. Argument Clinic is admittedly relatively simple right now. But as it evolves it will get more sophisticated, and it should be able to do many interesting and smart things with all the information you give it. Basic Concepts And Usage ------------------------ Argument Clinic ships with CPython; you’ll find it in `Tools/clinic/clinic.py`. If you run that script, specifying a C file as an argument: ``` $ python3 Tools/clinic/clinic.py foo.c ``` Argument Clinic will scan over the file looking for lines that look exactly like this: ``` /*[clinic input] ``` When it finds one, it reads everything up to a line that looks exactly like this: ``` [clinic start generated code]*/ ``` Everything in between these two lines is input for Argument Clinic. All of these lines, including the beginning and ending comment lines, are collectively called an Argument Clinic “block”. When Argument Clinic parses one of these blocks, it generates output. This output is rewritten into the C file immediately after the block, followed by a comment containing a checksum. The Argument Clinic block now looks like this: ``` /*[clinic input] ... clinic input goes here ... [clinic start generated code]*/ ... clinic output goes here ... /*[clinic end generated code: checksum=...]*/ ``` If you run Argument Clinic on the same file a second time, Argument Clinic will discard the old output and write out the new output with a fresh checksum line. However, if the input hasn’t changed, the output won’t change either. You should never modify the output portion of an Argument Clinic block. Instead, change the input until it produces the output you want. (That’s the purpose of the checksum—to detect if someone changed the output, as these edits would be lost the next time Argument Clinic writes out fresh output.) For the sake of clarity, here’s the terminology we’ll use with Argument Clinic: * The first line of the comment (`/*[clinic input]`) is the *start line*. * The last line of the initial comment (`[clinic start generated code]*/`) is the *end line*. * The last line (`/*[clinic end generated code: checksum=...]*/`) is the *checksum line*. * In between the start line and the end line is the *input*. * In between the end line and the checksum line is the *output*. * All the text collectively, from the start line to the checksum line inclusively, is the *block*. (A block that hasn’t been successfully processed by Argument Clinic yet doesn’t have output or a checksum line, but it’s still considered a block.) Converting Your First Function ------------------------------ The best way to get a sense of how Argument Clinic works is to convert a function to work with it. Here, then, are the bare minimum steps you’d need to follow to convert a function to work with Argument Clinic. Note that for code you plan to check in to CPython, you really should take the conversion farther, using some of the advanced concepts you’ll see later on in the document (like “return converters” and “self converters”). But we’ll keep it simple for this walkthrough so you can learn. Let’s dive in! 0. Make sure you’re working with a freshly updated checkout of the CPython trunk. 1. Find a Python builtin that calls either [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple") or [`PyArg_ParseTupleAndKeywords()`](../c-api/arg#c.PyArg_ParseTupleAndKeywords "PyArg_ParseTupleAndKeywords"), and hasn’t been converted to work with Argument Clinic yet. For my example I’m using `_pickle.Pickler.dump()`. 2. If the call to the `PyArg_Parse` function uses any of the following format units: ``` O& O! es es# et et# ``` or if it has multiple calls to [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple"), you should choose a different function. Argument Clinic *does* support all of these scenarios. But these are advanced topics—let’s do something simpler for your first function. Also, if the function has multiple calls to [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple") or [`PyArg_ParseTupleAndKeywords()`](../c-api/arg#c.PyArg_ParseTupleAndKeywords "PyArg_ParseTupleAndKeywords") where it supports different types for the same argument, or if the function uses something besides PyArg\_Parse functions to parse its arguments, it probably isn’t suitable for conversion to Argument Clinic. Argument Clinic doesn’t support generic functions or polymorphic parameters. 3. Add the following boilerplate above the function, creating our block: ``` /*[clinic input] [clinic start generated code]*/ ``` 4. Cut the docstring and paste it in between the `[clinic]` lines, removing all the junk that makes it a properly quoted C string. When you’re done you should have just the text, based at the left margin, with no line wider than 80 characters. (Argument Clinic will preserve indents inside the docstring.) If the old docstring had a first line that looked like a function signature, throw that line away. (The docstring doesn’t need it anymore—when you use `help()` on your builtin in the future, the first line will be built automatically based on the function’s signature.) Sample: ``` /*[clinic input] Write a pickled representation of obj to the open file. [clinic start generated code]*/ ``` 5. If your docstring doesn’t have a “summary” line, Argument Clinic will complain. So let’s make sure it has one. The “summary” line should be a paragraph consisting of a single 80-column line at the beginning of the docstring. (Our example docstring consists solely of a summary line, so the sample code doesn’t have to change for this step.) 6. Above the docstring, enter the name of the function, followed by a blank line. This should be the Python name of the function, and should be the full dotted path to the function—it should start with the name of the module, include any sub-modules, and if the function is a method on a class it should include the class name too. Sample: ``` /*[clinic input] _pickle.Pickler.dump Write a pickled representation of obj to the open file. [clinic start generated code]*/ ``` 7. If this is the first time that module or class has been used with Argument Clinic in this C file, you must declare the module and/or class. Proper Argument Clinic hygiene prefers declaring these in a separate block somewhere near the top of the C file, in the same way that include files and statics go at the top. (In our sample code we’ll just show the two blocks next to each other.) The name of the class and module should be the same as the one seen by Python. Check the name defined in the [`PyModuleDef`](../c-api/module#c.PyModuleDef "PyModuleDef") or [`PyTypeObject`](../c-api/type#c.PyTypeObject "PyTypeObject") as appropriate. When you declare a class, you must also specify two aspects of its type in C: the type declaration you’d use for a pointer to an instance of this class, and a pointer to the [`PyTypeObject`](../c-api/type#c.PyTypeObject "PyTypeObject") for this class. Sample: ``` /*[clinic input] module _pickle class _pickle.Pickler "PicklerObject *" "&Pickler_Type" [clinic start generated code]*/ /*[clinic input] _pickle.Pickler.dump Write a pickled representation of obj to the open file. [clinic start generated code]*/ ``` 8. Declare each of the parameters to the function. Each parameter should get its own line. All the parameter lines should be indented from the function name and the docstring. The general form of these parameter lines is as follows: ``` name_of_parameter: converter ``` If the parameter has a default value, add that after the converter: ``` name_of_parameter: converter = default_value ``` Argument Clinic’s support for “default values” is quite sophisticated; please see [the section below on default values](#default-values) for more information. Add a blank line below the parameters. What’s a “converter”? It establishes both the type of the variable used in C, and the method to convert the Python value into a C value at runtime. For now you’re going to use what’s called a “legacy converter”—a convenience syntax intended to make porting old code into Argument Clinic easier. For each parameter, copy the “format unit” for that parameter from the `PyArg_Parse()` format argument and specify *that* as its converter, as a quoted string. (“format unit” is the formal name for the one-to-three character substring of the `format` parameter that tells the argument parsing function what the type of the variable is and how to convert it. For more on format units please see [Parsing arguments and building values](../c-api/arg#arg-parsing).) For multicharacter format units like `z#`, use the entire two-or-three character string. Sample: ``` /*[clinic input] module _pickle class _pickle.Pickler "PicklerObject *" "&Pickler_Type" [clinic start generated code]*/ /*[clinic input] _pickle.Pickler.dump obj: 'O' Write a pickled representation of obj to the open file. [clinic start generated code]*/ ``` 9. If your function has `|` in the format string, meaning some parameters have default values, you can ignore it. Argument Clinic infers which parameters are optional based on whether or not they have default values. If your function has `$` in the format string, meaning it takes keyword-only arguments, specify `*` on a line by itself before the first keyword-only argument, indented the same as the parameter lines. (`_pickle.Pickler.dump` has neither, so our sample is unchanged.) 10. If the existing C function calls [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple") (as opposed to [`PyArg_ParseTupleAndKeywords()`](../c-api/arg#c.PyArg_ParseTupleAndKeywords "PyArg_ParseTupleAndKeywords")), then all its arguments are positional-only. To mark all parameters as positional-only in Argument Clinic, add a `/` on a line by itself after the last parameter, indented the same as the parameter lines. Currently this is all-or-nothing; either all parameters are positional-only, or none of them are. (In the future Argument Clinic may relax this restriction.) Sample: ``` /*[clinic input] module _pickle class _pickle.Pickler "PicklerObject *" "&Pickler_Type" [clinic start generated code]*/ /*[clinic input] _pickle.Pickler.dump obj: 'O' / Write a pickled representation of obj to the open file. [clinic start generated code]*/ ``` 11. It’s helpful to write a per-parameter docstring for each parameter. But per-parameter docstrings are optional; you can skip this step if you prefer. Here’s how to add a per-parameter docstring. The first line of the per-parameter docstring must be indented further than the parameter definition. The left margin of this first line establishes the left margin for the whole per-parameter docstring; all the text you write will be outdented by this amount. You can write as much text as you like, across multiple lines if you wish. Sample: ``` /*[clinic input] module _pickle class _pickle.Pickler "PicklerObject *" "&Pickler_Type" [clinic start generated code]*/ /*[clinic input] _pickle.Pickler.dump obj: 'O' The object to be pickled. / Write a pickled representation of obj to the open file. [clinic start generated code]*/ ``` 12. Save and close the file, then run `Tools/clinic/clinic.py` on it. With luck everything worked—your block now has output, and a `.c.h` file has been generated! Reopen the file in your text editor to see: ``` /*[clinic input] _pickle.Pickler.dump obj: 'O' The object to be pickled. / Write a pickled representation of obj to the open file. [clinic start generated code]*/ static PyObject * _pickle_Pickler_dump(PicklerObject *self, PyObject *obj) /*[clinic end generated code: output=87ecad1261e02ac7 input=552eb1c0f52260d9]*/ ``` Obviously, if Argument Clinic didn’t produce any output, it’s because it found an error in your input. Keep fixing your errors and retrying until Argument Clinic processes your file without complaint. For readability, most of the glue code has been generated to a `.c.h` file. You’ll need to include that in your original `.c` file, typically right after the clinic module block: ``` #include "clinic/_pickle.c.h" ``` 13. Double-check that the argument-parsing code Argument Clinic generated looks basically the same as the existing code. First, ensure both places use the same argument-parsing function. The existing code must call either [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple") or [`PyArg_ParseTupleAndKeywords()`](../c-api/arg#c.PyArg_ParseTupleAndKeywords "PyArg_ParseTupleAndKeywords"); ensure that the code generated by Argument Clinic calls the *exact* same function. Second, the format string passed in to [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple") or [`PyArg_ParseTupleAndKeywords()`](../c-api/arg#c.PyArg_ParseTupleAndKeywords "PyArg_ParseTupleAndKeywords") should be *exactly* the same as the hand-written one in the existing function, up to the colon or semi-colon. (Argument Clinic always generates its format strings with a `:` followed by the name of the function. If the existing code’s format string ends with `;`, to provide usage help, this change is harmless—don’t worry about it.) Third, for parameters whose format units require two arguments (like a length variable, or an encoding string, or a pointer to a conversion function), ensure that the second argument is *exactly* the same between the two invocations. Fourth, inside the output portion of the block you’ll find a preprocessor macro defining the appropriate static [`PyMethodDef`](../c-api/structures#c.PyMethodDef "PyMethodDef") structure for this builtin: ``` #define __PICKLE_PICKLER_DUMP_METHODDEF \ {"dump", (PyCFunction)__pickle_Pickler_dump, METH_O, __pickle_Pickler_dump__doc__}, ``` This static structure should be *exactly* the same as the existing static [`PyMethodDef`](../c-api/structures#c.PyMethodDef "PyMethodDef") structure for this builtin. If any of these items differ in *any way*, adjust your Argument Clinic function specification and rerun `Tools/clinic/clinic.py` until they *are* the same. 14. Notice that the last line of its output is the declaration of your “impl” function. This is where the builtin’s implementation goes. Delete the existing prototype of the function you’re modifying, but leave the opening curly brace. Now delete its argument parsing code and the declarations of all the variables it dumps the arguments into. Notice how the Python arguments are now arguments to this impl function; if the implementation used different names for these variables, fix it. Let’s reiterate, just because it’s kind of weird. Your code should now look like this: ``` static return_type your_function_impl(...) /*[clinic end generated code: checksum=...]*/ { ... ``` Argument Clinic generated the checksum line and the function prototype just above it. You should write the opening (and closing) curly braces for the function, and the implementation inside. Sample: ``` /*[clinic input] module _pickle class _pickle.Pickler "PicklerObject *" "&Pickler_Type" [clinic start generated code]*/ /*[clinic end generated code: checksum=da39a3ee5e6b4b0d3255bfef95601890afd80709]*/ /*[clinic input] _pickle.Pickler.dump obj: 'O' The object to be pickled. / Write a pickled representation of obj to the open file. [clinic start generated code]*/ PyDoc_STRVAR(__pickle_Pickler_dump__doc__, "Write a pickled representation of obj to the open file.\n" "\n" ... static PyObject * _pickle_Pickler_dump_impl(PicklerObject *self, PyObject *obj) /*[clinic end generated code: checksum=3bd30745bf206a48f8b576a1da3d90f55a0a4187]*/ { /* Check whether the Pickler was initialized correctly (issue3664). Developers often forget to call __init__() in their subclasses, which would trigger a segfault without this check. */ if (self->write == NULL) { PyErr_Format(PicklingError, "Pickler.__init__() was not called by %s.__init__()", Py_TYPE(self)->tp_name); return NULL; } if (_Pickler_ClearBuffer(self) < 0) return NULL; ... ``` 15. Remember the macro with the [`PyMethodDef`](../c-api/structures#c.PyMethodDef "PyMethodDef") structure for this function? Find the existing [`PyMethodDef`](../c-api/structures#c.PyMethodDef "PyMethodDef") structure for this function and replace it with a reference to the macro. (If the builtin is at module scope, this will probably be very near the end of the file; if the builtin is a class method, this will probably be below but relatively near to the implementation.) Note that the body of the macro contains a trailing comma. So when you replace the existing static [`PyMethodDef`](../c-api/structures#c.PyMethodDef "PyMethodDef") structure with the macro, *don’t* add a comma to the end. Sample: ``` static struct PyMethodDef Pickler_methods[] = { __PICKLE_PICKLER_DUMP_METHODDEF __PICKLE_PICKLER_CLEAR_MEMO_METHODDEF {NULL, NULL} /* sentinel */ }; ``` 16. Compile, then run the relevant portions of the regression-test suite. This change should not introduce any new compile-time warnings or errors, and there should be no externally-visible change to Python’s behavior. Well, except for one difference: `inspect.signature()` run on your function should now provide a valid signature! Congratulations, you’ve ported your first function to work with Argument Clinic! Advanced Topics --------------- Now that you’ve had some experience working with Argument Clinic, it’s time for some advanced topics. ### Symbolic default values The default value you provide for a parameter can’t be any arbitrary expression. Currently the following are explicitly supported: * Numeric constants (integer and float) * String constants * `True`, `False`, and `None` * Simple symbolic constants like `sys.maxsize`, which must start with the name of the module In case you’re curious, this is implemented in `from_builtin()` in `Lib/inspect.py`. (In the future, this may need to get even more elaborate, to allow full expressions like `CONSTANT - 1`.) ### Renaming the C functions and variables generated by Argument Clinic Argument Clinic automatically names the functions it generates for you. Occasionally this may cause a problem, if the generated name collides with the name of an existing C function. There’s an easy solution: override the names used for the C functions. Just add the keyword `"as"` to your function declaration line, followed by the function name you wish to use. Argument Clinic will use that function name for the base (generated) function, then add `"_impl"` to the end and use that for the name of the impl function. For example, if we wanted to rename the C function names generated for `pickle.Pickler.dump`, it’d look like this: ``` /*[clinic input] pickle.Pickler.dump as pickler_dumper ... ``` The base function would now be named `pickler_dumper()`, and the impl function would now be named `pickler_dumper_impl()`. Similarly, you may have a problem where you want to give a parameter a specific Python name, but that name may be inconvenient in C. Argument Clinic allows you to give a parameter different names in Python and in C, using the same `"as"` syntax: ``` /*[clinic input] pickle.Pickler.dump obj: object file as file_obj: object protocol: object = NULL * fix_imports: bool = True ``` Here, the name used in Python (in the signature and the `keywords` array) would be `file`, but the C variable would be named `file_obj`. You can use this to rename the `self` parameter too! ### Converting functions using PyArg\_UnpackTuple To convert a function parsing its arguments with [`PyArg_UnpackTuple()`](../c-api/arg#c.PyArg_UnpackTuple "PyArg_UnpackTuple"), simply write out all the arguments, specifying each as an `object`. You may specify the `type` argument to cast the type as appropriate. All arguments should be marked positional-only (add a `/` on a line by itself after the last argument). Currently the generated code will use [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple"), but this will change soon. ### Optional Groups Some legacy functions have a tricky approach to parsing their arguments: they count the number of positional arguments, then use a `switch` statement to call one of several different [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple") calls depending on how many positional arguments there are. (These functions cannot accept keyword-only arguments.) This approach was used to simulate optional arguments back before [`PyArg_ParseTupleAndKeywords()`](../c-api/arg#c.PyArg_ParseTupleAndKeywords "PyArg_ParseTupleAndKeywords") was created. While functions using this approach can often be converted to use [`PyArg_ParseTupleAndKeywords()`](../c-api/arg#c.PyArg_ParseTupleAndKeywords "PyArg_ParseTupleAndKeywords"), optional arguments, and default values, it’s not always possible. Some of these legacy functions have behaviors [`PyArg_ParseTupleAndKeywords()`](../c-api/arg#c.PyArg_ParseTupleAndKeywords "PyArg_ParseTupleAndKeywords") doesn’t directly support. The most obvious example is the builtin function `range()`, which has an optional argument on the *left* side of its required argument! Another example is `curses.window.addch()`, which has a group of two arguments that must always be specified together. (The arguments are called `x` and `y`; if you call the function passing in `x`, you must also pass in `y`—and if you don’t pass in `x` you may not pass in `y` either.) In any case, the goal of Argument Clinic is to support argument parsing for all existing CPython builtins without changing their semantics. Therefore Argument Clinic supports this alternate approach to parsing, using what are called *optional groups*. Optional groups are groups of arguments that must all be passed in together. They can be to the left or the right of the required arguments. They can *only* be used with positional-only parameters. Note Optional groups are *only* intended for use when converting functions that make multiple calls to [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple")! Functions that use *any* other approach for parsing arguments should *almost never* be converted to Argument Clinic using optional groups. Functions using optional groups currently cannot have accurate signatures in Python, because Python just doesn’t understand the concept. Please avoid using optional groups wherever possible. To specify an optional group, add a `[` on a line by itself before the parameters you wish to group together, and a `]` on a line by itself after these parameters. As an example, here’s how `curses.window.addch` uses optional groups to make the first two parameters and the last parameter optional: ``` /*[clinic input] curses.window.addch [ x: int X-coordinate. y: int Y-coordinate. ] ch: object Character to add. [ attr: long Attributes for the character. ] / ... ``` Notes: * For every optional group, one additional parameter will be passed into the impl function representing the group. The parameter will be an int named `group_{direction}_{number}`, where `{direction}` is either `right` or `left` depending on whether the group is before or after the required parameters, and `{number}` is a monotonically increasing number (starting at 1) indicating how far away the group is from the required parameters. When the impl is called, this parameter will be set to zero if this group was unused, and set to non-zero if this group was used. (By used or unused, I mean whether or not the parameters received arguments in this invocation.) * If there are no required arguments, the optional groups will behave as if they’re to the right of the required arguments. * In the case of ambiguity, the argument parsing code favors parameters on the left (before the required parameters). * Optional groups can only contain positional-only parameters. * Optional groups are *only* intended for legacy code. Please do not use optional groups for new code. ### Using real Argument Clinic converters, instead of “legacy converters” To save time, and to minimize how much you need to learn to achieve your first port to Argument Clinic, the walkthrough above tells you to use “legacy converters”. “Legacy converters” are a convenience, designed explicitly to make porting existing code to Argument Clinic easier. And to be clear, their use is acceptable when porting code for Python 3.4. However, in the long term we probably want all our blocks to use Argument Clinic’s real syntax for converters. Why? A couple reasons: * The proper converters are far easier to read and clearer in their intent. * There are some format units that are unsupported as “legacy converters”, because they require arguments, and the legacy converter syntax doesn’t support specifying arguments. * In the future we may have a new argument parsing library that isn’t restricted to what [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple") supports; this flexibility won’t be available to parameters using legacy converters. Therefore, if you don’t mind a little extra effort, please use the normal converters instead of legacy converters. In a nutshell, the syntax for Argument Clinic (non-legacy) converters looks like a Python function call. However, if there are no explicit arguments to the function (all functions take their default values), you may omit the parentheses. Thus `bool` and `bool()` are exactly the same converters. All arguments to Argument Clinic converters are keyword-only. All Argument Clinic converters accept the following arguments: `c_default` The default value for this parameter when defined in C. Specifically, this will be the initializer for the variable declared in the “parse function”. See [the section on default values](#default-values) for how to use this. Specified as a string. `annotation` The annotation value for this parameter. Not currently supported, because [**PEP 8**](https://www.python.org/dev/peps/pep-0008) mandates that the Python library may not use annotations. In addition, some converters accept additional arguments. Here is a list of these arguments, along with their meanings: `accept` A set of Python types (and possibly pseudo-types); this restricts the allowable Python argument to values of these types. (This is not a general-purpose facility; as a rule it only supports specific lists of types as shown in the legacy converter table.) To accept `None`, add `NoneType` to this set. `bitwise` Only supported for unsigned integers. The native integer value of this Python argument will be written to the parameter without any range checking, even for negative values. `converter` Only supported by the `object` converter. Specifies the name of a [C “converter function”](../c-api/arg#o-ampersand) to use to convert this object to a native type. `encoding` Only supported for strings. Specifies the encoding to use when converting this string from a Python str (Unicode) value into a C `char *` value. `subclass_of` Only supported for the `object` converter. Requires that the Python value be a subclass of a Python type, as expressed in C. `type` Only supported for the `object` and `self` converters. Specifies the C type that will be used to declare the variable. Default value is `"PyObject *"`. `zeroes` Only supported for strings. If true, embedded NUL bytes (`'\\0'`) are permitted inside the value. The length of the string will be passed in to the impl function, just after the string parameter, as a parameter named `<parameter_name>_length`. Please note, not every possible combination of arguments will work. Usually these arguments are implemented by specific `PyArg_ParseTuple` *format units*, with specific behavior. For example, currently you cannot call `unsigned_short` without also specifying `bitwise=True`. Although it’s perfectly reasonable to think this would work, these semantics don’t map to any existing format unit. So Argument Clinic doesn’t support it. (Or, at least, not yet.) Below is a table showing the mapping of legacy converters into real Argument Clinic converters. On the left is the legacy converter, on the right is the text you’d replace it with. | | | | --- | --- | | `'B'` | `unsigned_char(bitwise=True)` | | `'b'` | `unsigned_char` | | `'c'` | `char` | | `'C'` | `int(accept={str})` | | `'d'` | `double` | | `'D'` | `Py_complex` | | `'es'` | `str(encoding='name_of_encoding')` | | `'es#'` | `str(encoding='name_of_encoding', zeroes=True)` | | `'et'` | `str(encoding='name_of_encoding', accept={bytes, bytearray, str})` | | `'et#'` | `str(encoding='name_of_encoding', accept={bytes, bytearray, str}, zeroes=True)` | | `'f'` | `float` | | `'h'` | `short` | | `'H'` | `unsigned_short(bitwise=True)` | | `'i'` | `int` | | `'I'` | `unsigned_int(bitwise=True)` | | `'k'` | `unsigned_long(bitwise=True)` | | `'K'` | `unsigned_long_long(bitwise=True)` | | `'l'` | `long` | | `'L'` | `long long` | | `'n'` | `Py_ssize_t` | | `'O'` | `object` | | `'O!'` | `object(subclass_of='&PySomething_Type')` | | `'O&'` | `object(converter='name_of_c_function')` | | `'p'` | `bool` | | `'S'` | `PyBytesObject` | | `'s'` | `str` | | `'s#'` | `str(zeroes=True)` | | `'s*'` | `Py_buffer(accept={buffer, str})` | | `'U'` | `unicode` | | `'u'` | `Py_UNICODE` | | `'u#'` | `Py_UNICODE(zeroes=True)` | | `'w*'` | `Py_buffer(accept={rwbuffer})` | | `'Y'` | `PyByteArrayObject` | | `'y'` | `str(accept={bytes})` | | `'y#'` | `str(accept={robuffer}, zeroes=True)` | | `'y*'` | `Py_buffer` | | `'Z'` | `Py_UNICODE(accept={str, NoneType})` | | `'Z#'` | `Py_UNICODE(accept={str, NoneType}, zeroes=True)` | | `'z'` | `str(accept={str, NoneType})` | | `'z#'` | `str(accept={str, NoneType}, zeroes=True)` | | `'z*'` | `Py_buffer(accept={buffer, str, NoneType})` | As an example, here’s our sample `pickle.Pickler.dump` using the proper converter: ``` /*[clinic input] pickle.Pickler.dump obj: object The object to be pickled. / Write a pickled representation of obj to the open file. [clinic start generated code]*/ ``` One advantage of real converters is that they’re more flexible than legacy converters. For example, the `unsigned_int` converter (and all the `unsigned_` converters) can be specified without `bitwise=True`. Their default behavior performs range checking on the value, and they won’t accept negative numbers. You just can’t do that with a legacy converter! Argument Clinic will show you all the converters it has available. For each converter it’ll show you all the parameters it accepts, along with the default value for each parameter. Just run `Tools/clinic/clinic.py --converters` to see the full list. ### Py\_buffer When using the `Py_buffer` converter (or the `'s*'`, `'w*'`, `'*y'`, or `'z*'` legacy converters), you *must* not call [`PyBuffer_Release()`](../c-api/buffer#c.PyBuffer_Release "PyBuffer_Release") on the provided buffer. Argument Clinic generates code that does it for you (in the parsing function). ### Advanced converters Remember those format units you skipped for your first time because they were advanced? Here’s how to handle those too. The trick is, all those format units take arguments—either conversion functions, or types, or strings specifying an encoding. (But “legacy converters” don’t support arguments. That’s why we skipped them for your first function.) The argument you specified to the format unit is now an argument to the converter; this argument is either `converter` (for `O&`), `subclass_of` (for `O!`), or `encoding` (for all the format units that start with `e`). When using `subclass_of`, you may also want to use the other custom argument for `object()`: `type`, which lets you set the type actually used for the parameter. For example, if you want to ensure that the object is a subclass of `PyUnicode_Type`, you probably want to use the converter `object(type='PyUnicodeObject *', subclass_of='&PyUnicode_Type')`. One possible problem with using Argument Clinic: it takes away some possible flexibility for the format units starting with `e`. When writing a `PyArg_Parse` call by hand, you could theoretically decide at runtime what encoding string to pass in to [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple"). But now this string must be hard-coded at Argument-Clinic-preprocessing-time. This limitation is deliberate; it made supporting this format unit much easier, and may allow for future optimizations. This restriction doesn’t seem unreasonable; CPython itself always passes in static hard-coded encoding strings for parameters whose format units start with `e`. ### Parameter default values Default values for parameters can be any of a number of values. At their simplest, they can be string, int, or float literals: ``` foo: str = "abc" bar: int = 123 bat: float = 45.6 ``` They can also use any of Python’s built-in constants: ``` yep: bool = True nope: bool = False nada: object = None ``` There’s also special support for a default value of `NULL`, and for simple expressions, documented in the following sections. ### The `NULL` default value For string and object parameters, you can set them to `None` to indicate that there’s no default. However, that means the C variable will be initialized to `Py_None`. For convenience’s sakes, there’s a special value called `NULL` for just this reason: from Python’s perspective it behaves like a default value of `None`, but the C variable is initialized with `NULL`. ### Expressions specified as default values The default value for a parameter can be more than just a literal value. It can be an entire expression, using math operators and looking up attributes on objects. However, this support isn’t exactly simple, because of some non-obvious semantics. Consider the following example: ``` foo: Py_ssize_t = sys.maxsize - 1 ``` `sys.maxsize` can have different values on different platforms. Therefore Argument Clinic can’t simply evaluate that expression locally and hard-code it in C. So it stores the default in such a way that it will get evaluated at runtime, when the user asks for the function’s signature. What namespace is available when the expression is evaluated? It’s evaluated in the context of the module the builtin came from. So, if your module has an attribute called “`max_widgets`”, you may simply use it: ``` foo: Py_ssize_t = max_widgets ``` If the symbol isn’t found in the current module, it fails over to looking in `sys.modules`. That’s how it can find `sys.maxsize` for example. (Since you don’t know in advance what modules the user will load into their interpreter, it’s best to restrict yourself to modules that are preloaded by Python itself.) Evaluating default values only at runtime means Argument Clinic can’t compute the correct equivalent C default value. So you need to tell it explicitly. When you use an expression, you must also specify the equivalent expression in C, using the `c_default` parameter to the converter: ``` foo: Py_ssize_t(c_default="PY_SSIZE_T_MAX - 1") = sys.maxsize - 1 ``` Another complication: Argument Clinic can’t know in advance whether or not the expression you supply is valid. It parses it to make sure it looks legal, but it can’t *actually* know. You must be very careful when using expressions to specify values that are guaranteed to be valid at runtime! Finally, because expressions must be representable as static C values, there are many restrictions on legal expressions. Here’s a list of Python features you’re not permitted to use: * Function calls. * Inline if statements (`3 if foo else 5`). * Automatic sequence unpacking (`*[1, 2, 3]`). * List/set/dict comprehensions and generator expressions. * Tuple/list/set/dict literals. ### Using a return converter By default the impl function Argument Clinic generates for you returns `PyObject *`. But your C function often computes some C type, then converts it into the `PyObject *` at the last moment. Argument Clinic handles converting your inputs from Python types into native C types—why not have it convert your return value from a native C type into a Python type too? That’s what a “return converter” does. It changes your impl function to return some C type, then adds code to the generated (non-impl) function to handle converting that value into the appropriate `PyObject *`. The syntax for return converters is similar to that of parameter converters. You specify the return converter like it was a return annotation on the function itself. Return converters behave much the same as parameter converters; they take arguments, the arguments are all keyword-only, and if you’re not changing any of the default arguments you can omit the parentheses. (If you use both `"as"` *and* a return converter for your function, the `"as"` should come before the return converter.) There’s one additional complication when using return converters: how do you indicate an error has occurred? Normally, a function returns a valid (non-`NULL`) pointer for success, and `NULL` for failure. But if you use an integer return converter, all integers are valid. How can Argument Clinic detect an error? Its solution: each return converter implicitly looks for a special value that indicates an error. If you return that value, and an error has been set (`PyErr_Occurred()` returns a true value), then the generated code will propagate the error. Otherwise it will encode the value you return like normal. Currently Argument Clinic supports only a few return converters: ``` bool int unsigned int long unsigned int size_t Py_ssize_t float double DecodeFSDefault ``` None of these take parameters. For the first three, return -1 to indicate error. For `DecodeFSDefault`, the return type is `const char *`; return a `NULL` pointer to indicate an error. (There’s also an experimental `NoneType` converter, which lets you return `Py_None` on success or `NULL` on failure, without having to increment the reference count on `Py_None`. I’m not sure it adds enough clarity to be worth using.) To see all the return converters Argument Clinic supports, along with their parameters (if any), just run `Tools/clinic/clinic.py --converters` for the full list. ### Cloning existing functions If you have a number of functions that look similar, you may be able to use Clinic’s “clone” feature. When you clone an existing function, you reuse: * its parameters, including + their names, + their converters, with all parameters, + their default values, + their per-parameter docstrings, + their *kind* (whether they’re positional only, positional or keyword, or keyword only), and * its return converter. The only thing not copied from the original function is its docstring; the syntax allows you to specify a new docstring. Here’s the syntax for cloning a function: ``` /*[clinic input] module.class.new_function [as c_basename] = module.class.existing_function Docstring for new_function goes here. [clinic start generated code]*/ ``` (The functions can be in different modules or classes. I wrote `module.class` in the sample just to illustrate that you must use the full path to *both* functions.) Sorry, there’s no syntax for partially-cloning a function, or cloning a function then modifying it. Cloning is an all-or nothing proposition. Also, the function you are cloning from must have been previously defined in the current file. ### Calling Python code The rest of the advanced topics require you to write Python code which lives inside your C file and modifies Argument Clinic’s runtime state. This is simple: you simply define a Python block. A Python block uses different delimiter lines than an Argument Clinic function block. It looks like this: ``` /*[python input] # python code goes here [python start generated code]*/ ``` All the code inside the Python block is executed at the time it’s parsed. All text written to stdout inside the block is redirected into the “output” after the block. As an example, here’s a Python block that adds a static integer variable to the C code: ``` /*[python input] print('static int __ignored_unused_variable__ = 0;') [python start generated code]*/ static int __ignored_unused_variable__ = 0; /*[python checksum:...]*/ ``` ### Using a “self converter” Argument Clinic automatically adds a “self” parameter for you using a default converter. It automatically sets the `type` of this parameter to the “pointer to an instance” you specified when you declared the type. However, you can override Argument Clinic’s converter and specify one yourself. Just add your own `self` parameter as the first parameter in a block, and ensure that its converter is an instance of `self_converter` or a subclass thereof. What’s the point? This lets you override the type of `self`, or give it a different default name. How do you specify the custom type you want to cast `self` to? If you only have one or two functions with the same type for `self`, you can directly use Argument Clinic’s existing `self` converter, passing in the type you want to use as the `type` parameter: ``` /*[clinic input] _pickle.Pickler.dump self: self(type="PicklerObject *") obj: object / Write a pickled representation of the given object to the open file. [clinic start generated code]*/ ``` On the other hand, if you have a lot of functions that will use the same type for `self`, it’s best to create your own converter, subclassing `self_converter` but overwriting the `type` member: ``` /*[python input] class PicklerObject_converter(self_converter): type = "PicklerObject *" [python start generated code]*/ /*[clinic input] _pickle.Pickler.dump self: PicklerObject obj: object / Write a pickled representation of the given object to the open file. [clinic start generated code]*/ ``` ### Writing a custom converter As we hinted at in the previous section… you can write your own converters! A converter is simply a Python class that inherits from `CConverter`. The main purpose of a custom converter is if you have a parameter using the `O&` format unit—parsing this parameter means calling a [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple") “converter function”. Your converter class should be named `*something*_converter`. If the name follows this convention, then your converter class will be automatically registered with Argument Clinic; its name will be the name of your class with the `_converter` suffix stripped off. (This is accomplished with a metaclass.) You shouldn’t subclass `CConverter.__init__`. Instead, you should write a `converter_init()` function. `converter_init()` always accepts a `self` parameter; after that, all additional parameters *must* be keyword-only. Any arguments passed in to the converter in Argument Clinic will be passed along to your `converter_init()`. There are some additional members of `CConverter` you may wish to specify in your subclass. Here’s the current list: `type` The C type to use for this variable. `type` should be a Python string specifying the type, e.g. `int`. If this is a pointer type, the type string should end with `' *'`. `default` The Python default value for this parameter, as a Python value. Or the magic value `unspecified` if there is no default. `py_default` `default` as it should appear in Python code, as a string. Or `None` if there is no default. `c_default` `default` as it should appear in C code, as a string. Or `None` if there is no default. `c_ignored_default` The default value used to initialize the C variable when there is no default, but not specifying a default may result in an “uninitialized variable” warning. This can easily happen when using option groups—although properly-written code will never actually use this value, the variable does get passed in to the impl, and the C compiler will complain about the “use” of the uninitialized value. This value should always be a non-empty string. `converter` The name of the C converter function, as a string. `impl_by_reference` A boolean value. If true, Argument Clinic will add a `&` in front of the name of the variable when passing it into the impl function. `parse_by_reference` A boolean value. If true, Argument Clinic will add a `&` in front of the name of the variable when passing it into [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple"). Here’s the simplest example of a custom converter, from `Modules/zlibmodule.c`: ``` /*[python input] class ssize_t_converter(CConverter): type = 'Py_ssize_t' converter = 'ssize_t_converter' [python start generated code]*/ /*[python end generated code: output=da39a3ee5e6b4b0d input=35521e4e733823c7]*/ ``` This block adds a converter to Argument Clinic named `ssize_t`. Parameters declared as `ssize_t` will be declared as type [`Py_ssize_t`](../c-api/intro#c.Py_ssize_t "Py_ssize_t"), and will be parsed by the `'O&'` format unit, which will call the `ssize_t_converter` converter function. `ssize_t` variables automatically support default values. More sophisticated custom converters can insert custom C code to handle initialization and cleanup. You can see more examples of custom converters in the CPython source tree; grep the C files for the string `CConverter`. ### Writing a custom return converter Writing a custom return converter is much like writing a custom converter. Except it’s somewhat simpler, because return converters are themselves much simpler. Return converters must subclass `CReturnConverter`. There are no examples yet of custom return converters, because they are not widely used yet. If you wish to write your own return converter, please read `Tools/clinic/clinic.py`, specifically the implementation of `CReturnConverter` and all its subclasses. ### METH\_O and METH\_NOARGS To convert a function using `METH_O`, make sure the function’s single argument is using the `object` converter, and mark the arguments as positional-only: ``` /*[clinic input] meth_o_sample argument: object / [clinic start generated code]*/ ``` To convert a function using `METH_NOARGS`, just don’t specify any arguments. You can still use a self converter, a return converter, and specify a `type` argument to the object converter for `METH_O`. ### tp\_new and tp\_init functions You can convert `tp_new` and `tp_init` functions. Just name them `__new__` or `__init__` as appropriate. Notes: * The function name generated for `__new__` doesn’t end in `__new__` like it would by default. It’s just the name of the class, converted into a valid C identifier. * No `PyMethodDef` `#define` is generated for these functions. * `__init__` functions return `int`, not `PyObject *`. * Use the docstring as the class docstring. * Although `__new__` and `__init__` functions must always accept both the `args` and `kwargs` objects, when converting you may specify any signature for these functions that you like. (If your function doesn’t support keywords, the parsing function generated will throw an exception if it receives any.) ### Changing and redirecting Clinic’s output It can be inconvenient to have Clinic’s output interspersed with your conventional hand-edited C code. Luckily, Clinic is configurable: you can buffer up its output for printing later (or earlier!), or write its output to a separate file. You can also add a prefix or suffix to every line of Clinic’s generated output. While changing Clinic’s output in this manner can be a boon to readability, it may result in Clinic code using types before they are defined, or your code attempting to use Clinic-generated code before it is defined. These problems can be easily solved by rearranging the declarations in your file, or moving where Clinic’s generated code goes. (This is why the default behavior of Clinic is to output everything into the current block; while many people consider this hampers readability, it will never require rearranging your code to fix definition-before-use problems.) Let’s start with defining some terminology: *field* A field, in this context, is a subsection of Clinic’s output. For example, the `#define` for the `PyMethodDef` structure is a field, called `methoddef_define`. Clinic has seven different fields it can output per function definition: ``` docstring_prototype docstring_definition methoddef_define impl_prototype parser_prototype parser_definition impl_definition ``` All the names are of the form `"<a>_<b>"`, where `"<a>"` is the semantic object represented (the parsing function, the impl function, the docstring, or the methoddef structure) and `"<b>"` represents what kind of statement the field is. Field names that end in `"_prototype"` represent forward declarations of that thing, without the actual body/data of the thing; field names that end in `"_definition"` represent the actual definition of the thing, with the body/data of the thing. (`"methoddef"` is special, it’s the only one that ends with `"_define"`, representing that it’s a preprocessor #define.) *destination* A destination is a place Clinic can write output to. There are five built-in destinations: `block` The default destination: printed in the output section of the current Clinic block. `buffer` A text buffer where you can save text for later. Text sent here is appended to the end of any existing text. It’s an error to have any text left in the buffer when Clinic finishes processing a file. `file` A separate “clinic file” that will be created automatically by Clinic. The filename chosen for the file is `{basename}.clinic{extension}`, where `basename` and `extension` were assigned the output from `os.path.splitext()` run on the current file. (Example: the `file` destination for `_pickle.c` would be written to `_pickle.clinic.c`.) **Important: When using a** `file` **destination, you** *must check in* **the generated file!** `two-pass` A buffer like `buffer`. However, a two-pass buffer can only be dumped once, and it prints out all text sent to it during all processing, even from Clinic blocks *after* the dumping point. `suppress` The text is suppressed—thrown away. Clinic defines five new directives that let you reconfigure its output. The first new directive is `dump`: ``` dump <destination> ``` This dumps the current contents of the named destination into the output of the current block, and empties it. This only works with `buffer` and `two-pass` destinations. The second new directive is `output`. The most basic form of `output` is like this: ``` output <field> <destination> ``` This tells Clinic to output *field* to *destination*. `output` also supports a special meta-destination, called `everything`, which tells Clinic to output *all* fields to that *destination*. `output` has a number of other functions: ``` output push output pop output preset <preset> ``` `output push` and `output pop` allow you to push and pop configurations on an internal configuration stack, so that you can temporarily modify the output configuration, then easily restore the previous configuration. Simply push before your change to save the current configuration, then pop when you wish to restore the previous configuration. `output preset` sets Clinic’s output to one of several built-in preset configurations, as follows: `block` Clinic’s original starting configuration. Writes everything immediately after the input block. Suppress the `parser_prototype` and `docstring_prototype`, write everything else to `block`. `file` Designed to write everything to the “clinic file” that it can. You then `#include` this file near the top of your file. You may need to rearrange your file to make this work, though usually this just means creating forward declarations for various `typedef` and `PyTypeObject` definitions. Suppress the `parser_prototype` and `docstring_prototype`, write the `impl_definition` to `block`, and write everything else to `file`. The default filename is `"{dirname}/clinic/{basename}.h"`. `buffer` Save up most of the output from Clinic, to be written into your file near the end. For Python files implementing modules or builtin types, it’s recommended that you dump the buffer just above the static structures for your module or builtin type; these are normally very near the end. Using `buffer` may require even more editing than `file`, if your file has static `PyMethodDef` arrays defined in the middle of the file. Suppress the `parser_prototype`, `impl_prototype`, and `docstring_prototype`, write the `impl_definition` to `block`, and write everything else to `file`. `two-pass` Similar to the `buffer` preset, but writes forward declarations to the `two-pass` buffer, and definitions to the `buffer`. This is similar to the `buffer` preset, but may require less editing than `buffer`. Dump the `two-pass` buffer near the top of your file, and dump the `buffer` near the end just like you would when using the `buffer` preset. Suppresses the `impl_prototype`, write the `impl_definition` to `block`, write `docstring_prototype`, `methoddef_define`, and `parser_prototype` to `two-pass`, write everything else to `buffer`. `partial-buffer` Similar to the `buffer` preset, but writes more things to `block`, only writing the really big chunks of generated code to `buffer`. This avoids the definition-before-use problem of `buffer` completely, at the small cost of having slightly more stuff in the block’s output. Dump the `buffer` near the end, just like you would when using the `buffer` preset. Suppresses the `impl_prototype`, write the `docstring_definition` and `parser_definition` to `buffer`, write everything else to `block`. The third new directive is `destination`: ``` destination <name> <command> [...] ``` This performs an operation on the destination named `name`. There are two defined subcommands: `new` and `clear`. The `new` subcommand works like this: ``` destination <name> new <type> ``` This creates a new destination with name `<name>` and type `<type>`. There are five destination types: `suppress` Throws the text away. `block` Writes the text to the current block. This is what Clinic originally did. `buffer` A simple text buffer, like the “buffer” builtin destination above. `file` A text file. The file destination takes an extra argument, a template to use for building the filename, like so: destination <name> new <type> <file\_template> The template can use three strings internally that will be replaced by bits of the filename: {path} The full path to the file, including directory and full filename. {dirname} The name of the directory the file is in. {basename} Just the name of the file, not including the directory. {basename\_root} Basename with the extension clipped off (everything up to but not including the last ‘.’). {basename\_extension} The last ‘.’ and everything after it. If the basename does not contain a period, this will be the empty string. If there are no periods in the filename, {basename} and {filename} are the same, and {extension} is empty. “{basename}{extension}” is always exactly the same as “{filename}”.” `two-pass` A two-pass buffer, like the “two-pass” builtin destination above. The `clear` subcommand works like this: ``` destination <name> clear ``` It removes all the accumulated text up to this point in the destination. (I don’t know what you’d need this for, but I thought maybe it’d be useful while someone’s experimenting.) The fourth new directive is `set`: ``` set line_prefix "string" set line_suffix "string" ``` `set` lets you set two internal variables in Clinic. `line_prefix` is a string that will be prepended to every line of Clinic’s output; `line_suffix` is a string that will be appended to every line of Clinic’s output. Both of these support two format strings: `{block comment start}` Turns into the string `/*`, the start-comment text sequence for C files. `{block comment end}` Turns into the string `*/`, the end-comment text sequence for C files. The final new directive is one you shouldn’t need to use directly, called `preserve`: ``` preserve ``` This tells Clinic that the current contents of the output should be kept, unmodified. This is used internally by Clinic when dumping output into `file` files; wrapping it in a Clinic block lets Clinic use its existing checksum functionality to ensure the file was not modified by hand before it gets overwritten. ### The #ifdef trick If you’re converting a function that isn’t available on all platforms, there’s a trick you can use to make life a little easier. The existing code probably looks like this: ``` #ifdef HAVE_FUNCTIONNAME static module_functionname(...) { ... } #endif /* HAVE_FUNCTIONNAME */ ``` And then in the `PyMethodDef` structure at the bottom the existing code will have: ``` #ifdef HAVE_FUNCTIONNAME {'functionname', ... }, #endif /* HAVE_FUNCTIONNAME */ ``` In this scenario, you should enclose the body of your impl function inside the `#ifdef`, like so: ``` #ifdef HAVE_FUNCTIONNAME /*[clinic input] module.functionname ... [clinic start generated code]*/ static module_functionname(...) { ... } #endif /* HAVE_FUNCTIONNAME */ ``` Then, remove those three lines from the `PyMethodDef` structure, replacing them with the macro Argument Clinic generated: ``` MODULE_FUNCTIONNAME_METHODDEF ``` (You can find the real name for this macro inside the generated code. Or you can calculate it yourself: it’s the name of your function as defined on the first line of your block, but with periods changed to underscores, uppercased, and `"_METHODDEF"` added to the end.) Perhaps you’re wondering: what if `HAVE_FUNCTIONNAME` isn’t defined? The `MODULE_FUNCTIONNAME_METHODDEF` macro won’t be defined either! Here’s where Argument Clinic gets very clever. It actually detects that the Argument Clinic block might be deactivated by the `#ifdef`. When that happens, it generates a little extra code that looks like this: ``` #ifndef MODULE_FUNCTIONNAME_METHODDEF #define MODULE_FUNCTIONNAME_METHODDEF #endif /* !defined(MODULE_FUNCTIONNAME_METHODDEF) */ ``` That means the macro always works. If the function is defined, this turns into the correct structure, including the trailing comma. If the function is undefined, this turns into nothing. However, this causes one ticklish problem: where should Argument Clinic put this extra code when using the “block” output preset? It can’t go in the output block, because that could be deactivated by the `#ifdef`. (That’s the whole point!) In this situation, Argument Clinic writes the extra code to the “buffer” destination. This may mean that you get a complaint from Argument Clinic: ``` Warning in file "Modules/posixmodule.c" on line 12357: Destination buffer 'buffer' not empty at end of file, emptying. ``` When this happens, just open your file, find the `dump buffer` block that Argument Clinic added to your file (it’ll be at the very bottom), then move it above the `PyMethodDef` structure where that macro is used. ### Using Argument Clinic in Python files It’s actually possible to use Argument Clinic to preprocess Python files. There’s no point to using Argument Clinic blocks, of course, as the output wouldn’t make any sense to the Python interpreter. But using Argument Clinic to run Python blocks lets you use Python as a Python preprocessor! Since Python comments are different from C comments, Argument Clinic blocks embedded in Python files look slightly different. They look like this: ``` #/*[python input] #print("def foo(): pass") #[python start generated code]*/ def foo(): pass #/*[python checksum:...]*/ ```
programming_docs
python Instrumenting CPython with DTrace and SystemTap Instrumenting CPython with DTrace and SystemTap =============================================== author David Malcolm author Łukasz Langa DTrace and SystemTap are monitoring tools, each providing a way to inspect what the processes on a computer system are doing. They both use domain-specific languages allowing a user to write scripts which: * filter which processes are to be observed * gather data from the processes of interest * generate reports on the data As of Python 3.6, CPython can be built with embedded “markers”, also known as “probes”, that can be observed by a DTrace or SystemTap script, making it easier to monitor what the CPython processes on a system are doing. **CPython implementation detail:** DTrace markers are implementation details of the CPython interpreter. No guarantees are made about probe compatibility between versions of CPython. DTrace scripts can stop working or work incorrectly without warning when changing CPython versions. Enabling the static markers --------------------------- macOS comes with built-in support for DTrace. On Linux, in order to build CPython with the embedded markers for SystemTap, the SystemTap development tools must be installed. On a Linux machine, this can be done via: ``` $ yum install systemtap-sdt-devel ``` or: ``` $ sudo apt-get install systemtap-sdt-dev ``` CPython must then be configured `--with-dtrace`: ``` checking for --with-dtrace... yes ``` On macOS, you can list available DTrace probes by running a Python process in the background and listing all probes made available by the Python provider: ``` $ python3.6 -q & $ sudo dtrace -l -P python$! # or: dtrace -l -m python3.6 ID PROVIDER MODULE FUNCTION NAME 29564 python18035 python3.6 _PyEval_EvalFrameDefault function-entry 29565 python18035 python3.6 dtrace_function_entry function-entry 29566 python18035 python3.6 _PyEval_EvalFrameDefault function-return 29567 python18035 python3.6 dtrace_function_return function-return 29568 python18035 python3.6 collect gc-done 29569 python18035 python3.6 collect gc-start 29570 python18035 python3.6 _PyEval_EvalFrameDefault line 29571 python18035 python3.6 maybe_dtrace_line line ``` On Linux, you can verify if the SystemTap static markers are present in the built binary by seeing if it contains a “.note.stapsdt” section. ``` $ readelf -S ./python | grep .note.stapsdt [30] .note.stapsdt NOTE 0000000000000000 00308d78 ``` If you’ve built Python as a shared library (with –enable-shared), you need to look instead within the shared library. For example: ``` $ readelf -S libpython3.3dm.so.1.0 | grep .note.stapsdt [29] .note.stapsdt NOTE 0000000000000000 00365b68 ``` Sufficiently modern readelf can print the metadata: ``` $ readelf -n ./python Displaying notes found at file offset 0x00000254 with length 0x00000020: Owner Data size Description GNU 0x00000010 NT_GNU_ABI_TAG (ABI version tag) OS: Linux, ABI: 2.6.32 Displaying notes found at file offset 0x00000274 with length 0x00000024: Owner Data size Description GNU 0x00000014 NT_GNU_BUILD_ID (unique build ID bitstring) Build ID: df924a2b08a7e89f6e11251d4602022977af2670 Displaying notes found at file offset 0x002d6c30 with length 0x00000144: Owner Data size Description stapsdt 0x00000031 NT_STAPSDT (SystemTap probe descriptors) Provider: python Name: gc__start Location: 0x00000000004371c3, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bf6 Arguments: -4@%ebx stapsdt 0x00000030 NT_STAPSDT (SystemTap probe descriptors) Provider: python Name: gc__done Location: 0x00000000004374e1, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bf8 Arguments: -8@%rax stapsdt 0x00000045 NT_STAPSDT (SystemTap probe descriptors) Provider: python Name: function__entry Location: 0x000000000053db6c, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6be8 Arguments: 8@%rbp 8@%r12 -4@%eax stapsdt 0x00000046 NT_STAPSDT (SystemTap probe descriptors) Provider: python Name: function__return Location: 0x000000000053dba8, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bea Arguments: 8@%rbp 8@%r12 -4@%eax ``` The above metadata contains information for SystemTap describing how it can patch strategically-placed machine code instructions to enable the tracing hooks used by a SystemTap script. Static DTrace probes -------------------- The following example DTrace script can be used to show the call/return hierarchy of a Python script, only tracing within the invocation of a function called “start”. In other words, import-time function invocations are not going to be listed: ``` self int indent; python$target:::function-entry /copyinstr(arg1) == "start"/ { self->trace = 1; } python$target:::function-entry /self->trace/ { printf("%d\t%*s:", timestamp, 15, probename); printf("%*s", self->indent, ""); printf("%s:%s:%d\n", basename(copyinstr(arg0)), copyinstr(arg1), arg2); self->indent++; } python$target:::function-return /self->trace/ { self->indent--; printf("%d\t%*s:", timestamp, 15, probename); printf("%*s", self->indent, ""); printf("%s:%s:%d\n", basename(copyinstr(arg0)), copyinstr(arg1), arg2); } python$target:::function-return /copyinstr(arg1) == "start"/ { self->trace = 0; } ``` It can be invoked like this: ``` $ sudo dtrace -q -s call_stack.d -c "python3.6 script.py" ``` The output looks like this: ``` 156641360502280 function-entry:call_stack.py:start:23 156641360518804 function-entry: call_stack.py:function_1:1 156641360532797 function-entry: call_stack.py:function_3:9 156641360546807 function-return: call_stack.py:function_3:10 156641360563367 function-return: call_stack.py:function_1:2 156641360578365 function-entry: call_stack.py:function_2:5 156641360591757 function-entry: call_stack.py:function_1:1 156641360605556 function-entry: call_stack.py:function_3:9 156641360617482 function-return: call_stack.py:function_3:10 156641360629814 function-return: call_stack.py:function_1:2 156641360642285 function-return: call_stack.py:function_2:6 156641360656770 function-entry: call_stack.py:function_3:9 156641360669707 function-return: call_stack.py:function_3:10 156641360687853 function-entry: call_stack.py:function_4:13 156641360700719 function-return: call_stack.py:function_4:14 156641360719640 function-entry: call_stack.py:function_5:18 156641360732567 function-return: call_stack.py:function_5:21 156641360747370 function-return:call_stack.py:start:28 ``` Static SystemTap markers ------------------------ The low-level way to use the SystemTap integration is to use the static markers directly. This requires you to explicitly state the binary file containing them. For example, this SystemTap script can be used to show the call/return hierarchy of a Python script: ``` probe process("python").mark("function__entry") { filename = user_string($arg1); funcname = user_string($arg2); lineno = $arg3; printf("%s => %s in %s:%d\\n", thread_indent(1), funcname, filename, lineno); } probe process("python").mark("function__return") { filename = user_string($arg1); funcname = user_string($arg2); lineno = $arg3; printf("%s <= %s in %s:%d\\n", thread_indent(-1), funcname, filename, lineno); } ``` It can be invoked like this: ``` $ stap \ show-call-hierarchy.stp \ -c "./python test.py" ``` The output looks like this: ``` 11408 python(8274): => __contains__ in Lib/_abcoll.py:362 11414 python(8274): => __getitem__ in Lib/os.py:425 11418 python(8274): => encode in Lib/os.py:490 11424 python(8274): <= encode in Lib/os.py:493 11428 python(8274): <= __getitem__ in Lib/os.py:426 11433 python(8274): <= __contains__ in Lib/_abcoll.py:366 ``` where the columns are: * time in microseconds since start of script * name of executable * PID of process and the remainder indicates the call/return hierarchy as the script executes. For a `–enable-shared` build of CPython, the markers are contained within the libpython shared library, and the probe’s dotted path needs to reflect this. For example, this line from the above example: ``` probe process("python").mark("function__entry") { ``` should instead read: ``` probe process("python").library("libpython3.6dm.so.1.0").mark("function__entry") { ``` (assuming a debug build of CPython 3.6) Available static markers ------------------------ `function__entry(str filename, str funcname, int lineno)` This marker indicates that execution of a Python function has begun. It is only triggered for pure-Python (bytecode) functions. The filename, function name, and line number are provided back to the tracing script as positional arguments, which must be accessed using `$arg1`, `$arg2`, `$arg3`: * `$arg1` : `(const char *)` filename, accessible using `user_string($arg1)` * `$arg2` : `(const char *)` function name, accessible using `user_string($arg2)` * `$arg3` : `int` line number `function__return(str filename, str funcname, int lineno)` This marker is the converse of `function__entry()`, and indicates that execution of a Python function has ended (either via `return`, or via an exception). It is only triggered for pure-Python (bytecode) functions. The arguments are the same as for `function__entry()` `line(str filename, str funcname, int lineno)` This marker indicates a Python line is about to be executed. It is the equivalent of line-by-line tracing with a Python profiler. It is not triggered within C functions. The arguments are the same as for `function__entry()`. `gc__start(int generation)` Fires when the Python interpreter starts a garbage collection cycle. `arg0` is the generation to scan, like [`gc.collect()`](../library/gc#gc.collect "gc.collect"). `gc__done(long collected)` Fires when the Python interpreter finishes a garbage collection cycle. `arg0` is the number of collected objects. `import__find__load__start(str modulename)` Fires before [`importlib`](../library/importlib#module-importlib "importlib: The implementation of the import machinery.") attempts to find and load the module. `arg0` is the module name. New in version 3.7. `import__find__load__done(str modulename, int found)` Fires after [`importlib`](../library/importlib#module-importlib "importlib: The implementation of the import machinery.")’s find\_and\_load function is called. `arg0` is the module name, `arg1` indicates if module was successfully loaded. New in version 3.7. `audit(str event, void *tuple)` Fires when [`sys.audit()`](../library/sys#sys.audit "sys.audit") or [`PySys_Audit()`](../c-api/sys#c.PySys_Audit "PySys_Audit") is called. `arg0` is the event name as C string, `arg1` is a [`PyObject`](../c-api/structures#c.PyObject "PyObject") pointer to a tuple object. New in version 3.8. SystemTap Tapsets ----------------- The higher-level way to use the SystemTap integration is to use a “tapset”: SystemTap’s equivalent of a library, which hides some of the lower-level details of the static markers. Here is a tapset file, based on a non-shared build of CPython: ``` /* Provide a higher-level wrapping around the function__entry and function__return markers: \*/ probe python.function.entry = process("python").mark("function__entry") { filename = user_string($arg1); funcname = user_string($arg2); lineno = $arg3; frameptr = $arg4 } probe python.function.return = process("python").mark("function__return") { filename = user_string($arg1); funcname = user_string($arg2); lineno = $arg3; frameptr = $arg4 } ``` If this file is installed in SystemTap’s tapset directory (e.g. `/usr/share/systemtap/tapset`), then these additional probepoints become available: `python.function.entry(str filename, str funcname, int lineno, frameptr)` This probe point indicates that execution of a Python function has begun. It is only triggered for pure-Python (bytecode) functions. `python.function.return(str filename, str funcname, int lineno, frameptr)` This probe point is the converse of `python.function.return`, and indicates that execution of a Python function has ended (either via `return`, or via an exception). It is only triggered for pure-Python (bytecode) functions. Examples -------- This SystemTap script uses the tapset above to more cleanly implement the example given above of tracing the Python function-call hierarchy, without needing to directly name the static markers: ``` probe python.function.entry { printf("%s => %s in %s:%d\n", thread_indent(1), funcname, filename, lineno); } probe python.function.return { printf("%s <= %s in %s:%d\n", thread_indent(-1), funcname, filename, lineno); } ``` The following script uses the tapset above to provide a top-like view of all running CPython code, showing the top 20 most frequently-entered bytecode frames, each second, across the whole system: ``` global fn_calls; probe python.function.entry { fn_calls[pid(), filename, funcname, lineno] += 1; } probe timer.ms(1000) { printf("\033[2J\033[1;1H") /* clear screen \*/ printf("%6s %80s %6s %30s %6s\n", "PID", "FILENAME", "LINE", "FUNCTION", "CALLS") foreach ([pid, filename, funcname, lineno] in fn_calls- limit 20) { printf("%6d %80s %6d %30s %6d\n", pid, filename, lineno, funcname, fn_calls[pid, filename, funcname, lineno]); } delete fn_calls; } ``` python Unicode HOWTO Unicode HOWTO ============= Release 1.12 This HOWTO discusses Python’s support for the Unicode specification for representing textual data, and explains various problems that people commonly encounter when trying to work with Unicode. Introduction to Unicode ----------------------- ### Definitions Today’s programs need to be able to handle a wide variety of characters. Applications are often internationalized to display messages and output in a variety of user-selectable languages; the same program might need to output an error message in English, French, Japanese, Hebrew, or Russian. Web content can be written in any of these languages and can also include a variety of emoji symbols. Python’s string type uses the Unicode Standard for representing characters, which lets Python programs work with all these different possible characters. Unicode (<https://www.unicode.org/>) is a specification that aims to list every character used by human languages and give each character its own unique code. The Unicode specifications are continually revised and updated to add new languages and symbols. A **character** is the smallest possible component of a text. ‘A’, ‘B’, ‘C’, etc., are all different characters. So are ‘È’ and ‘Í’. Characters vary depending on the language or context you’re talking about. For example, there’s a character for “Roman Numeral One”, ‘Ⅰ’, that’s separate from the uppercase letter ‘I’. They’ll usually look the same, but these are two different characters that have different meanings. The Unicode standard describes how characters are represented by **code points**. A code point value is an integer in the range 0 to 0x10FFFF (about 1.1 million values, the [actual number assigned](https://www.unicode.org/versions/latest/#Summary) is less than that). In the standard and in this document, a code point is written using the notation `U+265E` to mean the character with value `0x265e` (9,822 in decimal). The Unicode standard contains a lot of tables listing characters and their corresponding code points: ``` 0061 'a'; LATIN SMALL LETTER A 0062 'b'; LATIN SMALL LETTER B 0063 'c'; LATIN SMALL LETTER C ... 007B '{'; LEFT CURLY BRACKET ... 2167 'Ⅷ'; ROMAN NUMERAL EIGHT 2168 'Ⅸ'; ROMAN NUMERAL NINE ... 265E '♞'; BLACK CHESS KNIGHT 265F '♟'; BLACK CHESS PAWN ... 1F600 '😀'; GRINNING FACE 1F609 '😉'; WINKING FACE ... ``` Strictly, these definitions imply that it’s meaningless to say ‘this is character `U+265E`’. `U+265E` is a code point, which represents some particular character; in this case, it represents the character ‘BLACK CHESS KNIGHT’, ‘♞’. In informal contexts, this distinction between code points and characters will sometimes be forgotten. A character is represented on a screen or on paper by a set of graphical elements that’s called a **glyph**. The glyph for an uppercase A, for example, is two diagonal strokes and a horizontal stroke, though the exact details will depend on the font being used. Most Python code doesn’t need to worry about glyphs; figuring out the correct glyph to display is generally the job of a GUI toolkit or a terminal’s font renderer. ### Encodings To summarize the previous section: a Unicode string is a sequence of code points, which are numbers from 0 through `0x10FFFF` (1,114,111 decimal). This sequence of code points needs to be represented in memory as a set of **code units**, and **code units** are then mapped to 8-bit bytes. The rules for translating a Unicode string into a sequence of bytes are called a **character encoding**, or just an **encoding**. The first encoding you might think of is using 32-bit integers as the code unit, and then using the CPU’s representation of 32-bit integers. In this representation, the string “Python” might look like this: ``` P y t h o n 0x50 00 00 00 79 00 00 00 74 00 00 00 68 00 00 00 6f 00 00 00 6e 00 00 00 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 ``` This representation is straightforward but using it presents a number of problems. 1. It’s not portable; different processors order the bytes differently. 2. It’s very wasteful of space. In most texts, the majority of the code points are less than 127, or less than 255, so a lot of space is occupied by `0x00` bytes. The above string takes 24 bytes compared to the 6 bytes needed for an ASCII representation. Increased RAM usage doesn’t matter too much (desktop computers have gigabytes of RAM, and strings aren’t usually that large), but expanding our usage of disk and network bandwidth by a factor of 4 is intolerable. 3. It’s not compatible with existing C functions such as `strlen()`, so a new family of wide string functions would need to be used. Therefore this encoding isn’t used very much, and people instead choose other encodings that are more efficient and convenient, such as UTF-8. UTF-8 is one of the most commonly used encodings, and Python often defaults to using it. UTF stands for “Unicode Transformation Format”, and the ‘8’ means that 8-bit values are used in the encoding. (There are also UTF-16 and UTF-32 encodings, but they are less frequently used than UTF-8.) UTF-8 uses the following rules: 1. If the code point is < 128, it’s represented by the corresponding byte value. 2. If the code point is >= 128, it’s turned into a sequence of two, three, or four bytes, where each byte of the sequence is between 128 and 255. UTF-8 has several convenient properties: 1. It can handle any Unicode code point. 2. A Unicode string is turned into a sequence of bytes that contains embedded zero bytes only where they represent the null character (U+0000). This means that UTF-8 strings can be processed by C functions such as `strcpy()` and sent through protocols that can’t handle zero bytes for anything other than end-of-string markers. 3. A string of ASCII text is also valid UTF-8 text. 4. UTF-8 is fairly compact; the majority of commonly used characters can be represented with one or two bytes. 5. If bytes are corrupted or lost, it’s possible to determine the start of the next UTF-8-encoded code point and resynchronize. It’s also unlikely that random 8-bit data will look like valid UTF-8. 6. UTF-8 is a byte oriented encoding. The encoding specifies that each character is represented by a specific sequence of one or more bytes. This avoids the byte-ordering issues that can occur with integer and word oriented encodings, like UTF-16 and UTF-32, where the sequence of bytes varies depending on the hardware on which the string was encoded. ### References The [Unicode Consortium site](https://www.unicode.org) has character charts, a glossary, and PDF versions of the Unicode specification. Be prepared for some difficult reading. [A chronology](https://www.unicode.org/history/) of the origin and development of Unicode is also available on the site. On the Computerphile Youtube channel, Tom Scott briefly [discusses the history of Unicode and UTF-8](https://www.youtube.com/watch?v=MijmeoH9LT4) (9 minutes 36 seconds). To help understand the standard, Jukka Korpela has written [an introductory guide](http://jkorpela.fi/unicode/guide.html) to reading the Unicode character tables. Another [good introductory article](https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/) was written by Joel Spolsky. If this introduction didn’t make things clear to you, you should try reading this alternate article before continuing. Wikipedia entries are often helpful; see the entries for “[character encoding](https://en.wikipedia.org/wiki/Character_encoding)” and [UTF-8](https://en.wikipedia.org/wiki/UTF-8), for example. Python’s Unicode Support ------------------------ Now that you’ve learned the rudiments of Unicode, we can look at Python’s Unicode features. ### The String Type Since Python 3.0, the language’s [`str`](../library/stdtypes#str "str") type contains Unicode characters, meaning any string created using `"unicode rocks!"`, `'unicode rocks!'`, or the triple-quoted string syntax is stored as Unicode. The default encoding for Python source code is UTF-8, so you can simply include a Unicode character in a string literal: ``` try: with open('/tmp/input.txt', 'r') as f: ... except OSError: # 'File not found' error message. print("Fichier non trouvé") ``` Side note: Python 3 also supports using Unicode characters in identifiers: ``` répertoire = "/tmp/records.log" with open(répertoire, "w") as f: f.write("test\n") ``` If you can’t enter a particular character in your editor or want to keep the source code ASCII-only for some reason, you can also use escape sequences in string literals. (Depending on your system, you may see the actual capital-delta glyph instead of a u escape.) ``` >>> "\N{GREEK CAPITAL LETTER DELTA}" # Using the character name '\u0394' >>> "\u0394" # Using a 16-bit hex value '\u0394' >>> "\U00000394" # Using a 32-bit hex value '\u0394' ``` In addition, one can create a string using the [`decode()`](../library/stdtypes#bytes.decode "bytes.decode") method of [`bytes`](../library/stdtypes#bytes "bytes"). This method takes an *encoding* argument, such as `UTF-8`, and optionally an *errors* argument. The *errors* argument specifies the response when the input string can’t be converted according to the encoding’s rules. Legal values for this argument are `'strict'` (raise a [`UnicodeDecodeError`](../library/exceptions#UnicodeDecodeError "UnicodeDecodeError") exception), `'replace'` (use `U+FFFD`, `REPLACEMENT CHARACTER`), `'ignore'` (just leave the character out of the Unicode result), or `'backslashreplace'` (inserts a `\xNN` escape sequence). The following examples show the differences: ``` >>> b'\x80abc'.decode("utf-8", "strict") Traceback (most recent call last): ... UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte >>> b'\x80abc'.decode("utf-8", "replace") '\ufffdabc' >>> b'\x80abc'.decode("utf-8", "backslashreplace") '\\x80abc' >>> b'\x80abc'.decode("utf-8", "ignore") 'abc' ``` Encodings are specified as strings containing the encoding’s name. Python comes with roughly 100 different encodings; see the Python Library Reference at [Standard Encodings](../library/codecs#standard-encodings) for a list. Some encodings have multiple names; for example, `'latin-1'`, `'iso_8859_1'` and `'8859`’ are all synonyms for the same encoding. One-character Unicode strings can also be created with the [`chr()`](../library/functions#chr "chr") built-in function, which takes integers and returns a Unicode string of length 1 that contains the corresponding code point. The reverse operation is the built-in [`ord()`](../library/functions#ord "ord") function that takes a one-character Unicode string and returns the code point value: ``` >>> chr(57344) '\ue000' >>> ord('\ue000') 57344 ``` ### Converting to Bytes The opposite method of [`bytes.decode()`](../library/stdtypes#bytes.decode "bytes.decode") is [`str.encode()`](../library/stdtypes#str.encode "str.encode"), which returns a [`bytes`](../library/stdtypes#bytes "bytes") representation of the Unicode string, encoded in the requested *encoding*. The *errors* parameter is the same as the parameter of the [`decode()`](../library/stdtypes#bytes.decode "bytes.decode") method but supports a few more possible handlers. As well as `'strict'`, `'ignore'`, and `'replace'` (which in this case inserts a question mark instead of the unencodable character), there is also `'xmlcharrefreplace'` (inserts an XML character reference), `backslashreplace` (inserts a `\uNNNN` escape sequence) and `namereplace` (inserts a `\N{...}` escape sequence). The following example shows the different results: ``` >>> u = chr(40960) + 'abcd' + chr(1972) >>> u.encode('utf-8') b'\xea\x80\x80abcd\xde\xb4' >>> u.encode('ascii') Traceback (most recent call last): ... UnicodeEncodeError: 'ascii' codec can't encode character '\ua000' in position 0: ordinal not in range(128) >>> u.encode('ascii', 'ignore') b'abcd' >>> u.encode('ascii', 'replace') b'?abcd?' >>> u.encode('ascii', 'xmlcharrefreplace') b'&#40960;abcd&#1972;' >>> u.encode('ascii', 'backslashreplace') b'\\ua000abcd\\u07b4' >>> u.encode('ascii', 'namereplace') b'\\N{YI SYLLABLE IT}abcd\\u07b4' ``` The low-level routines for registering and accessing the available encodings are found in the [`codecs`](../library/codecs#module-codecs "codecs: Encode and decode data and streams.") module. Implementing new encodings also requires understanding the [`codecs`](../library/codecs#module-codecs "codecs: Encode and decode data and streams.") module. However, the encoding and decoding functions returned by this module are usually more low-level than is comfortable, and writing new encodings is a specialized task, so the module won’t be covered in this HOWTO. ### Unicode Literals in Python Source Code In Python source code, specific Unicode code points can be written using the `\u` escape sequence, which is followed by four hex digits giving the code point. The `\U` escape sequence is similar, but expects eight hex digits, not four: ``` >>> s = "a\xac\u1234\u20ac\U00008000" ... # ^^^^ two-digit hex escape ... # ^^^^^^ four-digit Unicode escape ... # ^^^^^^^^^^ eight-digit Unicode escape >>> [ord(c) for c in s] [97, 172, 4660, 8364, 32768] ``` Using escape sequences for code points greater than 127 is fine in small doses, but becomes an annoyance if you’re using many accented characters, as you would in a program with messages in French or some other accent-using language. You can also assemble strings using the [`chr()`](../library/functions#chr "chr") built-in function, but this is even more tedious. Ideally, you’d want to be able to write literals in your language’s natural encoding. You could then edit Python source code with your favorite editor which would display the accented characters naturally, and have the right characters used at runtime. Python supports writing source code in UTF-8 by default, but you can use almost any encoding if you declare the encoding being used. This is done by including a special comment as either the first or second line of the source file: ``` #!/usr/bin/env python # -*- coding: latin-1 -*- u = 'abcdé' print(ord(u[-1])) ``` The syntax is inspired by Emacs’s notation for specifying variables local to a file. Emacs supports many different variables, but Python only supports ‘coding’. The `-*-` symbols indicate to Emacs that the comment is special; they have no significance to Python but are a convention. Python looks for `coding: name` or `coding=name` in the comment. If you don’t include such a comment, the default encoding used will be UTF-8 as already mentioned. See also [**PEP 263**](https://www.python.org/dev/peps/pep-0263) for more information. ### Unicode Properties The Unicode specification includes a database of information about code points. For each defined code point, the information includes the character’s name, its category, the numeric value if applicable (for characters representing numeric concepts such as the Roman numerals, fractions such as one-third and four-fifths, etc.). There are also display-related properties, such as how to use the code point in bidirectional text. The following program displays some information about several characters, and prints the numeric value of one particular character: ``` import unicodedata u = chr(233) + chr(0x0bf2) + chr(3972) + chr(6000) + chr(13231) for i, c in enumerate(u): print(i, '%04x' % ord(c), unicodedata.category(c), end=" ") print(unicodedata.name(c)) # Get numeric value of second character print(unicodedata.numeric(u[1])) ``` When run, this prints: ``` 0 00e9 Ll LATIN SMALL LETTER E WITH ACUTE 1 0bf2 No TAMIL NUMBER ONE THOUSAND 2 0f84 Mn TIBETAN MARK HALANTA 3 1770 Lo TAGBANWA LETTER SA 4 33af So SQUARE RAD OVER S SQUARED 1000.0 ``` The category codes are abbreviations describing the nature of the character. These are grouped into categories such as “Letter”, “Number”, “Punctuation”, or “Symbol”, which in turn are broken up into subcategories. To take the codes from the above output, `'Ll'` means ‘Letter, lowercase’, `'No'` means “Number, other”, `'Mn'` is “Mark, nonspacing”, and `'So'` is “Symbol, other”. See [the General Category Values section of the Unicode Character Database documentation](https://www.unicode.org/reports/tr44/#General_Category_Values) for a list of category codes. ### Comparing Strings Unicode adds some complication to comparing strings, because the same set of characters can be represented by different sequences of code points. For example, a letter like ‘ê’ can be represented as a single code point U+00EA, or as U+0065 U+0302, which is the code point for ‘e’ followed by a code point for ‘COMBINING CIRCUMFLEX ACCENT’. These will produce the same output when printed, but one is a string of length 1 and the other is of length 2. One tool for a case-insensitive comparison is the [`casefold()`](../library/stdtypes#str.casefold "str.casefold") string method that converts a string to a case-insensitive form following an algorithm described by the Unicode Standard. This algorithm has special handling for characters such as the German letter ‘ß’ (code point U+00DF), which becomes the pair of lowercase letters ‘ss’. ``` >>> street = 'Gürzenichstraße' >>> street.casefold() 'gürzenichstrasse' ``` A second tool is the [`unicodedata`](../library/unicodedata#module-unicodedata "unicodedata: Access the Unicode Database.") module’s [`normalize()`](../library/unicodedata#unicodedata.normalize "unicodedata.normalize") function that converts strings to one of several normal forms, where letters followed by a combining character are replaced with single characters. `normalize()` can be used to perform string comparisons that won’t falsely report inequality if two strings use combining characters differently: ``` import unicodedata def compare_strs(s1, s2): def NFD(s): return unicodedata.normalize('NFD', s) return NFD(s1) == NFD(s2) single_char = 'ê' multiple_chars = '\N{LATIN SMALL LETTER E}\N{COMBINING CIRCUMFLEX ACCENT}' print('length of first string=', len(single_char)) print('length of second string=', len(multiple_chars)) print(compare_strs(single_char, multiple_chars)) ``` When run, this outputs: ``` $ python3 compare-strs.py length of first string= 1 length of second string= 2 True ``` The first argument to the [`normalize()`](../library/unicodedata#unicodedata.normalize "unicodedata.normalize") function is a string giving the desired normalization form, which can be one of ‘NFC’, ‘NFKC’, ‘NFD’, and ‘NFKD’. The Unicode Standard also specifies how to do caseless comparisons: ``` import unicodedata def compare_caseless(s1, s2): def NFD(s): return unicodedata.normalize('NFD', s) return NFD(NFD(s1).casefold()) == NFD(NFD(s2).casefold()) # Example usage single_char = 'ê' multiple_chars = '\N{LATIN CAPITAL LETTER E}\N{COMBINING CIRCUMFLEX ACCENT}' print(compare_caseless(single_char, multiple_chars)) ``` This will print `True`. (Why is `NFD()` invoked twice? Because there are a few characters that make `casefold()` return a non-normalized string, so the result needs to be normalized again. See section 3.13 of the Unicode Standard for a discussion and an example.) ### Unicode Regular Expressions The regular expressions supported by the [`re`](../library/re#module-re "re: Regular expression operations.") module can be provided either as bytes or strings. Some of the special character sequences such as `\d` and `\w` have different meanings depending on whether the pattern is supplied as bytes or a string. For example, `\d` will match the characters `[0-9]` in bytes but in strings will match any character that’s in the `'Nd'` category. The string in this example has the number 57 written in both Thai and Arabic numerals: ``` import re p = re.compile(r'\d+') s = "Over \u0e55\u0e57 57 flavours" m = p.search(s) print(repr(m.group())) ``` When executed, `\d+` will match the Thai numerals and print them out. If you supply the [`re.ASCII`](../library/re#re.ASCII "re.ASCII") flag to [`compile()`](../library/re#re.compile "re.compile"), `\d+` will match the substring “57” instead. Similarly, `\w` matches a wide variety of Unicode characters but only `[a-zA-Z0-9_]` in bytes or if [`re.ASCII`](../library/re#re.ASCII "re.ASCII") is supplied, and `\s` will match either Unicode whitespace characters or `[ \t\n\r\f\v]`. ### References Some good alternative discussions of Python’s Unicode support are: * [Processing Text Files in Python 3](http://python-notes.curiousefficiency.org/en/latest/python3/text_file_processing.html), by Nick Coghlan. * [Pragmatic Unicode](https://nedbatchelder.com/text/unipain.html), a PyCon 2012 presentation by Ned Batchelder. The [`str`](../library/stdtypes#str "str") type is described in the Python library reference at [Text Sequence Type — str](../library/stdtypes#textseq). The documentation for the [`unicodedata`](../library/unicodedata#module-unicodedata "unicodedata: Access the Unicode Database.") module. The documentation for the [`codecs`](../library/codecs#module-codecs "codecs: Encode and decode data and streams.") module. Marc-André Lemburg gave [a presentation titled “Python and Unicode” (PDF slides)](https://downloads.egenix.com/python/Unicode-EPC2002-Talk.pdf) at EuroPython 2002. The slides are an excellent overview of the design of Python 2’s Unicode features (where the Unicode string type is called `unicode` and literals start with `u`). Reading and Writing Unicode Data -------------------------------- Once you’ve written some code that works with Unicode data, the next problem is input/output. How do you get Unicode strings into your program, and how do you convert Unicode into a form suitable for storage or transmission? It’s possible that you may not need to do anything depending on your input sources and output destinations; you should check whether the libraries used in your application support Unicode natively. XML parsers often return Unicode data, for example. Many relational databases also support Unicode-valued columns and can return Unicode values from an SQL query. Unicode data is usually converted to a particular encoding before it gets written to disk or sent over a socket. It’s possible to do all the work yourself: open a file, read an 8-bit bytes object from it, and convert the bytes with `bytes.decode(encoding)`. However, the manual approach is not recommended. One problem is the multi-byte nature of encodings; one Unicode character can be represented by several bytes. If you want to read the file in arbitrary-sized chunks (say, 1024 or 4096 bytes), you need to write error-handling code to catch the case where only part of the bytes encoding a single Unicode character are read at the end of a chunk. One solution would be to read the entire file into memory and then perform the decoding, but that prevents you from working with files that are extremely large; if you need to read a 2 GiB file, you need 2 GiB of RAM. (More, really, since for at least a moment you’d need to have both the encoded string and its Unicode version in memory.) The solution would be to use the low-level decoding interface to catch the case of partial coding sequences. The work of implementing this has already been done for you: the built-in [`open()`](../library/functions#open "open") function can return a file-like object that assumes the file’s contents are in a specified encoding and accepts Unicode parameters for methods such as [`read()`](../library/io#io.TextIOBase.read "io.TextIOBase.read") and [`write()`](../library/io#io.TextIOBase.write "io.TextIOBase.write"). This works through [`open()`](../library/functions#open "open")’s *encoding* and *errors* parameters which are interpreted just like those in [`str.encode()`](../library/stdtypes#str.encode "str.encode") and [`bytes.decode()`](../library/stdtypes#bytes.decode "bytes.decode"). Reading Unicode from a file is therefore simple: ``` with open('unicode.txt', encoding='utf-8') as f: for line in f: print(repr(line)) ``` It’s also possible to open files in update mode, allowing both reading and writing: ``` with open('test', encoding='utf-8', mode='w+') as f: f.write('\u4500 blah blah blah\n') f.seek(0) print(repr(f.readline()[:1])) ``` The Unicode character `U+FEFF` is used as a byte-order mark (BOM), and is often written as the first character of a file in order to assist with autodetection of the file’s byte ordering. Some encodings, such as UTF-16, expect a BOM to be present at the start of a file; when such an encoding is used, the BOM will be automatically written as the first character and will be silently dropped when the file is read. There are variants of these encodings, such as ‘utf-16-le’ and ‘utf-16-be’ for little-endian and big-endian encodings, that specify one particular byte ordering and don’t skip the BOM. In some areas, it is also convention to use a “BOM” at the start of UTF-8 encoded files; the name is misleading since UTF-8 is not byte-order dependent. The mark simply announces that the file is encoded in UTF-8. For reading such files, use the ‘utf-8-sig’ codec to automatically skip the mark if present. ### Unicode filenames Most of the operating systems in common use today support filenames that contain arbitrary Unicode characters. Usually this is implemented by converting the Unicode string into some encoding that varies depending on the system. Today Python is converging on using UTF-8: Python on MacOS has used UTF-8 for several versions, and Python 3.6 switched to using UTF-8 on Windows as well. On Unix systems, there will only be a filesystem encoding if you’ve set the `LANG` or `LC_CTYPE` environment variables; if you haven’t, the default encoding is again UTF-8. The [`sys.getfilesystemencoding()`](../library/sys#sys.getfilesystemencoding "sys.getfilesystemencoding") function returns the encoding to use on your current system, in case you want to do the encoding manually, but there’s not much reason to bother. When opening a file for reading or writing, you can usually just provide the Unicode string as the filename, and it will be automatically converted to the right encoding for you: ``` filename = 'filename\u4500abc' with open(filename, 'w') as f: f.write('blah\n') ``` Functions in the [`os`](../library/os#module-os "os: Miscellaneous operating system interfaces.") module such as [`os.stat()`](../library/os#os.stat "os.stat") will also accept Unicode filenames. The [`os.listdir()`](../library/os#os.listdir "os.listdir") function returns filenames, which raises an issue: should it return the Unicode version of filenames, or should it return bytes containing the encoded versions? [`os.listdir()`](../library/os#os.listdir "os.listdir") can do both, depending on whether you provided the directory path as bytes or a Unicode string. If you pass a Unicode string as the path, filenames will be decoded using the filesystem’s encoding and a list of Unicode strings will be returned, while passing a byte path will return the filenames as bytes. For example, assuming the default filesystem encoding is UTF-8, running the following program: ``` fn = 'filename\u4500abc' f = open(fn, 'w') f.close() import os print(os.listdir(b'.')) print(os.listdir('.')) ``` will produce the following output: ``` $ python listdir-test.py [b'filename\xe4\x94\x80abc', ...] ['filename\u4500abc', ...] ``` The first list contains UTF-8-encoded filenames, and the second list contains the Unicode versions. Note that on most occasions, you should can just stick with using Unicode with these APIs. The bytes APIs should only be used on systems where undecodable file names can be present; that’s pretty much only Unix systems now. ### Tips for Writing Unicode-aware Programs This section provides some suggestions on writing software that deals with Unicode. The most important tip is: Software should only work with Unicode strings internally, decoding the input data as soon as possible and encoding the output only at the end. If you attempt to write processing functions that accept both Unicode and byte strings, you will find your program vulnerable to bugs wherever you combine the two different kinds of strings. There is no automatic encoding or decoding: if you do e.g. `str + bytes`, a [`TypeError`](../library/exceptions#TypeError "TypeError") will be raised. When using data coming from a web browser or some other untrusted source, a common technique is to check for illegal characters in a string before using the string in a generated command line or storing it in a database. If you’re doing this, be careful to check the decoded string, not the encoded bytes data; some encodings may have interesting properties, such as not being bijective or not being fully ASCII-compatible. This is especially true if the input data also specifies the encoding, since the attacker can then choose a clever way to hide malicious text in the encoded bytestream. #### Converting Between File Encodings The [`StreamRecoder`](../library/codecs#codecs.StreamRecoder "codecs.StreamRecoder") class can transparently convert between encodings, taking a stream that returns data in encoding #1 and behaving like a stream returning data in encoding #2. For example, if you have an input file *f* that’s in Latin-1, you can wrap it with a [`StreamRecoder`](../library/codecs#codecs.StreamRecoder "codecs.StreamRecoder") to return bytes encoded in UTF-8: ``` new_f = codecs.StreamRecoder(f, # en/decoder: used by read() to encode its results and # by write() to decode its input. codecs.getencoder('utf-8'), codecs.getdecoder('utf-8'), # reader/writer: used to read and write to the stream. codecs.getreader('latin-1'), codecs.getwriter('latin-1') ) ``` #### Files in an Unknown Encoding What can you do if you need to make a change to a file, but don’t know the file’s encoding? If you know the encoding is ASCII-compatible and only want to examine or modify the ASCII parts, you can open the file with the `surrogateescape` error handler: ``` with open(fname, 'r', encoding="ascii", errors="surrogateescape") as f: data = f.read() # make changes to the string 'data' with open(fname + '.new', 'w', encoding="ascii", errors="surrogateescape") as f: f.write(data) ``` The `surrogateescape` error handler will decode any non-ASCII bytes as code points in a special range running from U+DC80 to U+DCFF. These code points will then turn back into the same bytes when the `surrogateescape` error handler is used to encode the data and write it back out. ### References One section of [Mastering Python 3 Input/Output](http://pyvideo.org/video/289/pycon-2010--mastering-python-3-i-o), a PyCon 2010 talk by David Beazley, discusses text processing and binary data handling. The [PDF slides for Marc-André Lemburg’s presentation “Writing Unicode-aware Applications in Python”](https://downloads.egenix.com/python/LSM2005-Developing-Unicode-aware-applications-in-Python.pdf) discuss questions of character encodings as well as how to internationalize and localize an application. These slides cover Python 2.x only. [The Guts of Unicode in Python](http://pyvideo.org/video/1768/the-guts-of-unicode-in-python) is a PyCon 2013 talk by Benjamin Peterson that discusses the internal Unicode representation in Python 3.3. Acknowledgements ---------------- The initial draft of this document was written by Andrew Kuchling. It has since been revised further by Alexander Belopolsky, Georg Brandl, Andrew Kuchling, and Ezio Melotti. Thanks to the following people who have noted errors or offered suggestions on this article: Éric Araujo, Nicholas Bastin, Nick Coghlan, Marius Gedminas, Kent Johnson, Ken Krugler, Marc-André Lemburg, Martin von Löwis, Terry J. Reedy, Serhiy Storchaka, Eryk Sun, Chad Whitacre, Graham Wideman.
programming_docs
python Porting Extension Modules to Python 3 Porting Extension Modules to Python 3 ===================================== We recommend the following resources for porting extension modules to Python 3: * The [Migrating C extensions](http://python3porting.com/cextensions.html) chapter from *Supporting Python 3: An in-depth guide*, a book on moving from Python 2 to Python 3 in general, guides the reader through porting an extension module. * The [Porting guide](https://py3c.readthedocs.io/en/latest/guide.html) from the *py3c* project provides opinionated suggestions with supporting code. * The [Cython](http://cython.org/) and [CFFI](https://cffi.readthedocs.io/en/latest/) libraries offer abstractions over Python’s C API. Extensions generally need to be re-written to use one of them, but the library then handles differences between various Python versions and implementations. python An introduction to the ipaddress module An introduction to the ipaddress module ======================================= author Peter Moody author Nick Coghlan Overview This document aims to provide a gentle introduction to the [`ipaddress`](../library/ipaddress#module-ipaddress "ipaddress: IPv4/IPv6 manipulation library.") module. It is aimed primarily at users that aren’t already familiar with IP networking terminology, but may also be useful to network engineers wanting an overview of how [`ipaddress`](../library/ipaddress#module-ipaddress "ipaddress: IPv4/IPv6 manipulation library.") represents IP network addressing concepts. Creating Address/Network/Interface objects ------------------------------------------ Since [`ipaddress`](../library/ipaddress#module-ipaddress "ipaddress: IPv4/IPv6 manipulation library.") is a module for inspecting and manipulating IP addresses, the first thing you’ll want to do is create some objects. You can use [`ipaddress`](../library/ipaddress#module-ipaddress "ipaddress: IPv4/IPv6 manipulation library.") to create objects from strings and integers. ### A Note on IP Versions For readers that aren’t particularly familiar with IP addressing, it’s important to know that the Internet Protocol is currently in the process of moving from version 4 of the protocol to version 6. This transition is occurring largely because version 4 of the protocol doesn’t provide enough addresses to handle the needs of the whole world, especially given the increasing number of devices with direct connections to the internet. Explaining the details of the differences between the two versions of the protocol is beyond the scope of this introduction, but readers need to at least be aware that these two versions exist, and it will sometimes be necessary to force the use of one version or the other. ### IP Host Addresses Addresses, often referred to as “host addresses” are the most basic unit when working with IP addressing. The simplest way to create addresses is to use the [`ipaddress.ip_address()`](../library/ipaddress#ipaddress.ip_address "ipaddress.ip_address") factory function, which automatically determines whether to create an IPv4 or IPv6 address based on the passed in value: ``` >>> ipaddress.ip_address('192.0.2.1') IPv4Address('192.0.2.1') >>> ipaddress.ip_address('2001:DB8::1') IPv6Address('2001:db8::1') ``` Addresses can also be created directly from integers. Values that will fit within 32 bits are assumed to be IPv4 addresses: ``` >>> ipaddress.ip_address(3221225985) IPv4Address('192.0.2.1') >>> ipaddress.ip_address(42540766411282592856903984951653826561) IPv6Address('2001:db8::1') ``` To force the use of IPv4 or IPv6 addresses, the relevant classes can be invoked directly. This is particularly useful to force creation of IPv6 addresses for small integers: ``` >>> ipaddress.ip_address(1) IPv4Address('0.0.0.1') >>> ipaddress.IPv4Address(1) IPv4Address('0.0.0.1') >>> ipaddress.IPv6Address(1) IPv6Address('::1') ``` ### Defining Networks Host addresses are usually grouped together into IP networks, so [`ipaddress`](../library/ipaddress#module-ipaddress "ipaddress: IPv4/IPv6 manipulation library.") provides a way to create, inspect and manipulate network definitions. IP network objects are constructed from strings that define the range of host addresses that are part of that network. The simplest form for that information is a “network address/network prefix” pair, where the prefix defines the number of leading bits that are compared to determine whether or not an address is part of the network and the network address defines the expected value of those bits. As for addresses, a factory function is provided that determines the correct IP version automatically: ``` >>> ipaddress.ip_network('192.0.2.0/24') IPv4Network('192.0.2.0/24') >>> ipaddress.ip_network('2001:db8::0/96') IPv6Network('2001:db8::/96') ``` Network objects cannot have any host bits set. The practical effect of this is that `192.0.2.1/24` does not describe a network. Such definitions are referred to as interface objects since the ip-on-a-network notation is commonly used to describe network interfaces of a computer on a given network and are described further in the next section. By default, attempting to create a network object with host bits set will result in [`ValueError`](../library/exceptions#ValueError "ValueError") being raised. To request that the additional bits instead be coerced to zero, the flag `strict=False` can be passed to the constructor: ``` >>> ipaddress.ip_network('192.0.2.1/24') Traceback (most recent call last): ... ValueError: 192.0.2.1/24 has host bits set >>> ipaddress.ip_network('192.0.2.1/24', strict=False) IPv4Network('192.0.2.0/24') ``` While the string form offers significantly more flexibility, networks can also be defined with integers, just like host addresses. In this case, the network is considered to contain only the single address identified by the integer, so the network prefix includes the entire network address: ``` >>> ipaddress.ip_network(3221225984) IPv4Network('192.0.2.0/32') >>> ipaddress.ip_network(42540766411282592856903984951653826560) IPv6Network('2001:db8::/128') ``` As with addresses, creation of a particular kind of network can be forced by calling the class constructor directly instead of using the factory function. ### Host Interfaces As mentioned just above, if you need to describe an address on a particular network, neither the address nor the network classes are sufficient. Notation like `192.0.2.1/24` is commonly used by network engineers and the people who write tools for firewalls and routers as shorthand for “the host `192.0.2.1` on the network `192.0.2.0/24`”, Accordingly, [`ipaddress`](../library/ipaddress#module-ipaddress "ipaddress: IPv4/IPv6 manipulation library.") provides a set of hybrid classes that associate an address with a particular network. The interface for creation is identical to that for defining network objects, except that the address portion isn’t constrained to being a network address. ``` >>> ipaddress.ip_interface('192.0.2.1/24') IPv4Interface('192.0.2.1/24') >>> ipaddress.ip_interface('2001:db8::1/96') IPv6Interface('2001:db8::1/96') ``` Integer inputs are accepted (as with networks), and use of a particular IP version can be forced by calling the relevant constructor directly. Inspecting Address/Network/Interface Objects -------------------------------------------- You’ve gone to the trouble of creating an IPv(4|6)(Address|Network|Interface) object, so you probably want to get information about it. [`ipaddress`](../library/ipaddress#module-ipaddress "ipaddress: IPv4/IPv6 manipulation library.") tries to make doing this easy and intuitive. Extracting the IP version: ``` >>> addr4 = ipaddress.ip_address('192.0.2.1') >>> addr6 = ipaddress.ip_address('2001:db8::1') >>> addr6.version 6 >>> addr4.version 4 ``` Obtaining the network from an interface: ``` >>> host4 = ipaddress.ip_interface('192.0.2.1/24') >>> host4.network IPv4Network('192.0.2.0/24') >>> host6 = ipaddress.ip_interface('2001:db8::1/96') >>> host6.network IPv6Network('2001:db8::/96') ``` Finding out how many individual addresses are in a network: ``` >>> net4 = ipaddress.ip_network('192.0.2.0/24') >>> net4.num_addresses 256 >>> net6 = ipaddress.ip_network('2001:db8::0/96') >>> net6.num_addresses 4294967296 ``` Iterating through the “usable” addresses on a network: ``` >>> net4 = ipaddress.ip_network('192.0.2.0/24') >>> for x in net4.hosts(): ... print(x) 192.0.2.1 192.0.2.2 192.0.2.3 192.0.2.4 ... 192.0.2.252 192.0.2.253 192.0.2.254 ``` Obtaining the netmask (i.e. set bits corresponding to the network prefix) or the hostmask (any bits that are not part of the netmask): ``` >>> net4 = ipaddress.ip_network('192.0.2.0/24') >>> net4.netmask IPv4Address('255.255.255.0') >>> net4.hostmask IPv4Address('0.0.0.255') >>> net6 = ipaddress.ip_network('2001:db8::0/96') >>> net6.netmask IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff::') >>> net6.hostmask IPv6Address('::ffff:ffff') ``` Exploding or compressing the address: ``` >>> addr6.exploded '2001:0db8:0000:0000:0000:0000:0000:0001' >>> addr6.compressed '2001:db8::1' >>> net6.exploded '2001:0db8:0000:0000:0000:0000:0000:0000/96' >>> net6.compressed '2001:db8::/96' ``` While IPv4 doesn’t support explosion or compression, the associated objects still provide the relevant properties so that version neutral code can easily ensure the most concise or most verbose form is used for IPv6 addresses while still correctly handling IPv4 addresses. Networks as lists of Addresses ------------------------------ It’s sometimes useful to treat networks as lists. This means it is possible to index them like this: ``` >>> net4[1] IPv4Address('192.0.2.1') >>> net4[-1] IPv4Address('192.0.2.255') >>> net6[1] IPv6Address('2001:db8::1') >>> net6[-1] IPv6Address('2001:db8::ffff:ffff') ``` It also means that network objects lend themselves to using the list membership test syntax like this: ``` if address in network: # do something ``` Containment testing is done efficiently based on the network prefix: ``` >>> addr4 = ipaddress.ip_address('192.0.2.1') >>> addr4 in ipaddress.ip_network('192.0.2.0/24') True >>> addr4 in ipaddress.ip_network('192.0.3.0/24') False ``` Comparisons ----------- [`ipaddress`](../library/ipaddress#module-ipaddress "ipaddress: IPv4/IPv6 manipulation library.") provides some simple, hopefully intuitive ways to compare objects, where it makes sense: ``` >>> ipaddress.ip_address('192.0.2.1') < ipaddress.ip_address('192.0.2.2') True ``` A [`TypeError`](../library/exceptions#TypeError "TypeError") exception is raised if you try to compare objects of different versions or different types. Using IP Addresses with other modules ------------------------------------- Other modules that use IP addresses (such as [`socket`](../library/socket#module-socket "socket: Low-level networking interface.")) usually won’t accept objects from this module directly. Instead, they must be coerced to an integer or string that the other module will accept: ``` >>> addr4 = ipaddress.ip_address('192.0.2.1') >>> str(addr4) '192.0.2.1' >>> int(addr4) 3221225985 ``` Getting more detail when instance creation fails ------------------------------------------------ When creating address/network/interface objects using the version-agnostic factory functions, any errors will be reported as [`ValueError`](../library/exceptions#ValueError "ValueError") with a generic error message that simply says the passed in value was not recognized as an object of that type. The lack of a specific error is because it’s necessary to know whether the value is *supposed* to be IPv4 or IPv6 in order to provide more detail on why it has been rejected. To support use cases where it is useful to have access to this additional detail, the individual class constructors actually raise the [`ValueError`](../library/exceptions#ValueError "ValueError") subclasses [`ipaddress.AddressValueError`](../library/ipaddress#ipaddress.AddressValueError "ipaddress.AddressValueError") and [`ipaddress.NetmaskValueError`](../library/ipaddress#ipaddress.NetmaskValueError "ipaddress.NetmaskValueError") to indicate exactly which part of the definition failed to parse correctly. The error messages are significantly more detailed when using the class constructors directly. For example: ``` >>> ipaddress.ip_address("192.168.0.256") Traceback (most recent call last): ... ValueError: '192.168.0.256' does not appear to be an IPv4 or IPv6 address >>> ipaddress.IPv4Address("192.168.0.256") Traceback (most recent call last): ... ipaddress.AddressValueError: Octet 256 (> 255) not permitted in '192.168.0.256' >>> ipaddress.ip_network("192.168.0.1/64") Traceback (most recent call last): ... ValueError: '192.168.0.1/64' does not appear to be an IPv4 or IPv6 network >>> ipaddress.IPv4Network("192.168.0.1/64") Traceback (most recent call last): ... ipaddress.NetmaskValueError: '64' is not a valid netmask ``` However, both of the module specific exceptions have [`ValueError`](../library/exceptions#ValueError "ValueError") as their parent class, so if you’re not concerned with the particular type of error, you can still write code like the following: ``` try: network = ipaddress.IPv4Network(address) except ValueError: print('address/netmask is invalid for IPv4:', address) ``` python Porting Python 2 Code to Python 3 Porting Python 2 Code to Python 3 ================================= author Brett Cannon Abstract With Python 3 being the future of Python while Python 2 is still in active use, it is good to have your project available for both major releases of Python. This guide is meant to help you figure out how best to support both Python 2 & 3 simultaneously. If you are looking to port an extension module instead of pure Python code, please see [Porting Extension Modules to Python 3](cporting#cporting-howto). If you would like to read one core Python developer’s take on why Python 3 came into existence, you can read Nick Coghlan’s [Python 3 Q & A](https://ncoghlan-devs-python-notes.readthedocs.io/en/latest/python3/questions_and_answers.html) or Brett Cannon’s [Why Python 3 exists](https://snarky.ca/why-python-3-exists). For help with porting, you can view the archived [python-porting](https://mail.python.org/pipermail/python-porting/) mailing list. The Short Explanation --------------------- To make your project be single-source Python 2/3 compatible, the basic steps are: 1. Only worry about supporting Python 2.7 2. Make sure you have good test coverage ([coverage.py](https://pypi.org/project/coverage) can help; `python -m pip install coverage`) 3. Learn the differences between Python 2 & 3 4. Use [Futurize](http://python-future.org/automatic_conversion.html) (or [Modernize](https://python-modernize.readthedocs.io/)) to update your code (e.g. `python -m pip install future`) 5. Use [Pylint](https://pypi.org/project/pylint) to help make sure you don’t regress on your Python 3 support (`python -m pip install pylint`) 6. Use [caniusepython3](https://pypi.org/project/caniusepython3) to find out which of your dependencies are blocking your use of Python 3 (`python -m pip install caniusepython3`) 7. Once your dependencies are no longer blocking you, use continuous integration to make sure you stay compatible with Python 2 & 3 ([tox](https://pypi.org/project/tox) can help test against multiple versions of Python; `python -m pip install tox`) 8. Consider using optional static type checking to make sure your type usage works in both Python 2 & 3 (e.g. use [mypy](http://mypy-lang.org/) to check your typing under both Python 2 & Python 3; `python -m pip install mypy`). Note Note: Using `python -m pip install` guarantees that the `pip` you invoke is the one installed for the Python currently in use, whether it be a system-wide `pip` or one installed within a [virtual environment](../tutorial/venv#tut-venv). Details ------- A key point about supporting Python 2 & 3 simultaneously is that you can start **today**! Even if your dependencies are not supporting Python 3 yet that does not mean you can’t modernize your code **now** to support Python 3. Most changes required to support Python 3 lead to cleaner code using newer practices even in Python 2 code. Another key point is that modernizing your Python 2 code to also support Python 3 is largely automated for you. While you might have to make some API decisions thanks to Python 3 clarifying text data versus binary data, the lower-level work is now mostly done for you and thus can at least benefit from the automated changes immediately. Keep those key points in mind while you read on about the details of porting your code to support Python 2 & 3 simultaneously. ### Drop support for Python 2.6 and older While you can make Python 2.5 work with Python 3, it is **much** easier if you only have to work with Python 2.7. If dropping Python 2.5 is not an option then the [six](https://pypi.org/project/six) project can help you support Python 2.5 & 3 simultaneously (`python -m pip install six`). Do realize, though, that nearly all the projects listed in this HOWTO will not be available to you. If you are able to skip Python 2.5 and older, then the required changes to your code should continue to look and feel like idiomatic Python code. At worst you will have to use a function instead of a method in some instances or have to import a function instead of using a built-in one, but otherwise the overall transformation should not feel foreign to you. But you should aim for only supporting Python 2.7. Python 2.6 is no longer freely supported and thus is not receiving bugfixes. This means **you** will have to work around any issues you come across with Python 2.6. There are also some tools mentioned in this HOWTO which do not support Python 2.6 (e.g., [Pylint](https://pypi.org/project/pylint)), and this will become more commonplace as time goes on. It will simply be easier for you if you only support the versions of Python that you have to support. ### Make sure you specify the proper version support in your `setup.py` file In your `setup.py` file you should have the proper [trove classifier](https://pypi.org/classifiers) specifying what versions of Python you support. As your project does not support Python 3 yet you should at least have `Programming Language :: Python :: 2 :: Only` specified. Ideally you should also specify each major/minor version of Python that you do support, e.g. `Programming Language :: Python :: 2.7`. ### Have good test coverage Once you have your code supporting the oldest version of Python 2 you want it to, you will want to make sure your test suite has good coverage. A good rule of thumb is that if you want to be confident enough in your test suite that any failures that appear after having tools rewrite your code are actual bugs in the tools and not in your code. If you want a number to aim for, try to get over 80% coverage (and don’t feel bad if you find it hard to get better than 90% coverage). If you don’t already have a tool to measure test coverage then [coverage.py](https://pypi.org/project/coverage) is recommended. ### Learn the differences between Python 2 & 3 Once you have your code well-tested you are ready to begin porting your code to Python 3! But to fully understand how your code is going to change and what you want to look out for while you code, you will want to learn what changes Python 3 makes in terms of Python 2. Typically the two best ways of doing that is reading the [“What’s New”](https://docs.python.org/3.9/whatsnew/index.html#whatsnew-index) doc for each release of Python 3 and the [Porting to Python 3](http://python3porting.com/) book (which is free online). There is also a handy [cheat sheet](http://python-future.org/compatible_idioms.html) from the Python-Future project. ### Update your code Once you feel like you know what is different in Python 3 compared to Python 2, it’s time to update your code! You have a choice between two tools in porting your code automatically: [Futurize](http://python-future.org/automatic_conversion.html) and [Modernize](https://python-modernize.readthedocs.io/). Which tool you choose will depend on how much like Python 3 you want your code to be. [Futurize](http://python-future.org/automatic_conversion.html) does its best to make Python 3 idioms and practices exist in Python 2, e.g. backporting the `bytes` type from Python 3 so that you have semantic parity between the major versions of Python. [Modernize](https://python-modernize.readthedocs.io/), on the other hand, is more conservative and targets a Python 2/3 subset of Python, directly relying on [six](https://pypi.org/project/six) to help provide compatibility. As Python 3 is the future, it might be best to consider Futurize to begin adjusting to any new practices that Python 3 introduces which you are not accustomed to yet. Regardless of which tool you choose, they will update your code to run under Python 3 while staying compatible with the version of Python 2 you started with. Depending on how conservative you want to be, you may want to run the tool over your test suite first and visually inspect the diff to make sure the transformation is accurate. After you have transformed your test suite and verified that all the tests still pass as expected, then you can transform your application code knowing that any tests which fail is a translation failure. Unfortunately the tools can’t automate everything to make your code work under Python 3 and so there are a handful of things you will need to update manually to get full Python 3 support (which of these steps are necessary vary between the tools). Read the documentation for the tool you choose to use to see what it fixes by default and what it can do optionally to know what will (not) be fixed for you and what you may have to fix on your own (e.g. using `io.open()` over the built-in `open()` function is off by default in Modernize). Luckily, though, there are only a couple of things to watch out for which can be considered large issues that may be hard to debug if not watched for. #### Division In Python 3, `5 / 2 == 2.5` and not `2`; all division between `int` values result in a `float`. This change has actually been planned since Python 2.2 which was released in 2002. Since then users have been encouraged to add `from __future__ import division` to any and all files which use the `/` and `//` operators or to be running the interpreter with the `-Q` flag. If you have not been doing this then you will need to go through your code and do two things: 1. Add `from __future__ import division` to your files 2. Update any division operator as necessary to either use `//` to use floor division or continue using `/` and expect a float The reason that `/` isn’t simply translated to `//` automatically is that if an object defines a `__truediv__` method but not `__floordiv__` then your code would begin to fail (e.g. a user-defined class that uses `/` to signify some operation but not `//` for the same thing or at all). #### Text versus binary data In Python 2 you could use the `str` type for both text and binary data. Unfortunately this confluence of two different concepts could lead to brittle code which sometimes worked for either kind of data, sometimes not. It also could lead to confusing APIs if people didn’t explicitly state that something that accepted `str` accepted either text or binary data instead of one specific type. This complicated the situation especially for anyone supporting multiple languages as APIs wouldn’t bother explicitly supporting `unicode` when they claimed text data support. To make the distinction between text and binary data clearer and more pronounced, Python 3 did what most languages created in the age of the internet have done and made text and binary data distinct types that cannot blindly be mixed together (Python predates widespread access to the internet). For any code that deals only with text or only binary data, this separation doesn’t pose an issue. But for code that has to deal with both, it does mean you might have to now care about when you are using text compared to binary data, which is why this cannot be entirely automated. To start, you will need to decide which APIs take text and which take binary (it is **highly** recommended you don’t design APIs that can take both due to the difficulty of keeping the code working; as stated earlier it is difficult to do well). In Python 2 this means making sure the APIs that take text can work with `unicode` and those that work with binary data work with the `bytes` type from Python 3 (which is a subset of `str` in Python 2 and acts as an alias for `bytes` type in Python 2). Usually the biggest issue is realizing which methods exist on which types in Python 2 & 3 simultaneously (for text that’s `unicode` in Python 2 and `str` in Python 3, for binary that’s `str`/`bytes` in Python 2 and `bytes` in Python 3). The following table lists the **unique** methods of each data type across Python 2 & 3 (e.g., the `decode()` method is usable on the equivalent binary data type in either Python 2 or 3, but it can’t be used by the textual data type consistently between Python 2 and 3 because `str` in Python 3 doesn’t have the method). Do note that as of Python 3.5 the `__mod__` method was added to the bytes type. | | | | --- | --- | | **Text data** | **Binary data** | | | decode | | encode | | | format | | | isdecimal | | | isnumeric | | Making the distinction easier to handle can be accomplished by encoding and decoding between binary data and text at the edge of your code. This means that when you receive text in binary data, you should immediately decode it. And if your code needs to send text as binary data then encode it as late as possible. This allows your code to work with only text internally and thus eliminates having to keep track of what type of data you are working with. The next issue is making sure you know whether the string literals in your code represent text or binary data. You should add a `b` prefix to any literal that presents binary data. For text you should add a `u` prefix to the text literal. (there is a [`__future__`](../library/__future__#module-__future__ "__future__: Future statement definitions") import to force all unspecified literals to be Unicode, but usage has shown it isn’t as effective as adding a `b` or `u` prefix to all literals explicitly) As part of this dichotomy you also need to be careful about opening files. Unless you have been working on Windows, there is a chance you have not always bothered to add the `b` mode when opening a binary file (e.g., `rb` for binary reading). Under Python 3, binary files and text files are clearly distinct and mutually incompatible; see the [`io`](../library/io#module-io "io: Core tools for working with streams.") module for details. Therefore, you **must** make a decision of whether a file will be used for binary access (allowing binary data to be read and/or written) or textual access (allowing text data to be read and/or written). You should also use [`io.open()`](../library/io#io.open "io.open") for opening files instead of the built-in [`open()`](../library/functions#open "open") function as the [`io`](../library/io#module-io "io: Core tools for working with streams.") module is consistent from Python 2 to 3 while the built-in [`open()`](../library/functions#open "open") function is not (in Python 3 it’s actually [`io.open()`](../library/io#io.open "io.open")). Do not bother with the outdated practice of using [`codecs.open()`](../library/codecs#codecs.open "codecs.open") as that’s only necessary for keeping compatibility with Python 2.5. The constructors of both `str` and `bytes` have different semantics for the same arguments between Python 2 & 3. Passing an integer to `bytes` in Python 2 will give you the string representation of the integer: `bytes(3) == '3'`. But in Python 3, an integer argument to `bytes` will give you a bytes object as long as the integer specified, filled with null bytes: `bytes(3) == b'\x00\x00\x00'`. A similar worry is necessary when passing a bytes object to `str`. In Python 2 you just get the bytes object back: `str(b'3') == b'3'`. But in Python 3 you get the string representation of the bytes object: `str(b'3') == "b'3'"`. Finally, the indexing of binary data requires careful handling (slicing does **not** require any special handling). In Python 2, `b'123'[1] == b'2'` while in Python 3 `b'123'[1] == 50`. Because binary data is simply a collection of binary numbers, Python 3 returns the integer value for the byte you index on. But in Python 2 because `bytes == str`, indexing returns a one-item slice of bytes. The [six](https://pypi.org/project/six) project has a function named `six.indexbytes()` which will return an integer like in Python 3: `six.indexbytes(b'123', 1)`. To summarize: 1. Decide which of your APIs take text and which take binary data 2. Make sure that your code that works with text also works with `unicode` and code for binary data works with `bytes` in Python 2 (see the table above for what methods you cannot use for each type) 3. Mark all binary literals with a `b` prefix, textual literals with a `u` prefix 4. Decode binary data to text as soon as possible, encode text as binary data as late as possible 5. Open files using [`io.open()`](../library/io#io.open "io.open") and make sure to specify the `b` mode when appropriate 6. Be careful when indexing into binary data #### Use feature detection instead of version detection Inevitably you will have code that has to choose what to do based on what version of Python is running. The best way to do this is with feature detection of whether the version of Python you’re running under supports what you need. If for some reason that doesn’t work then you should make the version check be against Python 2 and not Python 3. To help explain this, let’s look at an example. Let’s pretend that you need access to a feature of [`importlib`](../library/importlib#module-importlib "importlib: The implementation of the import machinery.") that is available in Python’s standard library since Python 3.3 and available for Python 2 through [importlib2](https://pypi.org/project/importlib2) on PyPI. You might be tempted to write code to access e.g. the [`importlib.abc`](../library/importlib#module-importlib.abc "importlib.abc: Abstract base classes related to import") module by doing the following: ``` import sys if sys.version_info[0] == 3: from importlib import abc else: from importlib2 import abc ``` The problem with this code is what happens when Python 4 comes out? It would be better to treat Python 2 as the exceptional case instead of Python 3 and assume that future Python versions will be more compatible with Python 3 than Python 2: ``` import sys if sys.version_info[0] > 2: from importlib import abc else: from importlib2 import abc ``` The best solution, though, is to do no version detection at all and instead rely on feature detection. That avoids any potential issues of getting the version detection wrong and helps keep you future-compatible: ``` try: from importlib import abc except ImportError: from importlib2 import abc ``` ### Prevent compatibility regressions Once you have fully translated your code to be compatible with Python 3, you will want to make sure your code doesn’t regress and stop working under Python 3. This is especially true if you have a dependency which is blocking you from actually running under Python 3 at the moment. To help with staying compatible, any new modules you create should have at least the following block of code at the top of it: ``` from __future__ import absolute_import from __future__ import division from __future__ import print_function ``` You can also run Python 2 with the `-3` flag to be warned about various compatibility issues your code triggers during execution. If you turn warnings into errors with `-Werror` then you can make sure that you don’t accidentally miss a warning. You can also use the [Pylint](https://pypi.org/project/pylint) project and its `--py3k` flag to lint your code to receive warnings when your code begins to deviate from Python 3 compatibility. This also prevents you from having to run [Modernize](https://python-modernize.readthedocs.io/) or [Futurize](http://python-future.org/automatic_conversion.html) over your code regularly to catch compatibility regressions. This does require you only support Python 2.7 and Python 3.4 or newer as that is Pylint’s minimum Python version support. ### Check which dependencies block your transition **After** you have made your code compatible with Python 3 you should begin to care about whether your dependencies have also been ported. The [caniusepython3](https://pypi.org/project/caniusepython3) project was created to help you determine which projects – directly or indirectly – are blocking you from supporting Python 3. There is both a command-line tool as well as a web interface at <https://caniusepython3.com>. The project also provides code which you can integrate into your test suite so that you will have a failing test when you no longer have dependencies blocking you from using Python 3. This allows you to avoid having to manually check your dependencies and to be notified quickly when you can start running on Python 3. ### Update your `setup.py` file to denote Python 3 compatibility Once your code works under Python 3, you should update the classifiers in your `setup.py` to contain `Programming Language :: Python :: 3` and to not specify sole Python 2 support. This will tell anyone using your code that you support Python 2 **and** 3. Ideally you will also want to add classifiers for each major/minor version of Python you now support. ### Use continuous integration to stay compatible Once you are able to fully run under Python 3 you will want to make sure your code always works under both Python 2 & 3. Probably the best tool for running your tests under multiple Python interpreters is [tox](https://pypi.org/project/tox). You can then integrate tox with your continuous integration system so that you never accidentally break Python 2 or 3 support. You may also want to use the `-bb` flag with the Python 3 interpreter to trigger an exception when you are comparing bytes to strings or bytes to an int (the latter is available starting in Python 3.5). By default type-differing comparisons simply return `False`, but if you made a mistake in your separation of text/binary data handling or indexing on bytes you wouldn’t easily find the mistake. This flag will raise an exception when these kinds of comparisons occur, making the mistake much easier to track down. And that’s mostly it! At this point your code base is compatible with both Python 2 and 3 simultaneously. Your testing will also be set up so that you don’t accidentally break Python 2 or 3 compatibility regardless of which version you typically run your tests under while developing. ### Consider using optional static type checking Another way to help port your code is to use a static type checker like [mypy](http://mypy-lang.org/) or [pytype](https://github.com/google/pytype) on your code. These tools can be used to analyze your code as if it’s being run under Python 2, then you can run the tool a second time as if your code is running under Python 3. By running a static type checker twice like this you can discover if you’re e.g. misusing binary data type in one version of Python compared to another. If you add optional type hints to your code you can also explicitly state whether your APIs use textual or binary data, helping to make sure everything functions as expected in both versions of Python.
programming_docs
python Sorting HOW TO Sorting HOW TO ============== Author Andrew Dalke and Raymond Hettinger Release 0.1 Python lists have a built-in [`list.sort()`](../library/stdtypes#list.sort "list.sort") method that modifies the list in-place. There is also a [`sorted()`](../library/functions#sorted "sorted") built-in function that builds a new sorted list from an iterable. In this document, we explore the various techniques for sorting data using Python. Sorting Basics -------------- A simple ascending sort is very easy: just call the [`sorted()`](../library/functions#sorted "sorted") function. It returns a new sorted list: ``` >>> sorted([5, 2, 3, 1, 4]) [1, 2, 3, 4, 5] ``` You can also use the [`list.sort()`](../library/stdtypes#list.sort "list.sort") method. It modifies the list in-place (and returns `None` to avoid confusion). Usually it’s less convenient than [`sorted()`](../library/functions#sorted "sorted") - but if you don’t need the original list, it’s slightly more efficient. ``` >>> a = [5, 2, 3, 1, 4] >>> a.sort() >>> a [1, 2, 3, 4, 5] ``` Another difference is that the [`list.sort()`](../library/stdtypes#list.sort "list.sort") method is only defined for lists. In contrast, the [`sorted()`](../library/functions#sorted "sorted") function accepts any iterable. ``` >>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}) [1, 2, 3, 4, 5] ``` Key Functions ------------- Both [`list.sort()`](../library/stdtypes#list.sort "list.sort") and [`sorted()`](../library/functions#sorted "sorted") have a *key* parameter to specify a function (or other callable) to be called on each list element prior to making comparisons. For example, here’s a case-insensitive string comparison: ``` >>> sorted("This is a test string from Andrew".split(), key=str.lower) ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This'] ``` The value of the *key* parameter should be a function (or other callable) that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record. A common pattern is to sort complex objects using some of the object’s indices as keys. For example: ``` >>> student_tuples = [ ... ('john', 'A', 15), ... ('jane', 'B', 12), ... ('dave', 'B', 10), ... ] >>> sorted(student_tuples, key=lambda student: student[2]) # sort by age [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] ``` The same technique works for objects with named attributes. For example: ``` >>> class Student: ... def __init__(self, name, grade, age): ... self.name = name ... self.grade = grade ... self.age = age ... def __repr__(self): ... return repr((self.name, self.grade, self.age)) ``` ``` >>> student_objects = [ ... Student('john', 'A', 15), ... Student('jane', 'B', 12), ... Student('dave', 'B', 10), ... ] >>> sorted(student_objects, key=lambda student: student.age) # sort by age [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] ``` Operator Module Functions ------------------------- The key-function patterns shown above are very common, so Python provides convenience functions to make accessor functions easier and faster. The [`operator`](../library/operator#module-operator "operator: Functions corresponding to the standard operators.") module has [`itemgetter()`](../library/operator#operator.itemgetter "operator.itemgetter"), [`attrgetter()`](../library/operator#operator.attrgetter "operator.attrgetter"), and a [`methodcaller()`](../library/operator#operator.methodcaller "operator.methodcaller") function. Using those functions, the above examples become simpler and faster: ``` >>> from operator import itemgetter, attrgetter ``` ``` >>> sorted(student_tuples, key=itemgetter(2)) [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] ``` ``` >>> sorted(student_objects, key=attrgetter('age')) [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] ``` The operator module functions allow multiple levels of sorting. For example, to sort by *grade* then by *age*: ``` >>> sorted(student_tuples, key=itemgetter(1,2)) [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)] ``` ``` >>> sorted(student_objects, key=attrgetter('grade', 'age')) [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)] ``` Ascending and Descending ------------------------ Both [`list.sort()`](../library/stdtypes#list.sort "list.sort") and [`sorted()`](../library/functions#sorted "sorted") accept a *reverse* parameter with a boolean value. This is used to flag descending sorts. For example, to get the student data in reverse *age* order: ``` >>> sorted(student_tuples, key=itemgetter(2), reverse=True) [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] ``` ``` >>> sorted(student_objects, key=attrgetter('age'), reverse=True) [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] ``` Sort Stability and Complex Sorts -------------------------------- Sorts are guaranteed to be [stable](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability). That means that when multiple records have the same key, their original order is preserved. ``` >>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)] >>> sorted(data, key=itemgetter(0)) [('blue', 1), ('blue', 2), ('red', 1), ('red', 2)] ``` Notice how the two records for *blue* retain their original order so that `('blue', 1)` is guaranteed to precede `('blue', 2)`. This wonderful property lets you build complex sorts in a series of sorting steps. For example, to sort the student data by descending *grade* and then ascending *age*, do the *age* sort first and then sort again using *grade*: ``` >>> s = sorted(student_objects, key=attrgetter('age')) # sort on secondary key >>> sorted(s, key=attrgetter('grade'), reverse=True) # now sort on primary key, descending [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] ``` This can be abstracted out into a wrapper function that can take a list and tuples of field and order to sort them on multiple passes. ``` >>> def multisort(xs, specs): ... for key, reverse in reversed(specs): ... xs.sort(key=attrgetter(key), reverse=reverse) ... return xs ``` ``` >>> multisort(list(student_objects), (('grade', True), ('age', False))) [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] ``` The [Timsort](https://en.wikipedia.org/wiki/Timsort) algorithm used in Python does multiple sorts efficiently because it can take advantage of any ordering already present in a dataset. The Old Way Using Decorate-Sort-Undecorate ------------------------------------------ This idiom is called Decorate-Sort-Undecorate after its three steps: * First, the initial list is decorated with new values that control the sort order. * Second, the decorated list is sorted. * Finally, the decorations are removed, creating a list that contains only the initial values in the new order. For example, to sort the student data by *grade* using the DSU approach: ``` >>> decorated = [(student.grade, i, student) for i, student in enumerate(student_objects)] >>> decorated.sort() >>> [student for grade, i, student in decorated] # undecorate [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] ``` This idiom works because tuples are compared lexicographically; the first items are compared; if they are the same then the second items are compared, and so on. It is not strictly necessary in all cases to include the index *i* in the decorated list, but including it gives two benefits: * The sort is stable – if two items have the same key, their order will be preserved in the sorted list. * The original items do not have to be comparable because the ordering of the decorated tuples will be determined by at most the first two items. So for example the original list could contain complex numbers which cannot be sorted directly. Another name for this idiom is [Schwartzian transform](https://en.wikipedia.org/wiki/Schwartzian_transform), after Randal L. Schwartz, who popularized it among Perl programmers. Now that Python sorting provides key-functions, this technique is not often needed. The Old Way Using the *cmp* Parameter ------------------------------------- Many constructs given in this HOWTO assume Python 2.4 or later. Before that, there was no [`sorted()`](../library/functions#sorted "sorted") builtin and [`list.sort()`](../library/stdtypes#list.sort "list.sort") took no keyword arguments. Instead, all of the Py2.x versions supported a *cmp* parameter to handle user specified comparison functions. In Py3.0, the *cmp* parameter was removed entirely (as part of a larger effort to simplify and unify the language, eliminating the conflict between rich comparisons and the `__cmp__()` magic method). In Py2.x, sort allowed an optional function which can be called for doing the comparisons. That function should take two arguments to be compared and then return a negative value for less-than, return zero if they are equal, or return a positive value for greater-than. For example, we can do: ``` >>> def numeric_compare(x, y): ... return x - y >>> sorted([5, 2, 4, 1, 3], cmp=numeric_compare) [1, 2, 3, 4, 5] ``` Or you can reverse the order of comparison with: ``` >>> def reverse_numeric(x, y): ... return y - x >>> sorted([5, 2, 4, 1, 3], cmp=reverse_numeric) [5, 4, 3, 2, 1] ``` When porting code from Python 2.x to 3.x, the situation can arise when you have the user supplying a comparison function and you need to convert that to a key function. The following wrapper makes that easy to do: ``` def cmp_to_key(mycmp): 'Convert a cmp= function into a key= function' class K: def __init__(self, obj, *args): self.obj = obj def __lt__(self, other): return mycmp(self.obj, other.obj) < 0 def __gt__(self, other): return mycmp(self.obj, other.obj) > 0 def __eq__(self, other): return mycmp(self.obj, other.obj) == 0 def __le__(self, other): return mycmp(self.obj, other.obj) <= 0 def __ge__(self, other): return mycmp(self.obj, other.obj) >= 0 def __ne__(self, other): return mycmp(self.obj, other.obj) != 0 return K ``` To convert to a key function, just wrap the old comparison function: ``` >>> sorted([5, 2, 4, 1, 3], key=cmp_to_key(reverse_numeric)) [5, 4, 3, 2, 1] ``` In Python 3.2, the [`functools.cmp_to_key()`](../library/functools#functools.cmp_to_key "functools.cmp_to_key") function was added to the [`functools`](../library/functools#module-functools "functools: Higher-order functions and operations on callable objects.") module in the standard library. Odd and Ends ------------ * For locale aware sorting, use [`locale.strxfrm()`](../library/locale#locale.strxfrm "locale.strxfrm") for a key function or [`locale.strcoll()`](../library/locale#locale.strcoll "locale.strcoll") for a comparison function. * The *reverse* parameter still maintains sort stability (so that records with equal keys retain the original order). Interestingly, that effect can be simulated without the parameter by using the builtin [`reversed()`](../library/functions#reversed "reversed") function twice: ``` >>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)] >>> standard_way = sorted(data, key=itemgetter(0), reverse=True) >>> double_reversed = list(reversed(sorted(reversed(data), key=itemgetter(0)))) >>> assert standard_way == double_reversed >>> standard_way [('red', 1), ('red', 2), ('blue', 1), ('blue', 2)] ``` * The sort routines use `<` when making comparisons between two objects. So, it is easy to add a standard sort order to a class by defining an [`__lt__()`](../reference/datamodel#object.__lt__ "object.__lt__") method: ``` >>> Student.__lt__ = lambda self, other: self.age < other.age >>> sorted(student_objects) [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] ``` However, note that `<` can fall back to using [`__gt__()`](../reference/datamodel#object.__gt__ "object.__gt__") if [`__lt__()`](../reference/datamodel#object.__lt__ "object.__lt__") is not implemented (see [`object.__lt__()`](../reference/datamodel#object.__lt__ "object.__lt__")). * Key functions need not depend directly on the objects being sorted. A key function can also access external resources. For instance, if the student grades are stored in a dictionary, they can be used to sort a separate list of student names: ``` >>> students = ['dave', 'john', 'jane'] >>> newgrades = {'john': 'F', 'jane':'A', 'dave': 'C'} >>> sorted(students, key=newgrades.__getitem__) ['jane', 'dave', 'john'] ``` python Logging HOWTO Logging HOWTO ============= Author Vinay Sajip <vinay\_sajip at red-dove dot com> Basic Logging Tutorial ---------------------- Logging is a means of tracking events that happen when some software runs. The software’s developer adds logging calls to their code to indicate that certain events have occurred. An event is described by a descriptive message which can optionally contain variable data (i.e. data that is potentially different for each occurrence of the event). Events also have an importance which the developer ascribes to the event; the importance can also be called the *level* or *severity*. ### When to use logging Logging provides a set of convenience functions for simple logging usage. These are [`debug()`](../library/logging#logging.debug "logging.debug"), [`info()`](../library/logging#logging.info "logging.info"), [`warning()`](../library/logging#logging.warning "logging.warning"), [`error()`](../library/logging#logging.error "logging.error") and [`critical()`](../library/logging#logging.critical "logging.critical"). To determine when to use logging, see the table below, which states, for each of a set of common tasks, the best tool to use for it. | Task you want to perform | The best tool for the task | | --- | --- | | Display console output for ordinary usage of a command line script or program | [`print()`](../library/functions#print "print") | | Report events that occur during normal operation of a program (e.g. for status monitoring or fault investigation) | [`logging.info()`](../library/logging#logging.info "logging.info") (or [`logging.debug()`](../library/logging#logging.debug "logging.debug") for very detailed output for diagnostic purposes) | | Issue a warning regarding a particular runtime event | [`warnings.warn()`](../library/warnings#warnings.warn "warnings.warn") in library code if the issue is avoidable and the client application should be modified to eliminate the warning [`logging.warning()`](../library/logging#logging.warning "logging.warning") if there is nothing the client application can do about the situation, but the event should still be noted | | Report an error regarding a particular runtime event | Raise an exception | | Report suppression of an error without raising an exception (e.g. error handler in a long-running server process) | [`logging.error()`](../library/logging#logging.error "logging.error"), [`logging.exception()`](../library/logging#logging.exception "logging.exception") or [`logging.critical()`](../library/logging#logging.critical "logging.critical") as appropriate for the specific error and application domain | The logging functions are named after the level or severity of the events they are used to track. The standard levels and their applicability are described below (in increasing order of severity): | Level | When it’s used | | --- | --- | | `DEBUG` | Detailed information, typically of interest only when diagnosing problems. | | `INFO` | Confirmation that things are working as expected. | | `WARNING` | An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected. | | `ERROR` | Due to a more serious problem, the software has not been able to perform some function. | | `CRITICAL` | A serious error, indicating that the program itself may be unable to continue running. | The default level is `WARNING`, which means that only events of this level and above will be tracked, unless the logging package is configured to do otherwise. Events that are tracked can be handled in different ways. The simplest way of handling tracked events is to print them to the console. Another common way is to write them to a disk file. ### A simple example A very simple example is: ``` import logging logging.warning('Watch out!') # will print a message to the console logging.info('I told you so') # will not print anything ``` If you type these lines into a script and run it, you’ll see: ``` WARNING:root:Watch out! ``` printed out on the console. The `INFO` message doesn’t appear because the default level is `WARNING`. The printed message includes the indication of the level and the description of the event provided in the logging call, i.e. ‘Watch out!’. Don’t worry about the ‘root’ part for now: it will be explained later. The actual output can be formatted quite flexibly if you need that; formatting options will also be explained later. ### Logging to a file A very common situation is that of recording logging events in a file, so let’s look at that next. Be sure to try the following in a newly-started Python interpreter, and don’t just continue from the session described above: ``` import logging logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG) logging.debug('This message should go to the log file') logging.info('So should this') logging.warning('And this, too') logging.error('And non-ASCII stuff, too, like Øresund and Malmö') ``` Changed in version 3.9: The *encoding* argument was added. In earlier Python versions, or if not specified, the encoding used is the default value used by [`open()`](../library/functions#open "open"). While not shown in the above example, an *errors* argument can also now be passed, which determines how encoding errors are handled. For available values and the default, see the documentation for [`open()`](../library/functions#open "open"). And now if we open the file and look at what we have, we should find the log messages: ``` DEBUG:root:This message should go to the log file INFO:root:So should this WARNING:root:And this, too ERROR:root:And non-ASCII stuff, too, like Øresund and Malmö ``` This example also shows how you can set the logging level which acts as the threshold for tracking. In this case, because we set the threshold to `DEBUG`, all of the messages were printed. If you want to set the logging level from a command-line option such as: ``` --log=INFO ``` and you have the value of the parameter passed for `--log` in some variable *loglevel*, you can use: ``` getattr(logging, loglevel.upper()) ``` to get the value which you’ll pass to [`basicConfig()`](../library/logging#logging.basicConfig "logging.basicConfig") via the *level* argument. You may want to error check any user input value, perhaps as in the following example: ``` # assuming loglevel is bound to the string value obtained from the # command line argument. Convert to upper case to allow the user to # specify --log=DEBUG or --log=debug numeric_level = getattr(logging, loglevel.upper(), None) if not isinstance(numeric_level, int): raise ValueError('Invalid log level: %s' % loglevel) logging.basicConfig(level=numeric_level, ...) ``` The call to [`basicConfig()`](../library/logging#logging.basicConfig "logging.basicConfig") should come *before* any calls to [`debug()`](../library/logging#logging.debug "logging.debug"), [`info()`](../library/logging#logging.info "logging.info") etc. As it’s intended as a one-off simple configuration facility, only the first call will actually do anything: subsequent calls are effectively no-ops. If you run the above script several times, the messages from successive runs are appended to the file *example.log*. If you want each run to start afresh, not remembering the messages from earlier runs, you can specify the *filemode* argument, by changing the call in the above example to: ``` logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG) ``` The output will be the same as before, but the log file is no longer appended to, so the messages from earlier runs are lost. ### Logging from multiple modules If your program consists of multiple modules, here’s an example of how you could organize logging in it: ``` # myapp.py import logging import mylib def main(): logging.basicConfig(filename='myapp.log', level=logging.INFO) logging.info('Started') mylib.do_something() logging.info('Finished') if __name__ == '__main__': main() ``` ``` # mylib.py import logging def do_something(): logging.info('Doing something') ``` If you run *myapp.py*, you should see this in *myapp.log*: ``` INFO:root:Started INFO:root:Doing something INFO:root:Finished ``` which is hopefully what you were expecting to see. You can generalize this to multiple modules, using the pattern in *mylib.py*. Note that for this simple usage pattern, you won’t know, by looking in the log file, *where* in your application your messages came from, apart from looking at the event description. If you want to track the location of your messages, you’ll need to refer to the documentation beyond the tutorial level – see [Advanced Logging Tutorial](#logging-advanced-tutorial). ### Logging variable data To log variable data, use a format string for the event description message and append the variable data as arguments. For example: ``` import logging logging.warning('%s before you %s', 'Look', 'leap!') ``` will display: ``` WARNING:root:Look before you leap! ``` As you can see, merging of variable data into the event description message uses the old, %-style of string formatting. This is for backwards compatibility: the logging package pre-dates newer formatting options such as [`str.format()`](../library/stdtypes#str.format "str.format") and [`string.Template`](../library/string#string.Template "string.Template"). These newer formatting options *are* supported, but exploring them is outside the scope of this tutorial: see [Using particular formatting styles throughout your application](logging-cookbook#formatting-styles) for more information. ### Changing the format of displayed messages To change the format which is used to display messages, you need to specify the format you want to use: ``` import logging logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG) logging.debug('This message should appear on the console') logging.info('So should this') logging.warning('And this, too') ``` which would print: ``` DEBUG:This message should appear on the console INFO:So should this WARNING:And this, too ``` Notice that the ‘root’ which appeared in earlier examples has disappeared. For a full set of things that can appear in format strings, you can refer to the documentation for [LogRecord attributes](../library/logging#logrecord-attributes), but for simple usage, you just need the *levelname* (severity), *message* (event description, including variable data) and perhaps to display when the event occurred. This is described in the next section. ### Displaying the date/time in messages To display the date and time of an event, you would place ‘%(asctime)s’ in your format string: ``` import logging logging.basicConfig(format='%(asctime)s %(message)s') logging.warning('is when this event was logged.') ``` which should print something like this: ``` 2010-12-12 11:41:42,612 is when this event was logged. ``` The default format for date/time display (shown above) is like ISO8601 or [**RFC 3339**](https://tools.ietf.org/html/rfc3339.html). If you need more control over the formatting of the date/time, provide a *datefmt* argument to `basicConfig`, as in this example: ``` import logging logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') logging.warning('is when this event was logged.') ``` which would display something like this: ``` 12/12/2010 11:46:36 AM is when this event was logged. ``` The format of the *datefmt* argument is the same as supported by [`time.strftime()`](../library/time#time.strftime "time.strftime"). ### Next Steps That concludes the basic tutorial. It should be enough to get you up and running with logging. There’s a lot more that the logging package offers, but to get the best out of it, you’ll need to invest a little more of your time in reading the following sections. If you’re ready for that, grab some of your favourite beverage and carry on. If your logging needs are simple, then use the above examples to incorporate logging into your own scripts, and if you run into problems or don’t understand something, please post a question on the comp.lang.python Usenet group (available at <https://groups.google.com/forum/#!forum/comp.lang.python>) and you should receive help before too long. Still here? You can carry on reading the next few sections, which provide a slightly more advanced/in-depth tutorial than the basic one above. After that, you can take a look at the [Logging Cookbook](logging-cookbook#logging-cookbook). Advanced Logging Tutorial ------------------------- The logging library takes a modular approach and offers several categories of components: loggers, handlers, filters, and formatters. * Loggers expose the interface that application code directly uses. * Handlers send the log records (created by loggers) to the appropriate destination. * Filters provide a finer grained facility for determining which log records to output. * Formatters specify the layout of log records in the final output. Log event information is passed between loggers, handlers, filters and formatters in a [`LogRecord`](../library/logging#logging.LogRecord "logging.LogRecord") instance. Logging is performed by calling methods on instances of the [`Logger`](../library/logging#logging.Logger "logging.Logger") class (hereafter called *loggers*). Each instance has a name, and they are conceptually arranged in a namespace hierarchy using dots (periods) as separators. For example, a logger named ‘scan’ is the parent of loggers ‘scan.text’, ‘scan.html’ and ‘scan.pdf’. Logger names can be anything you want, and indicate the area of an application in which a logged message originates. A good convention to use when naming loggers is to use a module-level logger, in each module which uses logging, named as follows: ``` logger = logging.getLogger(__name__) ``` This means that logger names track the package/module hierarchy, and it’s intuitively obvious where events are logged just from the logger name. The root of the hierarchy of loggers is called the root logger. That’s the logger used by the functions [`debug()`](../library/logging#logging.debug "logging.debug"), [`info()`](../library/logging#logging.info "logging.info"), [`warning()`](../library/logging#logging.warning "logging.warning"), [`error()`](../library/logging#logging.error "logging.error") and [`critical()`](../library/logging#logging.critical "logging.critical"), which just call the same-named method of the root logger. The functions and the methods have the same signatures. The root logger’s name is printed as ‘root’ in the logged output. It is, of course, possible to log messages to different destinations. Support is included in the package for writing log messages to files, HTTP GET/POST locations, email via SMTP, generic sockets, queues, or OS-specific logging mechanisms such as syslog or the Windows NT event log. Destinations are served by *handler* classes. You can create your own log destination class if you have special requirements not met by any of the built-in handler classes. By default, no destination is set for any logging messages. You can specify a destination (such as console or file) by using [`basicConfig()`](../library/logging#logging.basicConfig "logging.basicConfig") as in the tutorial examples. If you call the functions [`debug()`](../library/logging#logging.debug "logging.debug"), [`info()`](../library/logging#logging.info "logging.info"), [`warning()`](../library/logging#logging.warning "logging.warning"), [`error()`](../library/logging#logging.error "logging.error") and [`critical()`](../library/logging#logging.critical "logging.critical"), they will check to see if no destination is set; and if one is not set, they will set a destination of the console (`sys.stderr`) and a default format for the displayed message before delegating to the root logger to do the actual message output. The default format set by [`basicConfig()`](../library/logging#logging.basicConfig "logging.basicConfig") for messages is: ``` severity:logger name:message ``` You can change this by passing a format string to [`basicConfig()`](../library/logging#logging.basicConfig "logging.basicConfig") with the *format* keyword argument. For all options regarding how a format string is constructed, see [Formatter Objects](../library/logging#formatter-objects). ### Logging Flow The flow of log event information in loggers and handlers is illustrated in the following diagram. ### Loggers [`Logger`](../library/logging#logging.Logger "logging.Logger") objects have a threefold job. First, they expose several methods to application code so that applications can log messages at runtime. Second, logger objects determine which log messages to act upon based upon severity (the default filtering facility) or filter objects. Third, logger objects pass along relevant log messages to all interested log handlers. The most widely used methods on logger objects fall into two categories: configuration and message sending. These are the most common configuration methods: * [`Logger.setLevel()`](../library/logging#logging.Logger.setLevel "logging.Logger.setLevel") specifies the lowest-severity log message a logger will handle, where debug is the lowest built-in severity level and critical is the highest built-in severity. For example, if the severity level is INFO, the logger will handle only INFO, WARNING, ERROR, and CRITICAL messages and will ignore DEBUG messages. * [`Logger.addHandler()`](../library/logging#logging.Logger.addHandler "logging.Logger.addHandler") and [`Logger.removeHandler()`](../library/logging#logging.Logger.removeHandler "logging.Logger.removeHandler") add and remove handler objects from the logger object. Handlers are covered in more detail in [Handlers](#handler-basic). * [`Logger.addFilter()`](../library/logging#logging.Logger.addFilter "logging.Logger.addFilter") and [`Logger.removeFilter()`](../library/logging#logging.Logger.removeFilter "logging.Logger.removeFilter") add and remove filter objects from the logger object. Filters are covered in more detail in [Filter Objects](../library/logging#filter). You don’t need to always call these methods on every logger you create. See the last two paragraphs in this section. With the logger object configured, the following methods create log messages: * [`Logger.debug()`](../library/logging#logging.Logger.debug "logging.Logger.debug"), [`Logger.info()`](../library/logging#logging.Logger.info "logging.Logger.info"), [`Logger.warning()`](../library/logging#logging.Logger.warning "logging.Logger.warning"), [`Logger.error()`](../library/logging#logging.Logger.error "logging.Logger.error"), and [`Logger.critical()`](../library/logging#logging.Logger.critical "logging.Logger.critical") all create log records with a message and a level that corresponds to their respective method names. The message is actually a format string, which may contain the standard string substitution syntax of `%s`, `%d`, `%f`, and so on. The rest of their arguments is a list of objects that correspond with the substitution fields in the message. With regard to `**kwargs`, the logging methods care only about a keyword of `exc_info` and use it to determine whether to log exception information. * [`Logger.exception()`](../library/logging#logging.Logger.exception "logging.Logger.exception") creates a log message similar to [`Logger.error()`](../library/logging#logging.Logger.error "logging.Logger.error"). The difference is that [`Logger.exception()`](../library/logging#logging.Logger.exception "logging.Logger.exception") dumps a stack trace along with it. Call this method only from an exception handler. * [`Logger.log()`](../library/logging#logging.Logger.log "logging.Logger.log") takes a log level as an explicit argument. This is a little more verbose for logging messages than using the log level convenience methods listed above, but this is how to log at custom log levels. [`getLogger()`](../library/logging#logging.getLogger "logging.getLogger") returns a reference to a logger instance with the specified name if it is provided, or `root` if not. The names are period-separated hierarchical structures. Multiple calls to [`getLogger()`](../library/logging#logging.getLogger "logging.getLogger") with the same name will return a reference to the same logger object. Loggers that are further down in the hierarchical list are children of loggers higher up in the list. For example, given a logger with a name of `foo`, loggers with names of `foo.bar`, `foo.bar.baz`, and `foo.bam` are all descendants of `foo`. Loggers have a concept of *effective level*. If a level is not explicitly set on a logger, the level of its parent is used instead as its effective level. If the parent has no explicit level set, *its* parent is examined, and so on - all ancestors are searched until an explicitly set level is found. The root logger always has an explicit level set (`WARNING` by default). When deciding whether to process an event, the effective level of the logger is used to determine whether the event is passed to the logger’s handlers. Child loggers propagate messages up to the handlers associated with their ancestor loggers. Because of this, it is unnecessary to define and configure handlers for all the loggers an application uses. It is sufficient to configure handlers for a top-level logger and create child loggers as needed. (You can, however, turn off propagation by setting the *propagate* attribute of a logger to `False`.) ### Handlers [`Handler`](../library/logging#logging.Handler "logging.Handler") objects are responsible for dispatching the appropriate log messages (based on the log messages’ severity) to the handler’s specified destination. [`Logger`](../library/logging#logging.Logger "logging.Logger") objects can add zero or more handler objects to themselves with an [`addHandler()`](../library/logging#logging.Logger.addHandler "logging.Logger.addHandler") method. As an example scenario, an application may want to send all log messages to a log file, all log messages of error or higher to stdout, and all messages of critical to an email address. This scenario requires three individual handlers where each handler is responsible for sending messages of a specific severity to a specific location. The standard library includes quite a few handler types (see [Useful Handlers](#useful-handlers)); the tutorials use mainly [`StreamHandler`](../library/logging.handlers#logging.StreamHandler "logging.StreamHandler") and [`FileHandler`](../library/logging.handlers#logging.FileHandler "logging.FileHandler") in its examples. There are very few methods in a handler for application developers to concern themselves with. The only handler methods that seem relevant for application developers who are using the built-in handler objects (that is, not creating custom handlers) are the following configuration methods: * The [`setLevel()`](../library/logging#logging.Handler.setLevel "logging.Handler.setLevel") method, just as in logger objects, specifies the lowest severity that will be dispatched to the appropriate destination. Why are there two `setLevel()` methods? The level set in the logger determines which severity of messages it will pass to its handlers. The level set in each handler determines which messages that handler will send on. * [`setFormatter()`](../library/logging#logging.Handler.setFormatter "logging.Handler.setFormatter") selects a Formatter object for this handler to use. * [`addFilter()`](../library/logging#logging.Handler.addFilter "logging.Handler.addFilter") and [`removeFilter()`](../library/logging#logging.Handler.removeFilter "logging.Handler.removeFilter") respectively configure and deconfigure filter objects on handlers. Application code should not directly instantiate and use instances of [`Handler`](../library/logging#logging.Handler "logging.Handler"). Instead, the [`Handler`](../library/logging#logging.Handler "logging.Handler") class is a base class that defines the interface that all handlers should have and establishes some default behavior that child classes can use (or override). ### Formatters Formatter objects configure the final order, structure, and contents of the log message. Unlike the base [`logging.Handler`](../library/logging#logging.Handler "logging.Handler") class, application code may instantiate formatter classes, although you could likely subclass the formatter if your application needs special behavior. The constructor takes three optional arguments – a message format string, a date format string and a style indicator. `logging.Formatter.__init__(fmt=None, datefmt=None, style='%')` If there is no message format string, the default is to use the raw message. If there is no date format string, the default date format is: ``` %Y-%m-%d %H:%M:%S ``` with the milliseconds tacked on at the end. The `style` is one of `%`, ‘{’ or ‘$’. If one of these is not specified, then ‘%’ will be used. If the `style` is ‘%’, the message format string uses `%(<dictionary key>)s` styled string substitution; the possible keys are documented in [LogRecord attributes](../library/logging#logrecord-attributes). If the style is ‘{’, the message format string is assumed to be compatible with [`str.format()`](../library/stdtypes#str.format "str.format") (using keyword arguments), while if the style is ‘$’ then the message format string should conform to what is expected by [`string.Template.substitute()`](../library/string#string.Template.substitute "string.Template.substitute"). Changed in version 3.2: Added the `style` parameter. The following message format string will log the time in a human-readable format, the severity of the message, and the contents of the message, in that order: ``` '%(asctime)s - %(levelname)s - %(message)s' ``` Formatters use a user-configurable function to convert the creation time of a record to a tuple. By default, [`time.localtime()`](../library/time#time.localtime "time.localtime") is used; to change this for a particular formatter instance, set the `converter` attribute of the instance to a function with the same signature as [`time.localtime()`](../library/time#time.localtime "time.localtime") or [`time.gmtime()`](../library/time#time.gmtime "time.gmtime"). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the `converter` attribute in the Formatter class (to `time.gmtime` for GMT display). ### Configuring Logging Programmers can configure logging in three ways: 1. Creating loggers, handlers, and formatters explicitly using Python code that calls the configuration methods listed above. 2. Creating a logging config file and reading it using the [`fileConfig()`](../library/logging.config#logging.config.fileConfig "logging.config.fileConfig") function. 3. Creating a dictionary of configuration information and passing it to the [`dictConfig()`](../library/logging.config#logging.config.dictConfig "logging.config.dictConfig") function. For the reference documentation on the last two options, see [Configuration functions](../library/logging.config#logging-config-api). The following example configures a very simple logger, a console handler, and a simple formatter using Python code: ``` import logging # create logger logger = logging.getLogger('simple_example') logger.setLevel(logging.DEBUG) # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # add formatter to ch ch.setFormatter(formatter) # add ch to logger logger.addHandler(ch) # 'application' code logger.debug('debug message') logger.info('info message') logger.warning('warn message') logger.error('error message') logger.critical('critical message') ``` Running this module from the command line produces the following output: ``` $ python simple_logging_module.py 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message 2005-03-19 15:10:26,620 - simple_example - INFO - info message 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message 2005-03-19 15:10:26,697 - simple_example - ERROR - error message 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message ``` The following Python module creates a logger, handler, and formatter nearly identical to those in the example listed above, with the only difference being the names of the objects: ``` import logging import logging.config logging.config.fileConfig('logging.conf') # create logger logger = logging.getLogger('simpleExample') # 'application' code logger.debug('debug message') logger.info('info message') logger.warning('warn message') logger.error('error message') logger.critical('critical message') ``` Here is the logging.conf file: ``` [loggers] keys=root,simpleExample [handlers] keys=consoleHandler [formatters] keys=simpleFormatter [logger_root] level=DEBUG handlers=consoleHandler [logger_simpleExample] level=DEBUG handlers=consoleHandler qualname=simpleExample propagate=0 [handler_consoleHandler] class=StreamHandler level=DEBUG formatter=simpleFormatter args=(sys.stdout,) [formatter_simpleFormatter] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s datefmt= ``` The output is nearly identical to that of the non-config-file-based example: ``` $ python simple_logging_config.py 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message 2005-03-19 15:38:55,979 - simpleExample - INFO - info message 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message ``` You can see that the config file approach has a few advantages over the Python code approach, mainly separation of configuration and code and the ability of noncoders to easily modify the logging properties. Warning The [`fileConfig()`](../library/logging.config#logging.config.fileConfig "logging.config.fileConfig") function takes a default parameter, `disable_existing_loggers`, which defaults to `True` for reasons of backward compatibility. This may or may not be what you want, since it will cause any non-root loggers existing before the [`fileConfig()`](../library/logging.config#logging.config.fileConfig "logging.config.fileConfig") call to be disabled unless they (or an ancestor) are explicitly named in the configuration. Please refer to the reference documentation for more information, and specify `False` for this parameter if you wish. The dictionary passed to [`dictConfig()`](../library/logging.config#logging.config.dictConfig "logging.config.dictConfig") can also specify a Boolean value with key `disable_existing_loggers`, which if not specified explicitly in the dictionary also defaults to being interpreted as `True`. This leads to the logger-disabling behaviour described above, which may not be what you want - in which case, provide the key explicitly with a value of `False`. Note that the class names referenced in config files need to be either relative to the logging module, or absolute values which can be resolved using normal import mechanisms. Thus, you could use either [`WatchedFileHandler`](../library/logging.handlers#logging.handlers.WatchedFileHandler "logging.handlers.WatchedFileHandler") (relative to the logging module) or `mypackage.mymodule.MyHandler` (for a class defined in package `mypackage` and module `mymodule`, where `mypackage` is available on the Python import path). In Python 3.2, a new means of configuring logging has been introduced, using dictionaries to hold configuration information. This provides a superset of the functionality of the config-file-based approach outlined above, and is the recommended configuration method for new applications and deployments. Because a Python dictionary is used to hold configuration information, and since you can populate that dictionary using different means, you have more options for configuration. For example, you can use a configuration file in JSON format, or, if you have access to YAML processing functionality, a file in YAML format, to populate the configuration dictionary. Or, of course, you can construct the dictionary in Python code, receive it in pickled form over a socket, or use whatever approach makes sense for your application. Here’s an example of the same configuration as above, in YAML format for the new dictionary-based approach: ``` version: 1 formatters: simple: format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' handlers: console: class: logging.StreamHandler level: DEBUG formatter: simple stream: ext://sys.stdout loggers: simpleExample: level: DEBUG handlers: [console] propagate: no root: level: DEBUG handlers: [console] ``` For more information about logging using a dictionary, see [Configuration functions](../library/logging.config#logging-config-api). ### What happens if no configuration is provided If no logging configuration is provided, it is possible to have a situation where a logging event needs to be output, but no handlers can be found to output the event. The behaviour of the logging package in these circumstances is dependent on the Python version. For versions of Python prior to 3.2, the behaviour is as follows: * If *logging.raiseExceptions* is `False` (production mode), the event is silently dropped. * If *logging.raiseExceptions* is `True` (development mode), a message ‘No handlers could be found for logger X.Y.Z’ is printed once. In Python 3.2 and later, the behaviour is as follows: * The event is output using a ‘handler of last resort’, stored in `logging.lastResort`. This internal handler is not associated with any logger, and acts like a [`StreamHandler`](../library/logging.handlers#logging.StreamHandler "logging.StreamHandler") which writes the event description message to the current value of `sys.stderr` (therefore respecting any redirections which may be in effect). No formatting is done on the message - just the bare event description message is printed. The handler’s level is set to `WARNING`, so all events at this and greater severities will be output. To obtain the pre-3.2 behaviour, `logging.lastResort` can be set to `None`. ### Configuring Logging for a Library When developing a library which uses logging, you should take care to document how the library uses logging - for example, the names of loggers used. Some consideration also needs to be given to its logging configuration. If the using application does not use logging, and library code makes logging calls, then (as described in the previous section) events of severity `WARNING` and greater will be printed to `sys.stderr`. This is regarded as the best default behaviour. If for some reason you *don’t* want these messages printed in the absence of any logging configuration, you can attach a do-nothing handler to the top-level logger for your library. This avoids the message being printed, since a handler will always be found for the library’s events: it just doesn’t produce any output. If the library user configures logging for application use, presumably that configuration will add some handlers, and if levels are suitably configured then logging calls made in library code will send output to those handlers, as normal. A do-nothing handler is included in the logging package: [`NullHandler`](../library/logging.handlers#logging.NullHandler "logging.NullHandler") (since Python 3.1). An instance of this handler could be added to the top-level logger of the logging namespace used by the library (*if* you want to prevent your library’s logged events being output to `sys.stderr` in the absence of logging configuration). If all logging by a library *foo* is done using loggers with names matching ‘foo.x’, ‘foo.x.y’, etc. then the code: ``` import logging logging.getLogger('foo').addHandler(logging.NullHandler()) ``` should have the desired effect. If an organisation produces a number of libraries, then the logger name specified can be ‘orgname.foo’ rather than just ‘foo’. Note It is strongly advised that you *do not add any handlers other than* [`NullHandler`](../library/logging.handlers#logging.NullHandler "logging.NullHandler") *to your library’s loggers*. This is because the configuration of handlers is the prerogative of the application developer who uses your library. The application developer knows their target audience and what handlers are most appropriate for their application: if you add handlers ‘under the hood’, you might well interfere with their ability to carry out unit tests and deliver logs which suit their requirements. Logging Levels -------------- The numeric values of logging levels are given in the following table. These are primarily of interest if you want to define your own levels, and need them to have specific values relative to the predefined levels. If you define a level with the same numeric value, it overwrites the predefined value; the predefined name is lost. | Level | Numeric value | | --- | --- | | `CRITICAL` | 50 | | `ERROR` | 40 | | `WARNING` | 30 | | `INFO` | 20 | | `DEBUG` | 10 | | `NOTSET` | 0 | Levels can also be associated with loggers, being set either by the developer or through loading a saved logging configuration. When a logging method is called on a logger, the logger compares its own level with the level associated with the method call. If the logger’s level is higher than the method call’s, no logging message is actually generated. This is the basic mechanism controlling the verbosity of logging output. Logging messages are encoded as instances of the [`LogRecord`](../library/logging#logging.LogRecord "logging.LogRecord") class. When a logger decides to actually log an event, a [`LogRecord`](../library/logging#logging.LogRecord "logging.LogRecord") instance is created from the logging message. Logging messages are subjected to a dispatch mechanism through the use of *handlers*, which are instances of subclasses of the [`Handler`](../library/logging#logging.Handler "logging.Handler") class. Handlers are responsible for ensuring that a logged message (in the form of a [`LogRecord`](../library/logging#logging.LogRecord "logging.LogRecord")) ends up in a particular location (or set of locations) which is useful for the target audience for that message (such as end users, support desk staff, system administrators, developers). Handlers are passed [`LogRecord`](../library/logging#logging.LogRecord "logging.LogRecord") instances intended for particular destinations. Each logger can have zero, one or more handlers associated with it (via the [`addHandler()`](../library/logging#logging.Logger.addHandler "logging.Logger.addHandler") method of [`Logger`](../library/logging#logging.Logger "logging.Logger")). In addition to any handlers directly associated with a logger, *all handlers associated with all ancestors of the logger* are called to dispatch the message (unless the *propagate* flag for a logger is set to a false value, at which point the passing to ancestor handlers stops). Just as for loggers, handlers can have levels associated with them. A handler’s level acts as a filter in the same way as a logger’s level does. If a handler decides to actually dispatch an event, the [`emit()`](../library/logging#logging.Handler.emit "logging.Handler.emit") method is used to send the message to its destination. Most user-defined subclasses of [`Handler`](../library/logging#logging.Handler "logging.Handler") will need to override this [`emit()`](../library/logging#logging.Handler.emit "logging.Handler.emit"). ### Custom Levels Defining your own levels is possible, but should not be necessary, as the existing levels have been chosen on the basis of practical experience. However, if you are convinced that you need custom levels, great care should be exercised when doing this, and it is possibly *a very bad idea to define custom levels if you are developing a library*. That’s because if multiple library authors all define their own custom levels, there is a chance that the logging output from such multiple libraries used together will be difficult for the using developer to control and/or interpret, because a given numeric value might mean different things for different libraries. Useful Handlers --------------- In addition to the base [`Handler`](../library/logging#logging.Handler "logging.Handler") class, many useful subclasses are provided: 1. [`StreamHandler`](../library/logging.handlers#logging.StreamHandler "logging.StreamHandler") instances send messages to streams (file-like objects). 2. [`FileHandler`](../library/logging.handlers#logging.FileHandler "logging.FileHandler") instances send messages to disk files. 3. [`BaseRotatingHandler`](../library/logging.handlers#logging.handlers.BaseRotatingHandler "logging.handlers.BaseRotatingHandler") is the base class for handlers that rotate log files at a certain point. It is not meant to be instantiated directly. Instead, use [`RotatingFileHandler`](../library/logging.handlers#logging.handlers.RotatingFileHandler "logging.handlers.RotatingFileHandler") or [`TimedRotatingFileHandler`](../library/logging.handlers#logging.handlers.TimedRotatingFileHandler "logging.handlers.TimedRotatingFileHandler"). 4. [`RotatingFileHandler`](../library/logging.handlers#logging.handlers.RotatingFileHandler "logging.handlers.RotatingFileHandler") instances send messages to disk files, with support for maximum log file sizes and log file rotation. 5. [`TimedRotatingFileHandler`](../library/logging.handlers#logging.handlers.TimedRotatingFileHandler "logging.handlers.TimedRotatingFileHandler") instances send messages to disk files, rotating the log file at certain timed intervals. 6. [`SocketHandler`](../library/logging.handlers#logging.handlers.SocketHandler "logging.handlers.SocketHandler") instances send messages to TCP/IP sockets. Since 3.4, Unix domain sockets are also supported. 7. [`DatagramHandler`](../library/logging.handlers#logging.handlers.DatagramHandler "logging.handlers.DatagramHandler") instances send messages to UDP sockets. Since 3.4, Unix domain sockets are also supported. 8. [`SMTPHandler`](../library/logging.handlers#logging.handlers.SMTPHandler "logging.handlers.SMTPHandler") instances send messages to a designated email address. 9. [`SysLogHandler`](../library/logging.handlers#logging.handlers.SysLogHandler "logging.handlers.SysLogHandler") instances send messages to a Unix syslog daemon, possibly on a remote machine. 10. [`NTEventLogHandler`](../library/logging.handlers#logging.handlers.NTEventLogHandler "logging.handlers.NTEventLogHandler") instances send messages to a Windows NT/2000/XP event log. 11. [`MemoryHandler`](../library/logging.handlers#logging.handlers.MemoryHandler "logging.handlers.MemoryHandler") instances send messages to a buffer in memory, which is flushed whenever specific criteria are met. 12. [`HTTPHandler`](../library/logging.handlers#logging.handlers.HTTPHandler "logging.handlers.HTTPHandler") instances send messages to an HTTP server using either `GET` or `POST` semantics. 13. [`WatchedFileHandler`](../library/logging.handlers#logging.handlers.WatchedFileHandler "logging.handlers.WatchedFileHandler") instances watch the file they are logging to. If the file changes, it is closed and reopened using the file name. This handler is only useful on Unix-like systems; Windows does not support the underlying mechanism used. 14. [`QueueHandler`](../library/logging.handlers#logging.handlers.QueueHandler "logging.handlers.QueueHandler") instances send messages to a queue, such as those implemented in the [`queue`](../library/queue#module-queue "queue: A synchronized queue class.") or [`multiprocessing`](../library/multiprocessing#module-multiprocessing "multiprocessing: Process-based parallelism.") modules. 15. [`NullHandler`](../library/logging.handlers#logging.NullHandler "logging.NullHandler") instances do nothing with error messages. They are used by library developers who want to use logging, but want to avoid the ‘No handlers could be found for logger XXX’ message which can be displayed if the library user has not configured logging. See [Configuring Logging for a Library](#library-config) for more information. New in version 3.1: The [`NullHandler`](../library/logging.handlers#logging.NullHandler "logging.NullHandler") class. New in version 3.2: The [`QueueHandler`](../library/logging.handlers#logging.handlers.QueueHandler "logging.handlers.QueueHandler") class. The [`NullHandler`](../library/logging.handlers#logging.NullHandler "logging.NullHandler"), [`StreamHandler`](../library/logging.handlers#logging.StreamHandler "logging.StreamHandler") and [`FileHandler`](../library/logging.handlers#logging.FileHandler "logging.FileHandler") classes are defined in the core logging package. The other handlers are defined in a sub-module, [`logging.handlers`](../library/logging.handlers#module-logging.handlers "logging.handlers: Handlers for the logging module."). (There is also another sub-module, [`logging.config`](../library/logging.config#module-logging.config "logging.config: Configuration of the logging module."), for configuration functionality.) Logged messages are formatted for presentation through instances of the [`Formatter`](../library/logging#logging.Formatter "logging.Formatter") class. They are initialized with a format string suitable for use with the % operator and a dictionary. For formatting multiple messages in a batch, instances of `BufferingFormatter` can be used. In addition to the format string (which is applied to each message in the batch), there is provision for header and trailer format strings. When filtering based on logger level and/or handler level is not enough, instances of [`Filter`](../library/logging#logging.Filter "logging.Filter") can be added to both [`Logger`](../library/logging#logging.Logger "logging.Logger") and [`Handler`](../library/logging#logging.Handler "logging.Handler") instances (through their [`addFilter()`](../library/logging#logging.Handler.addFilter "logging.Handler.addFilter") method). Before deciding to process a message further, both loggers and handlers consult all their filters for permission. If any filter returns a false value, the message is not processed further. The basic [`Filter`](../library/logging#logging.Filter "logging.Filter") functionality allows filtering by specific logger name. If this feature is used, messages sent to the named logger and its children are allowed through the filter, and all others dropped. Exceptions raised during logging -------------------------------- The logging package is designed to swallow exceptions which occur while logging in production. This is so that errors which occur while handling logging events - such as logging misconfiguration, network or other similar errors - do not cause the application using logging to terminate prematurely. [`SystemExit`](../library/exceptions#SystemExit "SystemExit") and [`KeyboardInterrupt`](../library/exceptions#KeyboardInterrupt "KeyboardInterrupt") exceptions are never swallowed. Other exceptions which occur during the [`emit()`](../library/logging#logging.Handler.emit "logging.Handler.emit") method of a [`Handler`](../library/logging#logging.Handler "logging.Handler") subclass are passed to its [`handleError()`](../library/logging#logging.Handler.handleError "logging.Handler.handleError") method. The default implementation of [`handleError()`](../library/logging#logging.Handler.handleError "logging.Handler.handleError") in [`Handler`](../library/logging#logging.Handler "logging.Handler") checks to see if a module-level variable, `raiseExceptions`, is set. If set, a traceback is printed to [`sys.stderr`](../library/sys#sys.stderr "sys.stderr"). If not set, the exception is swallowed. Note The default value of `raiseExceptions` is `True`. This is because during development, you typically want to be notified of any exceptions that occur. It’s advised that you set `raiseExceptions` to `False` for production usage. Using arbitrary objects as messages ----------------------------------- In the preceding sections and examples, it has been assumed that the message passed when logging the event is a string. However, this is not the only possibility. You can pass an arbitrary object as a message, and its [`__str__()`](../reference/datamodel#object.__str__ "object.__str__") method will be called when the logging system needs to convert it to a string representation. In fact, if you want to, you can avoid computing a string representation altogether - for example, the [`SocketHandler`](../library/logging.handlers#logging.handlers.SocketHandler "logging.handlers.SocketHandler") emits an event by pickling it and sending it over the wire. Optimization ------------ Formatting of message arguments is deferred until it cannot be avoided. However, computing the arguments passed to the logging method can also be expensive, and you may want to avoid doing it if the logger will just throw away your event. To decide what to do, you can call the [`isEnabledFor()`](../library/logging#logging.Logger.isEnabledFor "logging.Logger.isEnabledFor") method which takes a level argument and returns true if the event would be created by the Logger for that level of call. You can write code like this: ``` if logger.isEnabledFor(logging.DEBUG): logger.debug('Message with %s, %s', expensive_func1(), expensive_func2()) ``` so that if the logger’s threshold is set above `DEBUG`, the calls to `expensive_func1()` and `expensive_func2()` are never made. Note In some cases, [`isEnabledFor()`](../library/logging#logging.Logger.isEnabledFor "logging.Logger.isEnabledFor") can itself be more expensive than you’d like (e.g. for deeply nested loggers where an explicit level is only set high up in the logger hierarchy). In such cases (or if you want to avoid calling a method in tight loops), you can cache the result of a call to [`isEnabledFor()`](../library/logging#logging.Logger.isEnabledFor "logging.Logger.isEnabledFor") in a local or instance variable, and use that instead of calling the method each time. Such a cached value would only need to be recomputed when the logging configuration changes dynamically while the application is running (which is not all that common). There are other optimizations which can be made for specific applications which need more precise control over what logging information is collected. Here’s a list of things you can do to avoid processing during logging which you don’t need: | What you don’t want to collect | How to avoid collecting it | | --- | --- | | Information about where calls were made from. | Set `logging._srcfile` to `None`. This avoids calling [`sys._getframe()`](../library/sys#sys._getframe "sys._getframe"), which may help to speed up your code in environments like PyPy (which can’t speed up code that uses [`sys._getframe()`](../library/sys#sys._getframe "sys._getframe")). | | Threading information. | Set `logging.logThreads` to `0`. | | Process information. | Set `logging.logProcesses` to `0`. | Also note that the core logging module only includes the basic handlers. If you don’t import [`logging.handlers`](../library/logging.handlers#module-logging.handlers "logging.handlers: Handlers for the logging module.") and [`logging.config`](../library/logging.config#module-logging.config "logging.config: Configuration of the logging module."), they won’t take up any memory. See also `Module` [`logging`](../library/logging#module-logging "logging: Flexible event logging system for applications.") API reference for the logging module. `Module` [`logging.config`](../library/logging.config#module-logging.config "logging.config: Configuration of the logging module.") Configuration API for the logging module. `Module` [`logging.handlers`](../library/logging.handlers#module-logging.handlers "logging.handlers: Handlers for the logging module.") Useful handlers included with the logging module. [A logging cookbook](logging-cookbook#logging-cookbook)
programming_docs
python Logging Cookbook Logging Cookbook ================ Author Vinay Sajip <vinay\_sajip at red-dove dot com> This page contains a number of recipes related to logging, which have been found useful in the past. Using logging in multiple modules --------------------------------- Multiple calls to `logging.getLogger('someLogger')` return a reference to the same logger object. This is true not only within the same module, but also across modules as long as it is in the same Python interpreter process. It is true for references to the same object; additionally, application code can define and configure a parent logger in one module and create (but not configure) a child logger in a separate module, and all logger calls to the child will pass up to the parent. Here is a main module: ``` import logging import auxiliary_module # create logger with 'spam_application' logger = logging.getLogger('spam_application') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages fh = logging.FileHandler('spam.log') fh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.ERROR) # create formatter and add it to the handlers formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) ch.setFormatter(formatter) # add the handlers to the logger logger.addHandler(fh) logger.addHandler(ch) logger.info('creating an instance of auxiliary_module.Auxiliary') a = auxiliary_module.Auxiliary() logger.info('created an instance of auxiliary_module.Auxiliary') logger.info('calling auxiliary_module.Auxiliary.do_something') a.do_something() logger.info('finished auxiliary_module.Auxiliary.do_something') logger.info('calling auxiliary_module.some_function()') auxiliary_module.some_function() logger.info('done with auxiliary_module.some_function()') ``` Here is the auxiliary module: ``` import logging # create logger module_logger = logging.getLogger('spam_application.auxiliary') class Auxiliary: def __init__(self): self.logger = logging.getLogger('spam_application.auxiliary.Auxiliary') self.logger.info('creating an instance of Auxiliary') def do_something(self): self.logger.info('doing something') a = 1 + 1 self.logger.info('done doing something') def some_function(): module_logger.info('received a call to "some_function"') ``` The output looks like this: ``` 2005-03-23 23:47:11,663 - spam_application - INFO - creating an instance of auxiliary_module.Auxiliary 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO - creating an instance of Auxiliary 2005-03-23 23:47:11,665 - spam_application - INFO - created an instance of auxiliary_module.Auxiliary 2005-03-23 23:47:11,668 - spam_application - INFO - calling auxiliary_module.Auxiliary.do_something 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO - doing something 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO - done doing something 2005-03-23 23:47:11,670 - spam_application - INFO - finished auxiliary_module.Auxiliary.do_something 2005-03-23 23:47:11,671 - spam_application - INFO - calling auxiliary_module.some_function() 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO - received a call to 'some_function' 2005-03-23 23:47:11,673 - spam_application - INFO - done with auxiliary_module.some_function() ``` Logging from multiple threads ----------------------------- Logging from multiple threads requires no special effort. The following example shows logging from the main (initial) thread and another thread: ``` import logging import threading import time def worker(arg): while not arg['stop']: logging.debug('Hi from myfunc') time.sleep(0.5) def main(): logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s') info = {'stop': False} thread = threading.Thread(target=worker, args=(info,)) thread.start() while True: try: logging.debug('Hello from main') time.sleep(0.75) except KeyboardInterrupt: info['stop'] = True break thread.join() if __name__ == '__main__': main() ``` When run, the script should print something like the following: ``` 0 Thread-1 Hi from myfunc 3 MainThread Hello from main 505 Thread-1 Hi from myfunc 755 MainThread Hello from main 1007 Thread-1 Hi from myfunc 1507 MainThread Hello from main 1508 Thread-1 Hi from myfunc 2010 Thread-1 Hi from myfunc 2258 MainThread Hello from main 2512 Thread-1 Hi from myfunc 3009 MainThread Hello from main 3013 Thread-1 Hi from myfunc 3515 Thread-1 Hi from myfunc 3761 MainThread Hello from main 4017 Thread-1 Hi from myfunc 4513 MainThread Hello from main 4518 Thread-1 Hi from myfunc ``` This shows the logging output interspersed as one might expect. This approach works for more threads than shown here, of course. Multiple handlers and formatters -------------------------------- Loggers are plain Python objects. The [`addHandler()`](../library/logging#logging.Logger.addHandler "logging.Logger.addHandler") method has no minimum or maximum quota for the number of handlers you may add. Sometimes it will be beneficial for an application to log all messages of all severities to a text file while simultaneously logging errors or above to the console. To set this up, simply configure the appropriate handlers. The logging calls in the application code will remain unchanged. Here is a slight modification to the previous simple module-based configuration example: ``` import logging logger = logging.getLogger('simple_example') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages fh = logging.FileHandler('spam.log') fh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.ERROR) # create formatter and add it to the handlers formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) fh.setFormatter(formatter) # add the handlers to logger logger.addHandler(ch) logger.addHandler(fh) # 'application' code logger.debug('debug message') logger.info('info message') logger.warning('warn message') logger.error('error message') logger.critical('critical message') ``` Notice that the ‘application’ code does not care about multiple handlers. All that changed was the addition and configuration of a new handler named *fh*. The ability to create new handlers with higher- or lower-severity filters can be very helpful when writing and testing an application. Instead of using many `print` statements for debugging, use `logger.debug`: Unlike the print statements, which you will have to delete or comment out later, the logger.debug statements can remain intact in the source code and remain dormant until you need them again. At that time, the only change that needs to happen is to modify the severity level of the logger and/or handler to debug. Logging to multiple destinations -------------------------------- Let’s say you want to log to console and file with different message formats and in differing circumstances. Say you want to log messages with levels of DEBUG and higher to file, and those messages at level INFO and higher to the console. Let’s also assume that the file should contain timestamps, but the console messages should not. Here’s how you can achieve this: ``` import logging # set up logging to file - see previous section for more details logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filename='/temp/myapp.log', filemode='w') # define a Handler which writes INFO messages or higher to the sys.stderr console = logging.StreamHandler() console.setLevel(logging.INFO) # set a format which is simpler for console use formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') # tell the handler to use this format console.setFormatter(formatter) # add the handler to the root logger logging.getLogger('').addHandler(console) # Now, we can log to the root logger, or any other logger. First the root... logging.info('Jackdaws love my big sphinx of quartz.') # Now, define a couple of other loggers which might represent areas in your # application: logger1 = logging.getLogger('myapp.area1') logger2 = logging.getLogger('myapp.area2') logger1.debug('Quick zephyrs blow, vexing daft Jim.') logger1.info('How quickly daft jumping zebras vex.') logger2.warning('Jail zesty vixen who grabbed pay from quack.') logger2.error('The five boxing wizards jump quickly.') ``` When you run this, on the console you will see ``` root : INFO Jackdaws love my big sphinx of quartz. myapp.area1 : INFO How quickly daft jumping zebras vex. myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack. myapp.area2 : ERROR The five boxing wizards jump quickly. ``` and in the file you will see something like ``` 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz. 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim. 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex. 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack. 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly. ``` As you can see, the DEBUG message only shows up in the file. The other messages are sent to both destinations. This example uses console and file handlers, but you can use any number and combination of handlers you choose. Configuration server example ---------------------------- Here is an example of a module using the logging configuration server: ``` import logging import logging.config import time import os # read initial config file logging.config.fileConfig('logging.conf') # create and start listener on port 9999 t = logging.config.listen(9999) t.start() logger = logging.getLogger('simpleExample') try: # loop through logging calls to see the difference # new configurations make, until Ctrl+C is pressed while True: logger.debug('debug message') logger.info('info message') logger.warning('warn message') logger.error('error message') logger.critical('critical message') time.sleep(5) except KeyboardInterrupt: # cleanup logging.config.stopListening() t.join() ``` And here is a script that takes a filename and sends that file to the server, properly preceded with the binary-encoded length, as the new logging configuration: ``` #!/usr/bin/env python import socket, sys, struct with open(sys.argv[1], 'rb') as f: data_to_send = f.read() HOST = 'localhost' PORT = 9999 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print('connecting...') s.connect((HOST, PORT)) print('sending config...') s.send(struct.pack('>L', len(data_to_send))) s.send(data_to_send) s.close() print('complete') ``` Dealing with handlers that block -------------------------------- Sometimes you have to get your logging handlers to do their work without blocking the thread you’re logging from. This is common in Web applications, though of course it also occurs in other scenarios. A common culprit which demonstrates sluggish behaviour is the [`SMTPHandler`](../library/logging.handlers#logging.handlers.SMTPHandler "logging.handlers.SMTPHandler"): sending emails can take a long time, for a number of reasons outside the developer’s control (for example, a poorly performing mail or network infrastructure). But almost any network-based handler can block: Even a [`SocketHandler`](../library/logging.handlers#logging.handlers.SocketHandler "logging.handlers.SocketHandler") operation may do a DNS query under the hood which is too slow (and this query can be deep in the socket library code, below the Python layer, and outside your control). One solution is to use a two-part approach. For the first part, attach only a [`QueueHandler`](../library/logging.handlers#logging.handlers.QueueHandler "logging.handlers.QueueHandler") to those loggers which are accessed from performance-critical threads. They simply write to their queue, which can be sized to a large enough capacity or initialized with no upper bound to their size. The write to the queue will typically be accepted quickly, though you will probably need to catch the [`queue.Full`](../library/queue#queue.Full "queue.Full") exception as a precaution in your code. If you are a library developer who has performance-critical threads in their code, be sure to document this (together with a suggestion to attach only `QueueHandlers` to your loggers) for the benefit of other developers who will use your code. The second part of the solution is [`QueueListener`](../library/logging.handlers#logging.handlers.QueueListener "logging.handlers.QueueListener"), which has been designed as the counterpart to [`QueueHandler`](../library/logging.handlers#logging.handlers.QueueHandler "logging.handlers.QueueHandler"). A [`QueueListener`](../library/logging.handlers#logging.handlers.QueueListener "logging.handlers.QueueListener") is very simple: it’s passed a queue and some handlers, and it fires up an internal thread which listens to its queue for LogRecords sent from `QueueHandlers` (or any other source of `LogRecords`, for that matter). The `LogRecords` are removed from the queue and passed to the handlers for processing. The advantage of having a separate [`QueueListener`](../library/logging.handlers#logging.handlers.QueueListener "logging.handlers.QueueListener") class is that you can use the same instance to service multiple `QueueHandlers`. This is more resource-friendly than, say, having threaded versions of the existing handler classes, which would eat up one thread per handler for no particular benefit. An example of using these two classes follows (imports omitted): ``` que = queue.Queue(-1) # no limit on size queue_handler = QueueHandler(que) handler = logging.StreamHandler() listener = QueueListener(que, handler) root = logging.getLogger() root.addHandler(queue_handler) formatter = logging.Formatter('%(threadName)s: %(message)s') handler.setFormatter(formatter) listener.start() # The log output will display the thread which generated # the event (the main thread) rather than the internal # thread which monitors the internal queue. This is what # you want to happen. root.warning('Look out!') listener.stop() ``` which, when run, will produce: ``` MainThread: Look out! ``` Changed in version 3.5: Prior to Python 3.5, the [`QueueListener`](../library/logging.handlers#logging.handlers.QueueListener "logging.handlers.QueueListener") always passed every message received from the queue to every handler it was initialized with. (This was because it was assumed that level filtering was all done on the other side, where the queue is filled.) From 3.5 onwards, this behaviour can be changed by passing a keyword argument `respect_handler_level=True` to the listener’s constructor. When this is done, the listener compares the level of each message with the handler’s level, and only passes a message to a handler if it’s appropriate to do so. Sending and receiving logging events across a network ----------------------------------------------------- Let’s say you want to send logging events across a network, and handle them at the receiving end. A simple way of doing this is attaching a [`SocketHandler`](../library/logging.handlers#logging.handlers.SocketHandler "logging.handlers.SocketHandler") instance to the root logger at the sending end: ``` import logging, logging.handlers rootLogger = logging.getLogger('') rootLogger.setLevel(logging.DEBUG) socketHandler = logging.handlers.SocketHandler('localhost', logging.handlers.DEFAULT_TCP_LOGGING_PORT) # don't bother with a formatter, since a socket handler sends the event as # an unformatted pickle rootLogger.addHandler(socketHandler) # Now, we can log to the root logger, or any other logger. First the root... logging.info('Jackdaws love my big sphinx of quartz.') # Now, define a couple of other loggers which might represent areas in your # application: logger1 = logging.getLogger('myapp.area1') logger2 = logging.getLogger('myapp.area2') logger1.debug('Quick zephyrs blow, vexing daft Jim.') logger1.info('How quickly daft jumping zebras vex.') logger2.warning('Jail zesty vixen who grabbed pay from quack.') logger2.error('The five boxing wizards jump quickly.') ``` At the receiving end, you can set up a receiver using the [`socketserver`](../library/socketserver#module-socketserver "socketserver: A framework for network servers.") module. Here is a basic working example: ``` import pickle import logging import logging.handlers import socketserver import struct class LogRecordStreamHandler(socketserver.StreamRequestHandler): """Handler for a streaming logging request. This basically logs the record using whatever logging policy is configured locally. """ def handle(self): """ Handle multiple requests - each expected to be a 4-byte length, followed by the LogRecord in pickle format. Logs the record according to whatever policy is configured locally. """ while True: chunk = self.connection.recv(4) if len(chunk) < 4: break slen = struct.unpack('>L', chunk)[0] chunk = self.connection.recv(slen) while len(chunk) < slen: chunk = chunk + self.connection.recv(slen - len(chunk)) obj = self.unPickle(chunk) record = logging.makeLogRecord(obj) self.handleLogRecord(record) def unPickle(self, data): return pickle.loads(data) def handleLogRecord(self, record): # if a name is specified, we use the named logger rather than the one # implied by the record. if self.server.logname is not None: name = self.server.logname else: name = record.name logger = logging.getLogger(name) # N.B. EVERY record gets logged. This is because Logger.handle # is normally called AFTER logger-level filtering. If you want # to do filtering, do it at the client end to save wasting # cycles and network bandwidth! logger.handle(record) class LogRecordSocketReceiver(socketserver.ThreadingTCPServer): """ Simple TCP socket-based logging receiver suitable for testing. """ allow_reuse_address = True def __init__(self, host='localhost', port=logging.handlers.DEFAULT_TCP_LOGGING_PORT, handler=LogRecordStreamHandler): socketserver.ThreadingTCPServer.__init__(self, (host, port), handler) self.abort = 0 self.timeout = 1 self.logname = None def serve_until_stopped(self): import select abort = 0 while not abort: rd, wr, ex = select.select([self.socket.fileno()], [], [], self.timeout) if rd: self.handle_request() abort = self.abort def main(): logging.basicConfig( format='%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s') tcpserver = LogRecordSocketReceiver() print('About to start TCP server...') tcpserver.serve_until_stopped() if __name__ == '__main__': main() ``` First run the server, and then the client. On the client side, nothing is printed on the console; on the server side, you should see something like: ``` About to start TCP server... 59 root INFO Jackdaws love my big sphinx of quartz. 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim. 69 myapp.area1 INFO How quickly daft jumping zebras vex. 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack. 69 myapp.area2 ERROR The five boxing wizards jump quickly. ``` Note that there are some security issues with pickle in some scenarios. If these affect you, you can use an alternative serialization scheme by overriding the `makePickle()` method and implementing your alternative there, as well as adapting the above script to use your alternative serialization. ### Running a logging socket listener in production To run a logging listener in production, you may need to use a process-management tool such as [Supervisor](http://supervisord.org/). [Here](https://gist.github.com/vsajip/4b227eeec43817465ca835ca66f75e2b) is a Gist which provides the bare-bones files to run the above functionality using Supervisor: you will need to change the `/path/to/` parts in the Gist to reflect the actual paths you want to use. Adding contextual information to your logging output ---------------------------------------------------- Sometimes you want logging output to contain contextual information in addition to the parameters passed to the logging call. For example, in a networked application, it may be desirable to log client-specific information in the log (e.g. remote client’s username, or IP address). Although you could use the *extra* parameter to achieve this, it’s not always convenient to pass the information in this way. While it might be tempting to create `Logger` instances on a per-connection basis, this is not a good idea because these instances are not garbage collected. While this is not a problem in practice, when the number of `Logger` instances is dependent on the level of granularity you want to use in logging an application, it could be hard to manage if the number of `Logger` instances becomes effectively unbounded. ### Using LoggerAdapters to impart contextual information An easy way in which you can pass contextual information to be output along with logging event information is to use the `LoggerAdapter` class. This class is designed to look like a `Logger`, so that you can call `debug()`, `info()`, `warning()`, `error()`, `exception()`, `critical()` and `log()`. These methods have the same signatures as their counterparts in `Logger`, so you can use the two types of instances interchangeably. When you create an instance of `LoggerAdapter`, you pass it a `Logger` instance and a dict-like object which contains your contextual information. When you call one of the logging methods on an instance of `LoggerAdapter`, it delegates the call to the underlying instance of `Logger` passed to its constructor, and arranges to pass the contextual information in the delegated call. Here’s a snippet from the code of `LoggerAdapter`: ``` def debug(self, msg, /, *args, **kwargs): """ Delegate a debug call to the underlying logger, after adding contextual information from this adapter instance. """ msg, kwargs = self.process(msg, kwargs) self.logger.debug(msg, *args, **kwargs) ``` The `process()` method of `LoggerAdapter` is where the contextual information is added to the logging output. It’s passed the message and keyword arguments of the logging call, and it passes back (potentially) modified versions of these to use in the call to the underlying logger. The default implementation of this method leaves the message alone, but inserts an ‘extra’ key in the keyword argument whose value is the dict-like object passed to the constructor. Of course, if you had passed an ‘extra’ keyword argument in the call to the adapter, it will be silently overwritten. The advantage of using ‘extra’ is that the values in the dict-like object are merged into the `LogRecord` instance’s \_\_dict\_\_, allowing you to use customized strings with your `Formatter` instances which know about the keys of the dict-like object. If you need a different method, e.g. if you want to prepend or append the contextual information to the message string, you just need to subclass `LoggerAdapter` and override `process()` to do what you need. Here is a simple example: ``` class CustomAdapter(logging.LoggerAdapter): """ This example adapter expects the passed in dict-like object to have a 'connid' key, whose value in brackets is prepended to the log message. """ def process(self, msg, kwargs): return '[%s] %s' % (self.extra['connid'], msg), kwargs ``` which you can use like this: ``` logger = logging.getLogger(__name__) adapter = CustomAdapter(logger, {'connid': some_conn_id}) ``` Then any events that you log to the adapter will have the value of `some_conn_id` prepended to the log messages. #### Using objects other than dicts to pass contextual information You don’t need to pass an actual dict to a `LoggerAdapter` - you could pass an instance of a class which implements `__getitem__` and `__iter__` so that it looks like a dict to logging. This would be useful if you want to generate values dynamically (whereas the values in a dict would be constant). ### Using Filters to impart contextual information You can also add contextual information to log output using a user-defined `Filter`. `Filter` instances are allowed to modify the `LogRecords` passed to them, including adding additional attributes which can then be output using a suitable format string, or if needed a custom `Formatter`. For example in a web application, the request being processed (or at least, the interesting parts of it) can be stored in a threadlocal ([`threading.local`](../library/threading#threading.local "threading.local")) variable, and then accessed from a `Filter` to add, say, information from the request - say, the remote IP address and remote user’s username - to the `LogRecord`, using the attribute names ‘ip’ and ‘user’ as in the `LoggerAdapter` example above. In that case, the same format string can be used to get similar output to that shown above. Here’s an example script: ``` import logging from random import choice class ContextFilter(logging.Filter): """ This is a filter which injects contextual information into the log. Rather than use actual contextual information, we just use random data in this demo. """ USERS = ['jim', 'fred', 'sheila'] IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1'] def filter(self, record): record.ip = choice(ContextFilter.IPS) record.user = choice(ContextFilter.USERS) return True if __name__ == '__main__': levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL) logging.basicConfig(level=logging.DEBUG, format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s') a1 = logging.getLogger('a.b.c') a2 = logging.getLogger('d.e.f') f = ContextFilter() a1.addFilter(f) a2.addFilter(f) a1.debug('A debug message') a1.info('An info message with %s', 'some parameters') for x in range(10): lvl = choice(levels) lvlname = logging.getLevelName(lvl) a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters') ``` which, when run, produces something like: ``` 2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1 User: sheila A message at CRITICAL level with 2 parameters 2010-09-06 22:38:15,300 d.e.f ERROR IP: 127.0.0.1 User: jim A message at ERROR level with 2 parameters 2010-09-06 22:38:15,300 d.e.f DEBUG IP: 127.0.0.1 User: sheila A message at DEBUG level with 2 parameters 2010-09-06 22:38:15,300 d.e.f ERROR IP: 123.231.231.123 User: fred A message at ERROR level with 2 parameters 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 192.168.0.1 User: jim A message at CRITICAL level with 2 parameters 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1 User: sheila A message at CRITICAL level with 2 parameters 2010-09-06 22:38:15,300 d.e.f DEBUG IP: 192.168.0.1 User: jim A message at DEBUG level with 2 parameters 2010-09-06 22:38:15,301 d.e.f ERROR IP: 127.0.0.1 User: sheila A message at ERROR level with 2 parameters 2010-09-06 22:38:15,301 d.e.f DEBUG IP: 123.231.231.123 User: fred A message at DEBUG level with 2 parameters 2010-09-06 22:38:15,301 d.e.f INFO IP: 123.231.231.123 User: fred A message at INFO level with 2 parameters ``` Logging to a single file from multiple processes ------------------------------------------------ Although logging is thread-safe, and logging to a single file from multiple threads in a single process *is* supported, logging to a single file from *multiple processes* is *not* supported, because there is no standard way to serialize access to a single file across multiple processes in Python. If you need to log to a single file from multiple processes, one way of doing this is to have all the processes log to a `SocketHandler`, and have a separate process which implements a socket server which reads from the socket and logs to file. (If you prefer, you can dedicate one thread in one of the existing processes to perform this function.) [This section](#network-logging) documents this approach in more detail and includes a working socket receiver which can be used as a starting point for you to adapt in your own applications. You could also write your own handler which uses the [`Lock`](../library/multiprocessing#multiprocessing.Lock "multiprocessing.Lock") class from the [`multiprocessing`](../library/multiprocessing#module-multiprocessing "multiprocessing: Process-based parallelism.") module to serialize access to the file from your processes. The existing `FileHandler` and subclasses do not make use of [`multiprocessing`](../library/multiprocessing#module-multiprocessing "multiprocessing: Process-based parallelism.") at present, though they may do so in the future. Note that at present, the [`multiprocessing`](../library/multiprocessing#module-multiprocessing "multiprocessing: Process-based parallelism.") module does not provide working lock functionality on all platforms (see <https://bugs.python.org/issue3770>). Alternatively, you can use a `Queue` and a [`QueueHandler`](../library/logging.handlers#logging.handlers.QueueHandler "logging.handlers.QueueHandler") to send all logging events to one of the processes in your multi-process application. The following example script demonstrates how you can do this; in the example a separate listener process listens for events sent by other processes and logs them according to its own logging configuration. Although the example only demonstrates one way of doing it (for example, you may want to use a listener thread rather than a separate listener process – the implementation would be analogous) it does allow for completely different logging configurations for the listener and the other processes in your application, and can be used as the basis for code meeting your own specific requirements: ``` # You'll need these imports in your own code import logging import logging.handlers import multiprocessing # Next two import lines for this demo only from random import choice, random import time # # Because you'll want to define the logging configurations for listener and workers, the # listener and worker process functions take a configurer parameter which is a callable # for configuring logging for that process. These functions are also passed the queue, # which they use for communication. # # In practice, you can configure the listener however you want, but note that in this # simple example, the listener does not apply level or filter logic to received records. # In practice, you would probably want to do this logic in the worker processes, to avoid # sending events which would be filtered out between processes. # # The size of the rotated files is made small so you can see the results easily. def listener_configurer(): root = logging.getLogger() h = logging.handlers.RotatingFileHandler('mptest.log', 'a', 300, 10) f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s') h.setFormatter(f) root.addHandler(h) # This is the listener process top-level loop: wait for logging events # (LogRecords)on the queue and handle them, quit when you get a None for a # LogRecord. def listener_process(queue, configurer): configurer() while True: try: record = queue.get() if record is None: # We send this as a sentinel to tell the listener to quit. break logger = logging.getLogger(record.name) logger.handle(record) # No level or filter logic applied - just do it! except Exception: import sys, traceback print('Whoops! Problem:', file=sys.stderr) traceback.print_exc(file=sys.stderr) # Arrays used for random selections in this demo LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL] LOGGERS = ['a.b.c', 'd.e.f'] MESSAGES = [ 'Random message #1', 'Random message #2', 'Random message #3', ] # The worker configuration is done at the start of the worker process run. # Note that on Windows you can't rely on fork semantics, so each process # will run the logging configuration code when it starts. def worker_configurer(queue): h = logging.handlers.QueueHandler(queue) # Just the one handler needed root = logging.getLogger() root.addHandler(h) # send all messages, for demo; no other level or filter logic applied. root.setLevel(logging.DEBUG) # This is the worker process top-level loop, which just logs ten events with # random intervening delays before terminating. # The print messages are just so you know it's doing something! def worker_process(queue, configurer): configurer(queue) name = multiprocessing.current_process().name print('Worker started: %s' % name) for i in range(10): time.sleep(random()) logger = logging.getLogger(choice(LOGGERS)) level = choice(LEVELS) message = choice(MESSAGES) logger.log(level, message) print('Worker finished: %s' % name) # Here's where the demo gets orchestrated. Create the queue, create and start # the listener, create ten workers and start them, wait for them to finish, # then send a None to the queue to tell the listener to finish. def main(): queue = multiprocessing.Queue(-1) listener = multiprocessing.Process(target=listener_process, args=(queue, listener_configurer)) listener.start() workers = [] for i in range(10): worker = multiprocessing.Process(target=worker_process, args=(queue, worker_configurer)) workers.append(worker) worker.start() for w in workers: w.join() queue.put_nowait(None) listener.join() if __name__ == '__main__': main() ``` A variant of the above script keeps the logging in the main process, in a separate thread: ``` import logging import logging.config import logging.handlers from multiprocessing import Process, Queue import random import threading import time def logger_thread(q): while True: record = q.get() if record is None: break logger = logging.getLogger(record.name) logger.handle(record) def worker_process(q): qh = logging.handlers.QueueHandler(q) root = logging.getLogger() root.setLevel(logging.DEBUG) root.addHandler(qh) levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL] loggers = ['foo', 'foo.bar', 'foo.bar.baz', 'spam', 'spam.ham', 'spam.ham.eggs'] for i in range(100): lvl = random.choice(levels) logger = logging.getLogger(random.choice(loggers)) logger.log(lvl, 'Message no. %d', i) if __name__ == '__main__': q = Queue() d = { 'version': 1, 'formatters': { 'detailed': { 'class': 'logging.Formatter', 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s' } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'level': 'INFO', }, 'file': { 'class': 'logging.FileHandler', 'filename': 'mplog.log', 'mode': 'w', 'formatter': 'detailed', }, 'foofile': { 'class': 'logging.FileHandler', 'filename': 'mplog-foo.log', 'mode': 'w', 'formatter': 'detailed', }, 'errors': { 'class': 'logging.FileHandler', 'filename': 'mplog-errors.log', 'mode': 'w', 'level': 'ERROR', 'formatter': 'detailed', }, }, 'loggers': { 'foo': { 'handlers': ['foofile'] } }, 'root': { 'level': 'DEBUG', 'handlers': ['console', 'file', 'errors'] }, } workers = [] for i in range(5): wp = Process(target=worker_process, name='worker %d' % (i + 1), args=(q,)) workers.append(wp) wp.start() logging.config.dictConfig(d) lp = threading.Thread(target=logger_thread, args=(q,)) lp.start() # At this point, the main process could do some useful work of its own # Once it's done that, it can wait for the workers to terminate... for wp in workers: wp.join() # And now tell the logging thread to finish up, too q.put(None) lp.join() ``` This variant shows how you can e.g. apply configuration for particular loggers - e.g. the `foo` logger has a special handler which stores all events in the `foo` subsystem in a file `mplog-foo.log`. This will be used by the logging machinery in the main process (even though the logging events are generated in the worker processes) to direct the messages to the appropriate destinations. ### Using concurrent.futures.ProcessPoolExecutor If you want to use [`concurrent.futures.ProcessPoolExecutor`](../library/concurrent.futures#concurrent.futures.ProcessPoolExecutor "concurrent.futures.ProcessPoolExecutor") to start your worker processes, you need to create the queue slightly differently. Instead of ``` queue = multiprocessing.Queue(-1) ``` you should use ``` queue = multiprocessing.Manager().Queue(-1) # also works with the examples above ``` and you can then replace the worker creation from this: ``` workers = [] for i in range(10): worker = multiprocessing.Process(target=worker_process, args=(queue, worker_configurer)) workers.append(worker) worker.start() for w in workers: w.join() ``` to this (remembering to first import [`concurrent.futures`](../library/concurrent.futures#module-concurrent.futures "concurrent.futures: Execute computations concurrently using threads or processes.")): ``` with concurrent.futures.ProcessPoolExecutor(max_workers=10) as executor: for i in range(10): executor.submit(worker_process, queue, worker_configurer) ``` ### Deploying Web applications using Gunicorn and uWSGI When deploying Web applications using [Gunicorn](https://gunicorn.org/) or [uWSGI](https://uwsgi-docs.readthedocs.io/en/latest/) (or similar), multiple worker processes are created to handle client requests. In such environments, avoid creating file-based handlers directly in your web application. Instead, use a [`SocketHandler`](../library/logging.handlers#logging.handlers.SocketHandler "logging.handlers.SocketHandler") to log from the web application to a listener in a separate process. This can be set up using a process management tool such as Supervisor - see [Running a logging socket listener in production](#running-a-logging-socket-listener-in-production) for more details. Using file rotation ------------------- Sometimes you want to let a log file grow to a certain size, then open a new file and log to that. You may want to keep a certain number of these files, and when that many files have been created, rotate the files so that the number of files and the size of the files both remain bounded. For this usage pattern, the logging package provides a `RotatingFileHandler`: ``` import glob import logging import logging.handlers LOG_FILENAME = 'logging_rotatingfile_example.out' # Set up a specific logger with our desired output level my_logger = logging.getLogger('MyLogger') my_logger.setLevel(logging.DEBUG) # Add the log message handler to the logger handler = logging.handlers.RotatingFileHandler( LOG_FILENAME, maxBytes=20, backupCount=5) my_logger.addHandler(handler) # Log some messages for i in range(20): my_logger.debug('i = %d' % i) # See what files are created logfiles = glob.glob('%s*' % LOG_FILENAME) for filename in logfiles: print(filename) ``` The result should be 6 separate files, each with part of the log history for the application: ``` logging_rotatingfile_example.out logging_rotatingfile_example.out.1 logging_rotatingfile_example.out.2 logging_rotatingfile_example.out.3 logging_rotatingfile_example.out.4 logging_rotatingfile_example.out.5 ``` The most current file is always `logging_rotatingfile_example.out`, and each time it reaches the size limit it is renamed with the suffix `.1`. Each of the existing backup files is renamed to increment the suffix (`.1` becomes `.2`, etc.) and the `.6` file is erased. Obviously this example sets the log length much too small as an extreme example. You would want to set *maxBytes* to an appropriate value. Use of alternative formatting styles ------------------------------------ When logging was added to the Python standard library, the only way of formatting messages with variable content was to use the %-formatting method. Since then, Python has gained two new formatting approaches: [`string.Template`](../library/string#string.Template "string.Template") (added in Python 2.4) and [`str.format()`](../library/stdtypes#str.format "str.format") (added in Python 2.6). Logging (as of 3.2) provides improved support for these two additional formatting styles. The `Formatter` class been enhanced to take an additional, optional keyword parameter named `style`. This defaults to `'%'`, but other possible values are `'{'` and `'$'`, which correspond to the other two formatting styles. Backwards compatibility is maintained by default (as you would expect), but by explicitly specifying a style parameter, you get the ability to specify format strings which work with [`str.format()`](../library/stdtypes#str.format "str.format") or [`string.Template`](../library/string#string.Template "string.Template"). Here’s an example console session to show the possibilities: ``` >>> import logging >>> root = logging.getLogger() >>> root.setLevel(logging.DEBUG) >>> handler = logging.StreamHandler() >>> bf = logging.Formatter('{asctime} {name} {levelname:8s} {message}', ... style='{') >>> handler.setFormatter(bf) >>> root.addHandler(handler) >>> logger = logging.getLogger('foo.bar') >>> logger.debug('This is a DEBUG message') 2010-10-28 15:11:55,341 foo.bar DEBUG This is a DEBUG message >>> logger.critical('This is a CRITICAL message') 2010-10-28 15:12:11,526 foo.bar CRITICAL This is a CRITICAL message >>> df = logging.Formatter('$asctime $name ${levelname} $message', ... style='$') >>> handler.setFormatter(df) >>> logger.debug('This is a DEBUG message') 2010-10-28 15:13:06,924 foo.bar DEBUG This is a DEBUG message >>> logger.critical('This is a CRITICAL message') 2010-10-28 15:13:11,494 foo.bar CRITICAL This is a CRITICAL message >>> ``` Note that the formatting of logging messages for final output to logs is completely independent of how an individual logging message is constructed. That can still use %-formatting, as shown here: ``` >>> logger.error('This is an%s %s %s', 'other,', 'ERROR,', 'message') 2010-10-28 15:19:29,833 foo.bar ERROR This is another, ERROR, message >>> ``` Logging calls (`logger.debug()`, `logger.info()` etc.) only take positional parameters for the actual logging message itself, with keyword parameters used only for determining options for how to handle the actual logging call (e.g. the `exc_info` keyword parameter to indicate that traceback information should be logged, or the `extra` keyword parameter to indicate additional contextual information to be added to the log). So you cannot directly make logging calls using [`str.format()`](../library/stdtypes#str.format "str.format") or [`string.Template`](../library/string#string.Template "string.Template") syntax, because internally the logging package uses %-formatting to merge the format string and the variable arguments. There would be no changing this while preserving backward compatibility, since all logging calls which are out there in existing code will be using %-format strings. There is, however, a way that you can use {}- and $- formatting to construct your individual log messages. Recall that for a message you can use an arbitrary object as a message format string, and that the logging package will call `str()` on that object to get the actual format string. Consider the following two classes: ``` class BraceMessage: def __init__(self, fmt, /, *args, **kwargs): self.fmt = fmt self.args = args self.kwargs = kwargs def __str__(self): return self.fmt.format(*self.args, **self.kwargs) class DollarMessage: def __init__(self, fmt, /, **kwargs): self.fmt = fmt self.kwargs = kwargs def __str__(self): from string import Template return Template(self.fmt).substitute(**self.kwargs) ``` Either of these can be used in place of a format string, to allow {}- or $-formatting to be used to build the actual “message” part which appears in the formatted log output in place of “%(message)s” or “{message}” or “$message”. It’s a little unwieldy to use the class names whenever you want to log something, but it’s quite palatable if you use an alias such as \_\_ (double underscore — not to be confused with \_, the single underscore used as a synonym/alias for [`gettext.gettext()`](../library/gettext#gettext.gettext "gettext.gettext") or its brethren). The above classes are not included in Python, though they’re easy enough to copy and paste into your own code. They can be used as follows (assuming that they’re declared in a module called `wherever`): ``` >>> from wherever import BraceMessage as __ >>> print(__('Message with {0} {name}', 2, name='placeholders')) Message with 2 placeholders >>> class Point: pass ... >>> p = Point() >>> p.x = 0.5 >>> p.y = 0.5 >>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})', ... point=p)) Message with coordinates: (0.50, 0.50) >>> from wherever import DollarMessage as __ >>> print(__('Message with $num $what', num=2, what='placeholders')) Message with 2 placeholders >>> ``` While the above examples use `print()` to show how the formatting works, you would of course use `logger.debug()` or similar to actually log using this approach. One thing to note is that you pay no significant performance penalty with this approach: the actual formatting happens not when you make the logging call, but when (and if) the logged message is actually about to be output to a log by a handler. So the only slightly unusual thing which might trip you up is that the parentheses go around the format string and the arguments, not just the format string. That’s because the \_\_ notation is just syntax sugar for a constructor call to one of the XXXMessage classes. If you prefer, you can use a `LoggerAdapter` to achieve a similar effect to the above, as in the following example: ``` import logging class Message: def __init__(self, fmt, args): self.fmt = fmt self.args = args def __str__(self): return self.fmt.format(*self.args) class StyleAdapter(logging.LoggerAdapter): def __init__(self, logger, extra=None): super().__init__(logger, extra or {}) def log(self, level, msg, /, *args, **kwargs): if self.isEnabledFor(level): msg, kwargs = self.process(msg, kwargs) self.logger._log(level, Message(msg, args), (), **kwargs) logger = StyleAdapter(logging.getLogger(__name__)) def main(): logger.debug('Hello, {}', 'world!') if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) main() ``` The above script should log the message `Hello, world!` when run with Python 3.2 or later. Customizing `LogRecord` ----------------------- Every logging event is represented by a [`LogRecord`](../library/logging#logging.LogRecord "logging.LogRecord") instance. When an event is logged and not filtered out by a logger’s level, a [`LogRecord`](../library/logging#logging.LogRecord "logging.LogRecord") is created, populated with information about the event and then passed to the handlers for that logger (and its ancestors, up to and including the logger where further propagation up the hierarchy is disabled). Before Python 3.2, there were only two places where this creation was done: * [`Logger.makeRecord()`](../library/logging#logging.Logger.makeRecord "logging.Logger.makeRecord"), which is called in the normal process of logging an event. This invoked [`LogRecord`](../library/logging#logging.LogRecord "logging.LogRecord") directly to create an instance. * [`makeLogRecord()`](../library/logging#logging.makeLogRecord "logging.makeLogRecord"), which is called with a dictionary containing attributes to be added to the LogRecord. This is typically invoked when a suitable dictionary has been received over the network (e.g. in pickle form via a [`SocketHandler`](../library/logging.handlers#logging.handlers.SocketHandler "logging.handlers.SocketHandler"), or in JSON form via an [`HTTPHandler`](../library/logging.handlers#logging.handlers.HTTPHandler "logging.handlers.HTTPHandler")). This has usually meant that if you need to do anything special with a [`LogRecord`](../library/logging#logging.LogRecord "logging.LogRecord"), you’ve had to do one of the following. * Create your own [`Logger`](../library/logging#logging.Logger "logging.Logger") subclass, which overrides [`Logger.makeRecord()`](../library/logging#logging.Logger.makeRecord "logging.Logger.makeRecord"), and set it using [`setLoggerClass()`](../library/logging#logging.setLoggerClass "logging.setLoggerClass") before any loggers that you care about are instantiated. * Add a [`Filter`](../library/logging#logging.Filter "logging.Filter") to a logger or handler, which does the necessary special manipulation you need when its [`filter()`](../library/logging#logging.Filter.filter "logging.Filter.filter") method is called. The first approach would be a little unwieldy in the scenario where (say) several different libraries wanted to do different things. Each would attempt to set its own [`Logger`](../library/logging#logging.Logger "logging.Logger") subclass, and the one which did this last would win. The second approach works reasonably well for many cases, but does not allow you to e.g. use a specialized subclass of [`LogRecord`](../library/logging#logging.LogRecord "logging.LogRecord"). Library developers can set a suitable filter on their loggers, but they would have to remember to do this every time they introduced a new logger (which they would do simply by adding new packages or modules and doing ``` logger = logging.getLogger(__name__) ``` at module level). It’s probably one too many things to think about. Developers could also add the filter to a [`NullHandler`](../library/logging.handlers#logging.NullHandler "logging.NullHandler") attached to their top-level logger, but this would not be invoked if an application developer attached a handler to a lower-level library logger — so output from that handler would not reflect the intentions of the library developer. In Python 3.2 and later, [`LogRecord`](../library/logging#logging.LogRecord "logging.LogRecord") creation is done through a factory, which you can specify. The factory is just a callable you can set with [`setLogRecordFactory()`](../library/logging#logging.setLogRecordFactory "logging.setLogRecordFactory"), and interrogate with [`getLogRecordFactory()`](../library/logging#logging.getLogRecordFactory "logging.getLogRecordFactory"). The factory is invoked with the same signature as the [`LogRecord`](../library/logging#logging.LogRecord "logging.LogRecord") constructor, as [`LogRecord`](../library/logging#logging.LogRecord "logging.LogRecord") is the default setting for the factory. This approach allows a custom factory to control all aspects of LogRecord creation. For example, you could return a subclass, or just add some additional attributes to the record once created, using a pattern similar to this: ``` old_factory = logging.getLogRecordFactory() def record_factory(*args, **kwargs): record = old_factory(*args, **kwargs) record.custom_attribute = 0xdecafbad return record logging.setLogRecordFactory(record_factory) ``` This pattern allows different libraries to chain factories together, and as long as they don’t overwrite each other’s attributes or unintentionally overwrite the attributes provided as standard, there should be no surprises. However, it should be borne in mind that each link in the chain adds run-time overhead to all logging operations, and the technique should only be used when the use of a [`Filter`](../library/logging#logging.Filter "logging.Filter") does not provide the desired result. Subclassing QueueHandler - a ZeroMQ example ------------------------------------------- You can use a `QueueHandler` subclass to send messages to other kinds of queues, for example a ZeroMQ ‘publish’ socket. In the example below,the socket is created separately and passed to the handler (as its ‘queue’): ``` import zmq # using pyzmq, the Python binding for ZeroMQ import json # for serializing records portably ctx = zmq.Context() sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value sock.bind('tcp://*:5556') # or wherever class ZeroMQSocketHandler(QueueHandler): def enqueue(self, record): self.queue.send_json(record.__dict__) handler = ZeroMQSocketHandler(sock) ``` Of course there are other ways of organizing this, for example passing in the data needed by the handler to create the socket: ``` class ZeroMQSocketHandler(QueueHandler): def __init__(self, uri, socktype=zmq.PUB, ctx=None): self.ctx = ctx or zmq.Context() socket = zmq.Socket(self.ctx, socktype) socket.bind(uri) super().__init__(socket) def enqueue(self, record): self.queue.send_json(record.__dict__) def close(self): self.queue.close() ``` Subclassing QueueListener - a ZeroMQ example -------------------------------------------- You can also subclass `QueueListener` to get messages from other kinds of queues, for example a ZeroMQ ‘subscribe’ socket. Here’s an example: ``` class ZeroMQSocketListener(QueueListener): def __init__(self, uri, /, *handlers, **kwargs): self.ctx = kwargs.get('ctx') or zmq.Context() socket = zmq.Socket(self.ctx, zmq.SUB) socket.setsockopt_string(zmq.SUBSCRIBE, '') # subscribe to everything socket.connect(uri) super().__init__(socket, *handlers, **kwargs) def dequeue(self): msg = self.queue.recv_json() return logging.makeLogRecord(msg) ``` See also `Module` [`logging`](../library/logging#module-logging "logging: Flexible event logging system for applications.") API reference for the logging module. `Module` [`logging.config`](../library/logging.config#module-logging.config "logging.config: Configuration of the logging module.") Configuration API for the logging module. `Module` [`logging.handlers`](../library/logging.handlers#module-logging.handlers "logging.handlers: Handlers for the logging module.") Useful handlers included with the logging module. [A basic logging tutorial](logging#logging-basic-tutorial) [A more advanced logging tutorial](logging#logging-advanced-tutorial) An example dictionary-based configuration ----------------------------------------- Below is an example of a logging configuration dictionary - it’s taken from the [documentation on the Django project](https://docs.djangoproject.com/en/stable/topics/logging/#configuring-logging). This dictionary is passed to [`dictConfig()`](../library/logging.config#logging.config.dictConfig "logging.config.dictConfig") to put the configuration into effect: ``` LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'filters': { 'special': { '()': 'project.logging.SpecialFilter', 'foo': 'bar', } }, 'handlers': { 'null': { 'level':'DEBUG', 'class':'django.utils.log.NullHandler', }, 'console':{ 'level':'DEBUG', 'class':'logging.StreamHandler', 'formatter': 'simple' }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'filters': ['special'] } }, 'loggers': { 'django': { 'handlers':['null'], 'propagate': True, 'level':'INFO', }, 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': False, }, 'myproject.custom': { 'handlers': ['console', 'mail_admins'], 'level': 'INFO', 'filters': ['special'] } } } ``` For more information about this configuration, you can see the [relevant section](https://docs.djangoproject.com/en/stable/topics/logging/#configuring-logging) of the Django documentation. Using a rotator and namer to customize log rotation processing -------------------------------------------------------------- An example of how you can define a namer and rotator is given in the following snippet, which shows zlib-based compression of the log file: ``` def namer(name): return name + ".gz" def rotator(source, dest): with open(source, "rb") as sf: data = sf.read() compressed = zlib.compress(data, 9) with open(dest, "wb") as df: df.write(compressed) os.remove(source) rh = logging.handlers.RotatingFileHandler(...) rh.rotator = rotator rh.namer = namer ``` These are not “true” .gz files, as they are bare compressed data, with no “container” such as you’d find in an actual gzip file. This snippet is just for illustration purposes. A more elaborate multiprocessing example ---------------------------------------- The following working example shows how logging can be used with multiprocessing using configuration files. The configurations are fairly simple, but serve to illustrate how more complex ones could be implemented in a real multiprocessing scenario. In the example, the main process spawns a listener process and some worker processes. Each of the main process, the listener and the workers have three separate configurations (the workers all share the same configuration). We can see logging in the main process, how the workers log to a QueueHandler and how the listener implements a QueueListener and a more complex logging configuration, and arranges to dispatch events received via the queue to the handlers specified in the configuration. Note that these configurations are purely illustrative, but you should be able to adapt this example to your own scenario. Here’s the script - the docstrings and the comments hopefully explain how it works: ``` import logging import logging.config import logging.handlers from multiprocessing import Process, Queue, Event, current_process import os import random import time class MyHandler: """ A simple handler for logging events. It runs in the listener process and dispatches events to loggers based on the name in the received record, which then get dispatched, by the logging system, to the handlers configured for those loggers. """ def handle(self, record): if record.name == "root": logger = logging.getLogger() else: logger = logging.getLogger(record.name) if logger.isEnabledFor(record.levelno): # The process name is transformed just to show that it's the listener # doing the logging to files and console record.processName = '%s (for %s)' % (current_process().name, record.processName) logger.handle(record) def listener_process(q, stop_event, config): """ This could be done in the main process, but is just done in a separate process for illustrative purposes. This initialises logging according to the specified configuration, starts the listener and waits for the main process to signal completion via the event. The listener is then stopped, and the process exits. """ logging.config.dictConfig(config) listener = logging.handlers.QueueListener(q, MyHandler()) listener.start() if os.name == 'posix': # On POSIX, the setup logger will have been configured in the # parent process, but should have been disabled following the # dictConfig call. # On Windows, since fork isn't used, the setup logger won't # exist in the child, so it would be created and the message # would appear - hence the "if posix" clause. logger = logging.getLogger('setup') logger.critical('Should not appear, because of disabled logger ...') stop_event.wait() listener.stop() def worker_process(config): """ A number of these are spawned for the purpose of illustration. In practice, they could be a heterogeneous bunch of processes rather than ones which are identical to each other. This initialises logging according to the specified configuration, and logs a hundred messages with random levels to randomly selected loggers. A small sleep is added to allow other processes a chance to run. This is not strictly needed, but it mixes the output from the different processes a bit more than if it's left out. """ logging.config.dictConfig(config) levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL] loggers = ['foo', 'foo.bar', 'foo.bar.baz', 'spam', 'spam.ham', 'spam.ham.eggs'] if os.name == 'posix': # On POSIX, the setup logger will have been configured in the # parent process, but should have been disabled following the # dictConfig call. # On Windows, since fork isn't used, the setup logger won't # exist in the child, so it would be created and the message # would appear - hence the "if posix" clause. logger = logging.getLogger('setup') logger.critical('Should not appear, because of disabled logger ...') for i in range(100): lvl = random.choice(levels) logger = logging.getLogger(random.choice(loggers)) logger.log(lvl, 'Message no. %d', i) time.sleep(0.01) def main(): q = Queue() # The main process gets a simple configuration which prints to the console. config_initial = { 'version': 1, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'level': 'INFO' } }, 'root': { 'handlers': ['console'], 'level': 'DEBUG' } } # The worker process configuration is just a QueueHandler attached to the # root logger, which allows all messages to be sent to the queue. # We disable existing loggers to disable the "setup" logger used in the # parent process. This is needed on POSIX because the logger will # be there in the child following a fork(). config_worker = { 'version': 1, 'disable_existing_loggers': True, 'handlers': { 'queue': { 'class': 'logging.handlers.QueueHandler', 'queue': q } }, 'root': { 'handlers': ['queue'], 'level': 'DEBUG' } } # The listener process configuration shows that the full flexibility of # logging configuration is available to dispatch events to handlers however # you want. # We disable existing loggers to disable the "setup" logger used in the # parent process. This is needed on POSIX because the logger will # be there in the child following a fork(). config_listener = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'detailed': { 'class': 'logging.Formatter', 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s' }, 'simple': { 'class': 'logging.Formatter', 'format': '%(name)-15s %(levelname)-8s %(processName)-10s %(message)s' } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'simple', 'level': 'INFO' }, 'file': { 'class': 'logging.FileHandler', 'filename': 'mplog.log', 'mode': 'w', 'formatter': 'detailed' }, 'foofile': { 'class': 'logging.FileHandler', 'filename': 'mplog-foo.log', 'mode': 'w', 'formatter': 'detailed' }, 'errors': { 'class': 'logging.FileHandler', 'filename': 'mplog-errors.log', 'mode': 'w', 'formatter': 'detailed', 'level': 'ERROR' } }, 'loggers': { 'foo': { 'handlers': ['foofile'] } }, 'root': { 'handlers': ['console', 'file', 'errors'], 'level': 'DEBUG' } } # Log some initial events, just to show that logging in the parent works # normally. logging.config.dictConfig(config_initial) logger = logging.getLogger('setup') logger.info('About to create workers ...') workers = [] for i in range(5): wp = Process(target=worker_process, name='worker %d' % (i + 1), args=(config_worker,)) workers.append(wp) wp.start() logger.info('Started worker: %s', wp.name) logger.info('About to create listener ...') stop_event = Event() lp = Process(target=listener_process, name='listener', args=(q, stop_event, config_listener)) lp.start() logger.info('Started listener') # We now hang around for the workers to finish their work. for wp in workers: wp.join() # Workers all done, listening can now stop. # Logging in the parent still works normally. logger.info('Telling listener to stop ...') stop_event.set() lp.join() logger.info('All done.') if __name__ == '__main__': main() ``` Inserting a BOM into messages sent to a SysLogHandler ----------------------------------------------------- [**RFC 5424**](https://tools.ietf.org/html/rfc5424.html) requires that a Unicode message be sent to a syslog daemon as a set of bytes which have the following structure: an optional pure-ASCII component, followed by a UTF-8 Byte Order Mark (BOM), followed by Unicode encoded using UTF-8. (See the [**relevant section of the specification**](https://tools.ietf.org/html/rfc5424.html#section-6).) In Python 3.1, code was added to [`SysLogHandler`](../library/logging.handlers#logging.handlers.SysLogHandler "logging.handlers.SysLogHandler") to insert a BOM into the message, but unfortunately, it was implemented incorrectly, with the BOM appearing at the beginning of the message and hence not allowing any pure-ASCII component to appear before it. As this behaviour is broken, the incorrect BOM insertion code is being removed from Python 3.2.4 and later. However, it is not being replaced, and if you want to produce [**RFC 5424**](https://tools.ietf.org/html/rfc5424.html)-compliant messages which include a BOM, an optional pure-ASCII sequence before it and arbitrary Unicode after it, encoded using UTF-8, then you need to do the following: 1. Attach a [`Formatter`](../library/logging#logging.Formatter "logging.Formatter") instance to your [`SysLogHandler`](../library/logging.handlers#logging.handlers.SysLogHandler "logging.handlers.SysLogHandler") instance, with a format string such as: ``` 'ASCII section\ufeffUnicode section' ``` The Unicode code point U+FEFF, when encoded using UTF-8, will be encoded as a UTF-8 BOM – the byte-string `b'\xef\xbb\xbf'`. 2. Replace the ASCII section with whatever placeholders you like, but make sure that the data that appears in there after substitution is always ASCII (that way, it will remain unchanged after UTF-8 encoding). 3. Replace the Unicode section with whatever placeholders you like; if the data which appears there after substitution contains characters outside the ASCII range, that’s fine – it will be encoded using UTF-8. The formatted message *will* be encoded using UTF-8 encoding by `SysLogHandler`. If you follow the above rules, you should be able to produce [**RFC 5424**](https://tools.ietf.org/html/rfc5424.html)-compliant messages. If you don’t, logging may not complain, but your messages will not be RFC 5424-compliant, and your syslog daemon may complain. Implementing structured logging ------------------------------- Although most logging messages are intended for reading by humans, and thus not readily machine-parseable, there might be circumstances where you want to output messages in a structured format which *is* capable of being parsed by a program (without needing complex regular expressions to parse the log message). This is straightforward to achieve using the logging package. There are a number of ways in which this could be achieved, but the following is a simple approach which uses JSON to serialise the event in a machine-parseable manner: ``` import json import logging class StructuredMessage: def __init__(self, message, /, **kwargs): self.message = message self.kwargs = kwargs def __str__(self): return '%s >>> %s' % (self.message, json.dumps(self.kwargs)) _ = StructuredMessage # optional, to improve readability logging.basicConfig(level=logging.INFO, format='%(message)s') logging.info(_('message 1', foo='bar', bar='baz', num=123, fnum=123.456)) ``` If the above script is run, it prints: ``` message 1 >>> {"fnum": 123.456, "num": 123, "bar": "baz", "foo": "bar"} ``` Note that the order of items might be different according to the version of Python used. If you need more specialised processing, you can use a custom JSON encoder, as in the following complete example: ``` from __future__ import unicode_literals import json import logging # This next bit is to ensure the script runs unchanged on 2.x and 3.x try: unicode except NameError: unicode = str class Encoder(json.JSONEncoder): def default(self, o): if isinstance(o, set): return tuple(o) elif isinstance(o, unicode): return o.encode('unicode_escape').decode('ascii') return super().default(o) class StructuredMessage: def __init__(self, message, /, **kwargs): self.message = message self.kwargs = kwargs def __str__(self): s = Encoder().encode(self.kwargs) return '%s >>> %s' % (self.message, s) _ = StructuredMessage # optional, to improve readability def main(): logging.basicConfig(level=logging.INFO, format='%(message)s') logging.info(_('message 1', set_value={1, 2, 3}, snowman='\u2603')) if __name__ == '__main__': main() ``` When the above script is run, it prints: ``` message 1 >>> {"snowman": "\u2603", "set_value": [1, 2, 3]} ``` Note that the order of items might be different according to the version of Python used. Customizing handlers with dictConfig() -------------------------------------- There are times when you want to customize logging handlers in particular ways, and if you use [`dictConfig()`](../library/logging.config#logging.config.dictConfig "logging.config.dictConfig") you may be able to do this without subclassing. As an example, consider that you may want to set the ownership of a log file. On POSIX, this is easily done using [`shutil.chown()`](../library/shutil#shutil.chown "shutil.chown"), but the file handlers in the stdlib don’t offer built-in support. You can customize handler creation using a plain function such as: ``` def owned_file_handler(filename, mode='a', encoding=None, owner=None): if owner: if not os.path.exists(filename): open(filename, 'a').close() shutil.chown(filename, *owner) return logging.FileHandler(filename, mode, encoding) ``` You can then specify, in a logging configuration passed to [`dictConfig()`](../library/logging.config#logging.config.dictConfig "logging.config.dictConfig"), that a logging handler be created by calling this function: ``` LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'default': { 'format': '%(asctime)s %(levelname)s %(name)s %(message)s' }, }, 'handlers': { 'file':{ # The values below are popped from this dictionary and # used to create the handler, set the handler's level and # its formatter. '()': owned_file_handler, 'level':'DEBUG', 'formatter': 'default', # The values below are passed to the handler creator callable # as keyword arguments. 'owner': ['pulse', 'pulse'], 'filename': 'chowntest.log', 'mode': 'w', 'encoding': 'utf-8', }, }, 'root': { 'handlers': ['file'], 'level': 'DEBUG', }, } ``` In this example I am setting the ownership using the `pulse` user and group, just for the purposes of illustration. Putting it together into a working script, `chowntest.py`: ``` import logging, logging.config, os, shutil def owned_file_handler(filename, mode='a', encoding=None, owner=None): if owner: if not os.path.exists(filename): open(filename, 'a').close() shutil.chown(filename, *owner) return logging.FileHandler(filename, mode, encoding) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'default': { 'format': '%(asctime)s %(levelname)s %(name)s %(message)s' }, }, 'handlers': { 'file':{ # The values below are popped from this dictionary and # used to create the handler, set the handler's level and # its formatter. '()': owned_file_handler, 'level':'DEBUG', 'formatter': 'default', # The values below are passed to the handler creator callable # as keyword arguments. 'owner': ['pulse', 'pulse'], 'filename': 'chowntest.log', 'mode': 'w', 'encoding': 'utf-8', }, }, 'root': { 'handlers': ['file'], 'level': 'DEBUG', }, } logging.config.dictConfig(LOGGING) logger = logging.getLogger('mylogger') logger.debug('A debug message') ``` To run this, you will probably need to run as `root`: ``` $ sudo python3.3 chowntest.py $ cat chowntest.log 2013-11-05 09:34:51,128 DEBUG mylogger A debug message $ ls -l chowntest.log -rw-r--r-- 1 pulse pulse 55 2013-11-05 09:34 chowntest.log ``` Note that this example uses Python 3.3 because that’s where [`shutil.chown()`](../library/shutil#shutil.chown "shutil.chown") makes an appearance. This approach should work with any Python version that supports [`dictConfig()`](../library/logging.config#logging.config.dictConfig "logging.config.dictConfig") - namely, Python 2.7, 3.2 or later. With pre-3.3 versions, you would need to implement the actual ownership change using e.g. [`os.chown()`](../library/os#os.chown "os.chown"). In practice, the handler-creating function may be in a utility module somewhere in your project. Instead of the line in the configuration: ``` '()': owned_file_handler, ``` you could use e.g.: ``` '()': 'ext://project.util.owned_file_handler', ``` where `project.util` can be replaced with the actual name of the package where the function resides. In the above working script, using `'ext://__main__.owned_file_handler'` should work. Here, the actual callable is resolved by [`dictConfig()`](../library/logging.config#logging.config.dictConfig "logging.config.dictConfig") from the `ext://` specification. This example hopefully also points the way to how you could implement other types of file change - e.g. setting specific POSIX permission bits - in the same way, using [`os.chmod()`](../library/os#os.chmod "os.chmod"). Of course, the approach could also be extended to types of handler other than a [`FileHandler`](../library/logging.handlers#logging.FileHandler "logging.FileHandler") - for example, one of the rotating file handlers, or a different type of handler altogether. Using particular formatting styles throughout your application -------------------------------------------------------------- In Python 3.2, the [`Formatter`](../library/logging#logging.Formatter "logging.Formatter") gained a `style` keyword parameter which, while defaulting to `%` for backward compatibility, allowed the specification of `{` or `$` to support the formatting approaches supported by [`str.format()`](../library/stdtypes#str.format "str.format") and [`string.Template`](../library/string#string.Template "string.Template"). Note that this governs the formatting of logging messages for final output to logs, and is completely orthogonal to how an individual logging message is constructed. Logging calls ([`debug()`](../library/logging#logging.Logger.debug "logging.Logger.debug"), [`info()`](../library/logging#logging.Logger.info "logging.Logger.info") etc.) only take positional parameters for the actual logging message itself, with keyword parameters used only for determining options for how to handle the logging call (e.g. the `exc_info` keyword parameter to indicate that traceback information should be logged, or the `extra` keyword parameter to indicate additional contextual information to be added to the log). So you cannot directly make logging calls using [`str.format()`](../library/stdtypes#str.format "str.format") or [`string.Template`](../library/string#string.Template "string.Template") syntax, because internally the logging package uses %-formatting to merge the format string and the variable arguments. There would no changing this while preserving backward compatibility, since all logging calls which are out there in existing code will be using %-format strings. There have been suggestions to associate format styles with specific loggers, but that approach also runs into backward compatibility problems because any existing code could be using a given logger name and using %-formatting. For logging to work interoperably between any third-party libraries and your code, decisions about formatting need to be made at the level of the individual logging call. This opens up a couple of ways in which alternative formatting styles can be accommodated. ### Using LogRecord factories In Python 3.2, along with the [`Formatter`](../library/logging#logging.Formatter "logging.Formatter") changes mentioned above, the logging package gained the ability to allow users to set their own [`LogRecord`](../library/logging#logging.LogRecord "logging.LogRecord") subclasses, using the [`setLogRecordFactory()`](../library/logging#logging.setLogRecordFactory "logging.setLogRecordFactory") function. You can use this to set your own subclass of [`LogRecord`](../library/logging#logging.LogRecord "logging.LogRecord"), which does the Right Thing by overriding the [`getMessage()`](../library/logging#logging.LogRecord.getMessage "logging.LogRecord.getMessage") method. The base class implementation of this method is where the `msg % args` formatting happens, and where you can substitute your alternate formatting; however, you should be careful to support all formatting styles and allow %-formatting as the default, to ensure interoperability with other code. Care should also be taken to call `str(self.msg)`, just as the base implementation does. Refer to the reference documentation on [`setLogRecordFactory()`](../library/logging#logging.setLogRecordFactory "logging.setLogRecordFactory") and [`LogRecord`](../library/logging#logging.LogRecord "logging.LogRecord") for more information. ### Using custom message objects There is another, perhaps simpler way that you can use {}- and $- formatting to construct your individual log messages. You may recall (from [Using arbitrary objects as messages](logging#arbitrary-object-messages)) that when logging you can use an arbitrary object as a message format string, and that the logging package will call [`str()`](../library/stdtypes#str "str") on that object to get the actual format string. Consider the following two classes: ``` class BraceMessage: def __init__(self, fmt, /, *args, **kwargs): self.fmt = fmt self.args = args self.kwargs = kwargs def __str__(self): return self.fmt.format(*self.args, **self.kwargs) class DollarMessage: def __init__(self, fmt, /, **kwargs): self.fmt = fmt self.kwargs = kwargs def __str__(self): from string import Template return Template(self.fmt).substitute(**self.kwargs) ``` Either of these can be used in place of a format string, to allow {}- or $-formatting to be used to build the actual “message” part which appears in the formatted log output in place of “%(message)s” or “{message}” or “$message”. If you find it a little unwieldy to use the class names whenever you want to log something, you can make it more palatable if you use an alias such as `M` or `_` for the message (or perhaps `__`, if you are using `_` for localization). Examples of this approach are given below. Firstly, formatting with [`str.format()`](../library/stdtypes#str.format "str.format"): ``` >>> __ = BraceMessage >>> print(__('Message with {0} {1}', 2, 'placeholders')) Message with 2 placeholders >>> class Point: pass ... >>> p = Point() >>> p.x = 0.5 >>> p.y = 0.5 >>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})', point=p)) Message with coordinates: (0.50, 0.50) ``` Secondly, formatting with [`string.Template`](../library/string#string.Template "string.Template"): ``` >>> __ = DollarMessage >>> print(__('Message with $num $what', num=2, what='placeholders')) Message with 2 placeholders >>> ``` One thing to note is that you pay no significant performance penalty with this approach: the actual formatting happens not when you make the logging call, but when (and if) the logged message is actually about to be output to a log by a handler. So the only slightly unusual thing which might trip you up is that the parentheses go around the format string and the arguments, not just the format string. That’s because the \_\_ notation is just syntax sugar for a constructor call to one of the `XXXMessage` classes shown above. Configuring filters with dictConfig() ------------------------------------- You *can* configure filters using [`dictConfig()`](../library/logging.config#logging.config.dictConfig "logging.config.dictConfig"), though it might not be obvious at first glance how to do it (hence this recipe). Since [`Filter`](../library/logging#logging.Filter "logging.Filter") is the only filter class included in the standard library, and it is unlikely to cater to many requirements (it’s only there as a base class), you will typically need to define your own [`Filter`](../library/logging#logging.Filter "logging.Filter") subclass with an overridden [`filter()`](../library/logging#logging.Filter.filter "logging.Filter.filter") method. To do this, specify the `()` key in the configuration dictionary for the filter, specifying a callable which will be used to create the filter (a class is the most obvious, but you can provide any callable which returns a [`Filter`](../library/logging#logging.Filter "logging.Filter") instance). Here is a complete example: ``` import logging import logging.config import sys class MyFilter(logging.Filter): def __init__(self, param=None): self.param = param def filter(self, record): if self.param is None: allow = True else: allow = self.param not in record.msg if allow: record.msg = 'changed: ' + record.msg return allow LOGGING = { 'version': 1, 'filters': { 'myfilter': { '()': MyFilter, 'param': 'noshow', } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'filters': ['myfilter'] } }, 'root': { 'level': 'DEBUG', 'handlers': ['console'] }, } if __name__ == '__main__': logging.config.dictConfig(LOGGING) logging.debug('hello') logging.debug('hello - noshow') ``` This example shows how you can pass configuration data to the callable which constructs the instance, in the form of keyword parameters. When run, the above script will print: ``` changed: hello ``` which shows that the filter is working as configured. A couple of extra points to note: * If you can’t refer to the callable directly in the configuration (e.g. if it lives in a different module, and you can’t import it directly where the configuration dictionary is), you can use the form `ext://...` as described in [Access to external objects](../library/logging.config#logging-config-dict-externalobj). For example, you could have used the text `'ext://__main__.MyFilter'` instead of `MyFilter` in the above example. * As well as for filters, this technique can also be used to configure custom handlers and formatters. See [User-defined objects](../library/logging.config#logging-config-dict-userdef) for more information on how logging supports using user-defined objects in its configuration, and see the other cookbook recipe [Customizing handlers with dictConfig()](#custom-handlers) above. Customized exception formatting ------------------------------- There might be times when you want to do customized exception formatting - for argument’s sake, let’s say you want exactly one line per logged event, even when exception information is present. You can do this with a custom formatter class, as shown in the following example: ``` import logging class OneLineExceptionFormatter(logging.Formatter): def formatException(self, exc_info): """ Format an exception so that it prints on a single line. """ result = super().formatException(exc_info) return repr(result) # or format into one line however you want to def format(self, record): s = super().format(record) if record.exc_text: s = s.replace('\n', '') + '|' return s def configure_logging(): fh = logging.FileHandler('output.txt', 'w') f = OneLineExceptionFormatter('%(asctime)s|%(levelname)s|%(message)s|', '%d/%m/%Y %H:%M:%S') fh.setFormatter(f) root = logging.getLogger() root.setLevel(logging.DEBUG) root.addHandler(fh) def main(): configure_logging() logging.info('Sample message') try: x = 1 / 0 except ZeroDivisionError as e: logging.exception('ZeroDivisionError: %s', e) if __name__ == '__main__': main() ``` When run, this produces a file with exactly two lines: ``` 28/01/2015 07:21:23|INFO|Sample message| 28/01/2015 07:21:23|ERROR|ZeroDivisionError: integer division or modulo by zero|'Traceback (most recent call last):\n File "logtest7.py", line 30, in main\n x = 1 / 0\nZeroDivisionError: integer division or modulo by zero'| ``` While the above treatment is simplistic, it points the way to how exception information can be formatted to your liking. The [`traceback`](../library/traceback#module-traceback "traceback: Print or retrieve a stack traceback.") module may be helpful for more specialized needs. Speaking logging messages ------------------------- There might be situations when it is desirable to have logging messages rendered in an audible rather than a visible format. This is easy to do if you have text-to-speech (TTS) functionality available in your system, even if it doesn’t have a Python binding. Most TTS systems have a command line program you can run, and this can be invoked from a handler using [`subprocess`](../library/subprocess#module-subprocess "subprocess: Subprocess management."). It’s assumed here that TTS command line programs won’t expect to interact with users or take a long time to complete, and that the frequency of logged messages will be not so high as to swamp the user with messages, and that it’s acceptable to have the messages spoken one at a time rather than concurrently, The example implementation below waits for one message to be spoken before the next is processed, and this might cause other handlers to be kept waiting. Here is a short example showing the approach, which assumes that the `espeak` TTS package is available: ``` import logging import subprocess import sys class TTSHandler(logging.Handler): def emit(self, record): msg = self.format(record) # Speak slowly in a female English voice cmd = ['espeak', '-s150', '-ven+f3', msg] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) # wait for the program to finish p.communicate() def configure_logging(): h = TTSHandler() root = logging.getLogger() root.addHandler(h) # the default formatter just returns the message root.setLevel(logging.DEBUG) def main(): logging.info('Hello') logging.debug('Goodbye') if __name__ == '__main__': configure_logging() sys.exit(main()) ``` When run, this script should say “Hello” and then “Goodbye” in a female voice. The above approach can, of course, be adapted to other TTS systems and even other systems altogether which can process messages via external programs run from a command line. Buffering logging messages and outputting them conditionally ------------------------------------------------------------ There might be situations where you want to log messages in a temporary area and only output them if a certain condition occurs. For example, you may want to start logging debug events in a function, and if the function completes without errors, you don’t want to clutter the log with the collected debug information, but if there is an error, you want all the debug information to be output as well as the error. Here is an example which shows how you could do this using a decorator for your functions where you want logging to behave this way. It makes use of the [`logging.handlers.MemoryHandler`](../library/logging.handlers#logging.handlers.MemoryHandler "logging.handlers.MemoryHandler"), which allows buffering of logged events until some condition occurs, at which point the buffered events are `flushed` - passed to another handler (the `target` handler) for processing. By default, the `MemoryHandler` flushed when its buffer gets filled up or an event whose level is greater than or equal to a specified threshold is seen. You can use this recipe with a more specialised subclass of `MemoryHandler` if you want custom flushing behavior. The example script has a simple function, `foo`, which just cycles through all the logging levels, writing to `sys.stderr` to say what level it’s about to log at, and then actually logging a message at that level. You can pass a parameter to `foo` which, if true, will log at ERROR and CRITICAL levels - otherwise, it only logs at DEBUG, INFO and WARNING levels. The script just arranges to decorate `foo` with a decorator which will do the conditional logging that’s required. The decorator takes a logger as a parameter and attaches a memory handler for the duration of the call to the decorated function. The decorator can be additionally parameterised using a target handler, a level at which flushing should occur, and a capacity for the buffer (number of records buffered). These default to a [`StreamHandler`](../library/logging.handlers#logging.StreamHandler "logging.StreamHandler") which writes to `sys.stderr`, `logging.ERROR` and `100` respectively. Here’s the script: ``` import logging from logging.handlers import MemoryHandler import sys logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) def log_if_errors(logger, target_handler=None, flush_level=None, capacity=None): if target_handler is None: target_handler = logging.StreamHandler() if flush_level is None: flush_level = logging.ERROR if capacity is None: capacity = 100 handler = MemoryHandler(capacity, flushLevel=flush_level, target=target_handler) def decorator(fn): def wrapper(*args, **kwargs): logger.addHandler(handler) try: return fn(*args, **kwargs) except Exception: logger.exception('call failed') raise finally: super(MemoryHandler, handler).flush() logger.removeHandler(handler) return wrapper return decorator def write_line(s): sys.stderr.write('%s\n' % s) def foo(fail=False): write_line('about to log at DEBUG ...') logger.debug('Actually logged at DEBUG') write_line('about to log at INFO ...') logger.info('Actually logged at INFO') write_line('about to log at WARNING ...') logger.warning('Actually logged at WARNING') if fail: write_line('about to log at ERROR ...') logger.error('Actually logged at ERROR') write_line('about to log at CRITICAL ...') logger.critical('Actually logged at CRITICAL') return fail decorated_foo = log_if_errors(logger)(foo) if __name__ == '__main__': logger.setLevel(logging.DEBUG) write_line('Calling undecorated foo with False') assert not foo(False) write_line('Calling undecorated foo with True') assert foo(True) write_line('Calling decorated foo with False') assert not decorated_foo(False) write_line('Calling decorated foo with True') assert decorated_foo(True) ``` When this script is run, the following output should be observed: ``` Calling undecorated foo with False about to log at DEBUG ... about to log at INFO ... about to log at WARNING ... Calling undecorated foo with True about to log at DEBUG ... about to log at INFO ... about to log at WARNING ... about to log at ERROR ... about to log at CRITICAL ... Calling decorated foo with False about to log at DEBUG ... about to log at INFO ... about to log at WARNING ... Calling decorated foo with True about to log at DEBUG ... about to log at INFO ... about to log at WARNING ... about to log at ERROR ... Actually logged at DEBUG Actually logged at INFO Actually logged at WARNING Actually logged at ERROR about to log at CRITICAL ... Actually logged at CRITICAL ``` As you can see, actual logging output only occurs when an event is logged whose severity is ERROR or greater, but in that case, any previous events at lower severities are also logged. You can of course use the conventional means of decoration: ``` @log_if_errors(logger) def foo(fail=False): ... ``` Formatting times using UTC (GMT) via configuration -------------------------------------------------- Sometimes you want to format times using UTC, which can be done using a class such as `UTCFormatter`, shown below: ``` import logging import time class UTCFormatter(logging.Formatter): converter = time.gmtime ``` and you can then use the `UTCFormatter` in your code instead of [`Formatter`](../library/logging#logging.Formatter "logging.Formatter"). If you want to do that via configuration, you can use the [`dictConfig()`](../library/logging.config#logging.config.dictConfig "logging.config.dictConfig") API with an approach illustrated by the following complete example: ``` import logging import logging.config import time class UTCFormatter(logging.Formatter): converter = time.gmtime LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'utc': { '()': UTCFormatter, 'format': '%(asctime)s %(message)s', }, 'local': { 'format': '%(asctime)s %(message)s', } }, 'handlers': { 'console1': { 'class': 'logging.StreamHandler', 'formatter': 'utc', }, 'console2': { 'class': 'logging.StreamHandler', 'formatter': 'local', }, }, 'root': { 'handlers': ['console1', 'console2'], } } if __name__ == '__main__': logging.config.dictConfig(LOGGING) logging.warning('The local time is %s', time.asctime()) ``` When this script is run, it should print something like: ``` 2015-10-17 12:53:29,501 The local time is Sat Oct 17 13:53:29 2015 2015-10-17 13:53:29,501 The local time is Sat Oct 17 13:53:29 2015 ``` showing how the time is formatted both as local time and UTC, one for each handler. Using a context manager for selective logging --------------------------------------------- There are times when it would be useful to temporarily change the logging configuration and revert it back after doing something. For this, a context manager is the most obvious way of saving and restoring the logging context. Here is a simple example of such a context manager, which allows you to optionally change the logging level and add a logging handler purely in the scope of the context manager: ``` import logging import sys class LoggingContext: def __init__(self, logger, level=None, handler=None, close=True): self.logger = logger self.level = level self.handler = handler self.close = close def __enter__(self): if self.level is not None: self.old_level = self.logger.level self.logger.setLevel(self.level) if self.handler: self.logger.addHandler(self.handler) def __exit__(self, et, ev, tb): if self.level is not None: self.logger.setLevel(self.old_level) if self.handler: self.logger.removeHandler(self.handler) if self.handler and self.close: self.handler.close() # implicit return of None => don't swallow exceptions ``` If you specify a level value, the logger’s level is set to that value in the scope of the with block covered by the context manager. If you specify a handler, it is added to the logger on entry to the block and removed on exit from the block. You can also ask the manager to close the handler for you on block exit - you could do this if you don’t need the handler any more. To illustrate how it works, we can add the following block of code to the above: ``` if __name__ == '__main__': logger = logging.getLogger('foo') logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.INFO) logger.info('1. This should appear just once on stderr.') logger.debug('2. This should not appear.') with LoggingContext(logger, level=logging.DEBUG): logger.debug('3. This should appear once on stderr.') logger.debug('4. This should not appear.') h = logging.StreamHandler(sys.stdout) with LoggingContext(logger, level=logging.DEBUG, handler=h, close=True): logger.debug('5. This should appear twice - once on stderr and once on stdout.') logger.info('6. This should appear just once on stderr.') logger.debug('7. This should not appear.') ``` We initially set the logger’s level to `INFO`, so message #1 appears and message #2 doesn’t. We then change the level to `DEBUG` temporarily in the following `with` block, and so message #3 appears. After the block exits, the logger’s level is restored to `INFO` and so message #4 doesn’t appear. In the next `with` block, we set the level to `DEBUG` again but also add a handler writing to `sys.stdout`. Thus, message #5 appears twice on the console (once via `stderr` and once via `stdout`). After the `with` statement’s completion, the status is as it was before so message #6 appears (like message #1) whereas message #7 doesn’t (just like message #2). If we run the resulting script, the result is as follows: ``` $ python logctx.py 1. This should appear just once on stderr. 3. This should appear once on stderr. 5. This should appear twice - once on stderr and once on stdout. 5. This should appear twice - once on stderr and once on stdout. 6. This should appear just once on stderr. ``` If we run it again, but pipe `stderr` to `/dev/null`, we see the following, which is the only message written to `stdout`: ``` $ python logctx.py 2>/dev/null 5. This should appear twice - once on stderr and once on stdout. ``` Once again, but piping `stdout` to `/dev/null`, we get: ``` $ python logctx.py >/dev/null 1. This should appear just once on stderr. 3. This should appear once on stderr. 5. This should appear twice - once on stderr and once on stdout. 6. This should appear just once on stderr. ``` In this case, the message #5 printed to `stdout` doesn’t appear, as expected. Of course, the approach described here can be generalised, for example to attach logging filters temporarily. Note that the above code works in Python 2 as well as Python 3. A CLI application starter template ---------------------------------- Here’s an example which shows how you can: * Use a logging level based on command-line arguments * Dispatch to multiple subcommands in separate files, all logging at the same level in a consistent way * Make use of simple, minimal configuration Suppose we have a command-line application whose job is to stop, start or restart some services. This could be organised for the purposes of illustration as a file `app.py` that is the main script for the application, with individual commands implemented in `start.py`, `stop.py` and `restart.py`. Suppose further that we want to control the verbosity of the application via a command-line argument, defaulting to `logging.INFO`. Here’s one way that `app.py` could be written: ``` import argparse import importlib import logging import os import sys def main(args=None): scriptname = os.path.basename(__file__) parser = argparse.ArgumentParser(scriptname) levels = ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL') parser.add_argument('--log-level', default='INFO', choices=levels) subparsers = parser.add_subparsers(dest='command', help='Available commands:') start_cmd = subparsers.add_parser('start', help='Start a service') start_cmd.add_argument('name', metavar='NAME', help='Name of service to start') stop_cmd = subparsers.add_parser('stop', help='Stop one or more services') stop_cmd.add_argument('names', metavar='NAME', nargs='+', help='Name of service to stop') restart_cmd = subparsers.add_parser('restart', help='Restart one or more services') restart_cmd.add_argument('names', metavar='NAME', nargs='+', help='Name of service to restart') options = parser.parse_args() # the code to dispatch commands could all be in this file. For the purposes # of illustration only, we implement each command in a separate module. try: mod = importlib.import_module(options.command) cmd = getattr(mod, 'command') except (ImportError, AttributeError): print('Unable to find the code for command \'%s\'' % options.command) return 1 # Could get fancy here and load configuration from file or dictionary logging.basicConfig(level=options.log_level, format='%(levelname)s %(name)s %(message)s') cmd(options) if __name__ == '__main__': sys.exit(main()) ``` And the `start`, `stop` and `restart` commands can be implemented in separate modules, like so for starting: ``` # start.py import logging logger = logging.getLogger(__name__) def command(options): logger.debug('About to start %s', options.name) # actually do the command processing here ... logger.info('Started the \'%s\' service.', options.name) ``` and thus for stopping: ``` # stop.py import logging logger = logging.getLogger(__name__) def command(options): n = len(options.names) if n == 1: plural = '' services = '\'%s\'' % options.names[0] else: plural = 's' services = ', '.join('\'%s\'' % name for name in options.names) i = services.rfind(', ') services = services[:i] + ' and ' + services[i + 2:] logger.debug('About to stop %s', services) # actually do the command processing here ... logger.info('Stopped the %s service%s.', services, plural) ``` and similarly for restarting: ``` # restart.py import logging logger = logging.getLogger(__name__) def command(options): n = len(options.names) if n == 1: plural = '' services = '\'%s\'' % options.names[0] else: plural = 's' services = ', '.join('\'%s\'' % name for name in options.names) i = services.rfind(', ') services = services[:i] + ' and ' + services[i + 2:] logger.debug('About to restart %s', services) # actually do the command processing here ... logger.info('Restarted the %s service%s.', services, plural) ``` If we run this application with the default log level, we get output like this: ``` $ python app.py start foo INFO start Started the 'foo' service. $ python app.py stop foo bar INFO stop Stopped the 'foo' and 'bar' services. $ python app.py restart foo bar baz INFO restart Restarted the 'foo', 'bar' and 'baz' services. ``` The first word is the logging level, and the second word is the module or package name of the place where the event was logged. If we change the logging level, then we can change the information sent to the log. For example, if we want more information: ``` $ python app.py --log-level DEBUG start foo DEBUG start About to start foo INFO start Started the 'foo' service. $ python app.py --log-level DEBUG stop foo bar DEBUG stop About to stop 'foo' and 'bar' INFO stop Stopped the 'foo' and 'bar' services. $ python app.py --log-level DEBUG restart foo bar baz DEBUG restart About to restart 'foo', 'bar' and 'baz' INFO restart Restarted the 'foo', 'bar' and 'baz' services. ``` And if we want less: ``` $ python app.py --log-level WARNING start foo $ python app.py --log-level WARNING stop foo bar $ python app.py --log-level WARNING restart foo bar baz ``` In this case, the commands don’t print anything to the console, since nothing at `WARNING` level or above is logged by them. A Qt GUI for logging -------------------- A question that comes up from time to time is about how to log to a GUI application. The [Qt](https://www.qt.io/) framework is a popular cross-platform UI framework with Python bindings using [PySide2](https://pypi.org/project/PySide2/) or [PyQt5](https://pypi.org/project/PyQt5/) libraries. The following example shows how to log to a Qt GUI. This introduces a simple `QtHandler` class which takes a callable, which should be a slot in the main thread that does GUI updates. A worker thread is also created to show how you can log to the GUI from both the UI itself (via a button for manual logging) as well as a worker thread doing work in the background (here, just logging messages at random levels with random short delays in between). The worker thread is implemented using Qt’s `QThread` class rather than the [`threading`](../library/threading#module-threading "threading: Thread-based parallelism.") module, as there are circumstances where one has to use `QThread`, which offers better integration with other `Qt` components. The code should work with recent releases of either `PySide2` or `PyQt5`. You should be able to adapt the approach to earlier versions of Qt. Please refer to the comments in the code snippet for more detailed information. ``` import datetime import logging import random import sys import time # Deal with minor differences between PySide2 and PyQt5 try: from PySide2 import QtCore, QtGui, QtWidgets Signal = QtCore.Signal Slot = QtCore.Slot except ImportError: from PyQt5 import QtCore, QtGui, QtWidgets Signal = QtCore.pyqtSignal Slot = QtCore.pyqtSlot logger = logging.getLogger(__name__) # # Signals need to be contained in a QObject or subclass in order to be correctly # initialized. # class Signaller(QtCore.QObject): signal = Signal(str, logging.LogRecord) # # Output to a Qt GUI is only supposed to happen on the main thread. So, this # handler is designed to take a slot function which is set up to run in the main # thread. In this example, the function takes a string argument which is a # formatted log message, and the log record which generated it. The formatted # string is just a convenience - you could format a string for output any way # you like in the slot function itself. # # You specify the slot function to do whatever GUI updates you want. The handler # doesn't know or care about specific UI elements. # class QtHandler(logging.Handler): def __init__(self, slotfunc, *args, **kwargs): super().__init__(*args, **kwargs) self.signaller = Signaller() self.signaller.signal.connect(slotfunc) def emit(self, record): s = self.format(record) self.signaller.signal.emit(s, record) # # This example uses QThreads, which means that the threads at the Python level # are named something like "Dummy-1". The function below gets the Qt name of the # current thread. # def ctname(): return QtCore.QThread.currentThread().objectName() # # Used to generate random levels for logging. # LEVELS = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL) # # This worker class represents work that is done in a thread separate to the # main thread. The way the thread is kicked off to do work is via a button press # that connects to a slot in the worker. # # Because the default threadName value in the LogRecord isn't much use, we add # a qThreadName which contains the QThread name as computed above, and pass that # value in an "extra" dictionary which is used to update the LogRecord with the # QThread name. # # This example worker just outputs messages sequentially, interspersed with # random delays of the order of a few seconds. # class Worker(QtCore.QObject): @Slot() def start(self): extra = {'qThreadName': ctname() } logger.debug('Started work', extra=extra) i = 1 # Let the thread run until interrupted. This allows reasonably clean # thread termination. while not QtCore.QThread.currentThread().isInterruptionRequested(): delay = 0.5 + random.random() * 2 time.sleep(delay) level = random.choice(LEVELS) logger.log(level, 'Message after delay of %3.1f: %d', delay, i, extra=extra) i += 1 # # Implement a simple UI for this cookbook example. This contains: # # * A read-only text edit window which holds formatted log messages # * A button to start work and log stuff in a separate thread # * A button to log something from the main thread # * A button to clear the log window # class Window(QtWidgets.QWidget): COLORS = { logging.DEBUG: 'black', logging.INFO: 'blue', logging.WARNING: 'orange', logging.ERROR: 'red', logging.CRITICAL: 'purple', } def __init__(self, app): super().__init__() self.app = app self.textedit = te = QtWidgets.QPlainTextEdit(self) # Set whatever the default monospace font is for the platform f = QtGui.QFont('nosuchfont') f.setStyleHint(f.Monospace) te.setFont(f) te.setReadOnly(True) PB = QtWidgets.QPushButton self.work_button = PB('Start background work', self) self.log_button = PB('Log a message at a random level', self) self.clear_button = PB('Clear log window', self) self.handler = h = QtHandler(self.update_status) # Remember to use qThreadName rather than threadName in the format string. fs = '%(asctime)s %(qThreadName)-12s %(levelname)-8s %(message)s' formatter = logging.Formatter(fs) h.setFormatter(formatter) logger.addHandler(h) # Set up to terminate the QThread when we exit app.aboutToQuit.connect(self.force_quit) # Lay out all the widgets layout = QtWidgets.QVBoxLayout(self) layout.addWidget(te) layout.addWidget(self.work_button) layout.addWidget(self.log_button) layout.addWidget(self.clear_button) self.setFixedSize(900, 400) # Connect the non-worker slots and signals self.log_button.clicked.connect(self.manual_update) self.clear_button.clicked.connect(self.clear_display) # Start a new worker thread and connect the slots for the worker self.start_thread() self.work_button.clicked.connect(self.worker.start) # Once started, the button should be disabled self.work_button.clicked.connect(lambda : self.work_button.setEnabled(False)) def start_thread(self): self.worker = Worker() self.worker_thread = QtCore.QThread() self.worker.setObjectName('Worker') self.worker_thread.setObjectName('WorkerThread') # for qThreadName self.worker.moveToThread(self.worker_thread) # This will start an event loop in the worker thread self.worker_thread.start() def kill_thread(self): # Just tell the worker to stop, then tell it to quit and wait for that # to happen self.worker_thread.requestInterruption() if self.worker_thread.isRunning(): self.worker_thread.quit() self.worker_thread.wait() else: print('worker has already exited.') def force_quit(self): # For use when the window is closed if self.worker_thread.isRunning(): self.kill_thread() # The functions below update the UI and run in the main thread because # that's where the slots are set up @Slot(str, logging.LogRecord) def update_status(self, status, record): color = self.COLORS.get(record.levelno, 'black') s = '<pre><font color="%s">%s</font></pre>' % (color, status) self.textedit.appendHtml(s) @Slot() def manual_update(self): # This function uses the formatted message passed in, but also uses # information from the record to format the message in an appropriate # color according to its severity (level). level = random.choice(LEVELS) extra = {'qThreadName': ctname() } logger.log(level, 'Manually logged!', extra=extra) @Slot() def clear_display(self): self.textedit.clear() def main(): QtCore.QThread.currentThread().setObjectName('MainThread') logging.getLogger().setLevel(logging.DEBUG) app = QtWidgets.QApplication(sys.argv) example = Window(app) example.show() sys.exit(app.exec_()) if __name__=='__main__': main() ``` Patterns to avoid ----------------- Although the preceding sections have described ways of doing things you might need to do or deal with, it is worth mentioning some usage patterns which are *unhelpful*, and which should therefore be avoided in most cases. The following sections are in no particular order. ### Opening the same log file multiple times On Windows, you will generally not be able to open the same file multiple times as this will lead to a “file is in use by another process” error. However, on POSIX platforms you’ll not get any errors if you open the same file multiple times. This could be done accidentally, for example by: * Adding a file handler more than once which references the same file (e.g. by a copy/paste/forget-to-change error). * Opening two files that look different, as they have different names, but are the same because one is a symbolic link to the other. * Forking a process, following which both parent and child have a reference to the same file. This might be through use of the [`multiprocessing`](../library/multiprocessing#module-multiprocessing "multiprocessing: Process-based parallelism.") module, for example. Opening a file multiple times might *appear* to work most of the time, but can lead to a number of problems in practice: * Logging output can be garbled because multiple threads or processes try to write to the same file. Although logging guards against concurrent use of the same handler instance by multiple threads, there is no such protection if concurrent writes are attempted by two different threads using two different handler instances which happen to point to the same file. * An attempt to delete a file (e.g. during file rotation) silently fails, because there is another reference pointing to it. This can lead to confusion and wasted debugging time - log entries end up in unexpected places, or are lost altogether. Use the techniques outlined in [Logging to a single file from multiple processes](#multiple-processes) to circumvent such issues. ### Using loggers as attributes in a class or passing them as parameters While there might be unusual cases where you’ll need to do this, in general there is no point because loggers are singletons. Code can always access a given logger instance by name using `logging.getLogger(name)`, so passing instances around and holding them as instance attributes is pointless. Note that in other languages such as Java and C#, loggers are often static class attributes. However, this pattern doesn’t make sense in Python, where the module (and not the class) is the unit of software decomposition. ### Adding handlers other than `NullHandler` to a logger in a library Configuring logging by adding handlers, formatters and filters is the responsibility of the application developer, not the library developer. If you are maintaining a library, ensure that you don’t add handlers to any of your loggers other than a [`NullHandler`](../library/logging.handlers#logging.NullHandler "logging.NullHandler") instance. ### Creating a lot of loggers Loggers are singletons that are never freed during a script execution, and so creating lots of loggers will use up memory which can’t then be freed. Rather than create a logger per e.g. file processed or network connection made, use the [existing mechanisms](#context-info) for passing contextual information into your logs and restrict the loggers created to those describing areas within your application (generally modules, but occasionally slightly more fine-grained than that).
programming_docs
python String conversion and formatting String conversion and formatting ================================ Functions for number conversion and formatted string output. `int PyOS_snprintf(char *str, size_t size, const char *format, ...)` Output not more than *size* bytes to *str* according to the format string *format* and the extra arguments. See the Unix man page *[snprintf(3)](https://manpages.debian.org/snprintf(3))*. `int PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va)` Output not more than *size* bytes to *str* according to the format string *format* and the variable argument list *va*. Unix man page *[vsnprintf(3)](https://manpages.debian.org/vsnprintf(3))*. [`PyOS_snprintf()`](#c.PyOS_snprintf "PyOS_snprintf") and [`PyOS_vsnprintf()`](#c.PyOS_vsnprintf "PyOS_vsnprintf") wrap the Standard C library functions `snprintf()` and `vsnprintf()`. Their purpose is to guarantee consistent behavior in corner cases, which the Standard C functions do not. The wrappers ensure that `str[size-1]` is always `'\0'` upon return. They never write more than *size* bytes (including the trailing `'\0'`) into str. Both functions require that `str != NULL`, `size > 0` and `format != NULL`. If the platform doesn’t have `vsnprintf()` and the buffer size needed to avoid truncation exceeds *size* by more than 512 bytes, Python aborts with a [`Py_FatalError()`](sys#c.Py_FatalError "Py_FatalError"). The return value (*rv*) for these functions should be interpreted as follows: * When `0 <= rv < size`, the output conversion was successful and *rv* characters were written to *str* (excluding the trailing `'\0'` byte at `str[rv]`). * When `rv >= size`, the output conversion was truncated and a buffer with `rv + 1` bytes would have been needed to succeed. `str[size-1]` is `'\0'` in this case. * When `rv < 0`, “something bad happened.” `str[size-1]` is `'\0'` in this case too, but the rest of *str* is undefined. The exact cause of the error depends on the underlying platform. The following functions provide locale-independent string to number conversions. `double PyOS_string_to_double(const char *s, char **endptr, PyObject *overflow_exception)` Convert a string `s` to a `double`, raising a Python exception on failure. The set of accepted strings corresponds to the set of strings accepted by Python’s [`float()`](../library/functions#float "float") constructor, except that `s` must not have leading or trailing whitespace. The conversion is independent of the current locale. If `endptr` is `NULL`, convert the whole string. Raise [`ValueError`](../library/exceptions#ValueError "ValueError") and return `-1.0` if the string is not a valid representation of a floating-point number. If endptr is not `NULL`, convert as much of the string as possible and set `*endptr` to point to the first unconverted character. If no initial segment of the string is the valid representation of a floating-point number, set `*endptr` to point to the beginning of the string, raise ValueError, and return `-1.0`. If `s` represents a value that is too large to store in a float (for example, `"1e500"` is such a string on many platforms) then if `overflow_exception` is `NULL` return `Py_HUGE_VAL` (with an appropriate sign) and don’t set any exception. Otherwise, `overflow_exception` must point to a Python exception object; raise that exception and return `-1.0`. In both cases, set `*endptr` to point to the first character after the converted value. If any other error occurs during the conversion (for example an out-of-memory error), set the appropriate Python exception and return `-1.0`. New in version 3.1. `char* PyOS_double_to_string(double val, char format_code, int precision, int flags, int *ptype)` Convert a `double` *val* to a string using supplied *format\_code*, *precision*, and *flags*. *format\_code* must be one of `'e'`, `'E'`, `'f'`, `'F'`, `'g'`, `'G'` or `'r'`. For `'r'`, the supplied *precision* must be 0 and is ignored. The `'r'` format code specifies the standard [`repr()`](../library/functions#repr "repr") format. *flags* can be zero or more of the values `Py_DTSF_SIGN`, `Py_DTSF_ADD_DOT_0`, or `Py_DTSF_ALT`, or-ed together: * `Py_DTSF_SIGN` means to always precede the returned string with a sign character, even if *val* is non-negative. * `Py_DTSF_ADD_DOT_0` means to ensure that the returned string will not look like an integer. * `Py_DTSF_ALT` means to apply “alternate” formatting rules. See the documentation for the [`PyOS_snprintf()`](#c.PyOS_snprintf "PyOS_snprintf") `'#'` specifier for details. If *ptype* is non-`NULL`, then the value it points to will be set to one of `Py_DTST_FINITE`, `Py_DTST_INFINITE`, or `Py_DTST_NAN`, signifying that *val* is a finite number, an infinite number, or not a number, respectively. The return value is a pointer to *buffer* with the converted string or `NULL` if the conversion failed. The caller is responsible for freeing the returned string by calling [`PyMem_Free()`](memory#c.PyMem_Free "PyMem_Free"). New in version 3.1. `int PyOS_stricmp(const char *s1, const char *s2)` Case insensitive comparison of strings. The function works almost identically to `strcmp()` except that it ignores the case. `int PyOS_strnicmp(const char *s1, const char *s2, Py_ssize_t size)` Case insensitive comparison of strings. The function works almost identically to `strncmp()` except that it ignores the case. python API and ABI Versioning API and ABI Versioning ====================== `PY_VERSION_HEX` is the Python version number encoded in a single integer. For example if the `PY_VERSION_HEX` is set to `0x030401a2`, the underlying version information can be found by treating it as a 32 bit number in the following manner: | Bytes | Bits (big endian order) | Meaning | | --- | --- | --- | | `1` | `1-8` | `PY_MAJOR_VERSION` (the `3` in `3.4.1a2`) | | `2` | `9-16` | `PY_MINOR_VERSION` (the `4` in `3.4.1a2`) | | `3` | `17-24` | `PY_MICRO_VERSION` (the `1` in `3.4.1a2`) | | `4` | `25-28` | `PY_RELEASE_LEVEL` (`0xA` for alpha, `0xB` for beta, `0xC` for release candidate and `0xF` for final), in this case it is alpha. | | | `29-32` | `PY_RELEASE_SERIAL` (the `2` in `3.4.1a2`, zero for final releases) | Thus `3.4.1a2` is hexversion `0x030401a2`. All the given macros are defined in [Include/patchlevel.h](https://github.com/python/cpython/tree/3.9/Include/patchlevel.h). python Generator Objects Generator Objects ================= Generator objects are what Python uses to implement generator iterators. They are normally created by iterating over a function that yields values, rather than explicitly calling [`PyGen_New()`](#c.PyGen_New "PyGen_New") or [`PyGen_NewWithQualName()`](#c.PyGen_NewWithQualName "PyGen_NewWithQualName"). `PyGenObject` The C structure used for generator objects. `PyTypeObject PyGen_Type` The type object corresponding to generator objects. `int PyGen_Check(PyObject *ob)` Return true if *ob* is a generator object; *ob* must not be `NULL`. This function always succeeds. `int PyGen_CheckExact(PyObject *ob)` Return true if *ob*’s type is [`PyGen_Type`](#c.PyGen_Type "PyGen_Type"); *ob* must not be `NULL`. This function always succeeds. `PyObject* PyGen_New(PyFrameObject *frame)` *Return value: New reference.*Create and return a new generator object based on the *frame* object. A reference to *frame* is stolen by this function. The argument must not be `NULL`. `PyObject* PyGen_NewWithQualName(PyFrameObject *frame, PyObject *name, PyObject *qualname)` *Return value: New reference.*Create and return a new generator object based on the *frame* object, with `__name__` and `__qualname__` set to *name* and *qualname*. A reference to *frame* is stolen by this function. The *frame* argument must not be `NULL`. python Objects for Type Hinting Objects for Type Hinting ======================== Various built-in types for type hinting are provided. Only [GenericAlias](../library/stdtypes#types-genericalias) is exposed to C. `PyObject* Py_GenericAlias(PyObject *origin, PyObject *args)` Create a [GenericAlias](../library/stdtypes#types-genericalias) object. Equivalent to calling the Python class [`types.GenericAlias`](../library/types#types.GenericAlias "types.GenericAlias"). The *origin* and *args* arguments set the `GenericAlias`’s `__origin__` and `__args__` attributes respectively. *origin* should be a [`PyTypeObject*`](type#c.PyTypeObject "PyTypeObject"), and *args* can be a [`PyTupleObject*`](tuple#c.PyTupleObject "PyTupleObject") or any `PyObject*`. If *args* passed is not a tuple, a 1-tuple is automatically constructed and `__args__` is set to `(args,)`. Minimal checking is done for the arguments, so the function will succeed even if *origin* is not a type. The `GenericAlias`’s `__parameters__` attribute is constructed lazily from `__args__`. On failure, an exception is raised and `NULL` is returned. Here’s an example of how to make an extension type generic: ``` ... static PyMethodDef my_obj_methods[] = { // Other methods. ... {"__class_getitem__", (PyCFunction)Py_GenericAlias, METH_O|METH_CLASS, "See PEP 585"} ... } ``` See also The data model method [`__class_getitem__()`](../reference/datamodel#object.__class_getitem__ "object.__class_getitem__"). New in version 3.9. `PyTypeObject Py_GenericAliasType` The C type of the object returned by [`Py_GenericAlias()`](#c.Py_GenericAlias "Py_GenericAlias"). Equivalent to [`types.GenericAlias`](../library/types#types.GenericAlias "types.GenericAlias") in Python. New in version 3.9. python Reference Counting Reference Counting ================== The macros in this section are used for managing reference counts of Python objects. `void Py_INCREF(PyObject *o)` Increment the reference count for object *o*. The object must not be `NULL`; if you aren’t sure that it isn’t `NULL`, use [`Py_XINCREF()`](#c.Py_XINCREF "Py_XINCREF"). `void Py_XINCREF(PyObject *o)` Increment the reference count for object *o*. The object may be `NULL`, in which case the macro has no effect. `void Py_DECREF(PyObject *o)` Decrement the reference count for object *o*. The object must not be `NULL`; if you aren’t sure that it isn’t `NULL`, use [`Py_XDECREF()`](#c.Py_XDECREF "Py_XDECREF"). If the reference count reaches zero, the object’s type’s deallocation function (which must not be `NULL`) is invoked. Warning The deallocation function can cause arbitrary Python code to be invoked (e.g. when a class instance with a [`__del__()`](../reference/datamodel#object.__del__ "object.__del__") method is deallocated). While exceptions in such code are not propagated, the executed code has free access to all Python global variables. This means that any object that is reachable from a global variable should be in a consistent state before [`Py_DECREF()`](#c.Py_DECREF "Py_DECREF") is invoked. For example, code to delete an object from a list should copy a reference to the deleted object in a temporary variable, update the list data structure, and then call [`Py_DECREF()`](#c.Py_DECREF "Py_DECREF") for the temporary variable. `void Py_XDECREF(PyObject *o)` Decrement the reference count for object *o*. The object may be `NULL`, in which case the macro has no effect; otherwise the effect is the same as for [`Py_DECREF()`](#c.Py_DECREF "Py_DECREF"), and the same warning applies. `void Py_CLEAR(PyObject *o)` Decrement the reference count for object *o*. The object may be `NULL`, in which case the macro has no effect; otherwise the effect is the same as for [`Py_DECREF()`](#c.Py_DECREF "Py_DECREF"), except that the argument is also set to `NULL`. The warning for [`Py_DECREF()`](#c.Py_DECREF "Py_DECREF") does not apply with respect to the object passed because the macro carefully uses a temporary variable and sets the argument to `NULL` before decrementing its reference count. It is a good idea to use this macro whenever decrementing the reference count of an object that might be traversed during garbage collection. The following functions are for runtime dynamic embedding of Python: `Py_IncRef(PyObject *o)`, `Py_DecRef(PyObject *o)`. They are simply exported function versions of [`Py_XINCREF()`](#c.Py_XINCREF "Py_XINCREF") and [`Py_XDECREF()`](#c.Py_XDECREF "Py_XDECREF"), respectively. The following functions or macros are only for use within the interpreter core: `_Py_Dealloc()`, `_Py_ForgetReference()`, `_Py_NewReference()`, as well as the global variable `_Py_RefTotal`. python Parsing arguments and building values Parsing arguments and building values ===================================== These functions are useful when creating your own extensions functions and methods. Additional information and examples are available in [Extending and Embedding the Python Interpreter](../extending/index#extending-index). The first three of these functions described, [`PyArg_ParseTuple()`](#c.PyArg_ParseTuple "PyArg_ParseTuple"), [`PyArg_ParseTupleAndKeywords()`](#c.PyArg_ParseTupleAndKeywords "PyArg_ParseTupleAndKeywords"), and [`PyArg_Parse()`](#c.PyArg_Parse "PyArg_Parse"), all use *format strings* which are used to tell the function about the expected arguments. The format strings use the same syntax for each of these functions. Parsing arguments ----------------- A format string consists of zero or more “format units.” A format unit describes one Python object; it is usually a single character or a parenthesized sequence of format units. With a few exceptions, a format unit that is not a parenthesized sequence normally corresponds to a single address argument to these functions. In the following description, the quoted form is the format unit; the entry in (round) parentheses is the Python object type that matches the format unit; and the entry in [square] brackets is the type of the C variable(s) whose address should be passed. ### Strings and buffers These formats allow accessing an object as a contiguous chunk of memory. You don’t have to provide raw storage for the returned unicode or bytes area. In general, when a format sets a pointer to a buffer, the buffer is managed by the corresponding Python object, and the buffer shares the lifetime of this object. You won’t have to release any memory yourself. The only exceptions are `es`, `es#`, `et` and `et#`. However, when a [`Py_buffer`](buffer#c.Py_buffer "Py_buffer") structure gets filled, the underlying buffer is locked so that the caller can subsequently use the buffer even inside a [`Py_BEGIN_ALLOW_THREADS`](init#c.Py_BEGIN_ALLOW_THREADS "Py_BEGIN_ALLOW_THREADS") block without the risk of mutable data being resized or destroyed. As a result, **you have to call** [`PyBuffer_Release()`](buffer#c.PyBuffer_Release "PyBuffer_Release") after you have finished processing the data (or in any early abort case). Unless otherwise stated, buffers are not NUL-terminated. Some formats require a read-only [bytes-like object](../glossary#term-bytes-like-object), and set a pointer instead of a buffer structure. They work by checking that the object’s [`PyBufferProcs.bf_releasebuffer`](typeobj#c.PyBufferProcs.bf_releasebuffer "PyBufferProcs.bf_releasebuffer") field is `NULL`, which disallows mutable objects such as [`bytearray`](../library/stdtypes#bytearray "bytearray"). Note For all `#` variants of formats (`s#`, `y#`, etc.), the type of the length argument (int or [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t")) is controlled by defining the macro `PY_SSIZE_T_CLEAN` before including `Python.h`. If the macro was defined, length is a [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t") rather than an `int`. This behavior will change in a future Python version to only support [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t") and drop `int` support. It is best to always define `PY_SSIZE_T_CLEAN`. `s (str) [const char *]` Convert a Unicode object to a C pointer to a character string. A pointer to an existing string is stored in the character pointer variable whose address you pass. The C string is NUL-terminated. The Python string must not contain embedded null code points; if it does, a [`ValueError`](../library/exceptions#ValueError "ValueError") exception is raised. Unicode objects are converted to C strings using `'utf-8'` encoding. If this conversion fails, a [`UnicodeError`](../library/exceptions#UnicodeError "UnicodeError") is raised. Note This format does not accept [bytes-like objects](../glossary#term-bytes-like-object). If you want to accept filesystem paths and convert them to C character strings, it is preferable to use the `O&` format with [`PyUnicode_FSConverter()`](unicode#c.PyUnicode_FSConverter "PyUnicode_FSConverter") as *converter*. Changed in version 3.5: Previously, [`TypeError`](../library/exceptions#TypeError "TypeError") was raised when embedded null code points were encountered in the Python string. `s* (str or bytes-like object) [Py_buffer]` This format accepts Unicode objects as well as bytes-like objects. It fills a [`Py_buffer`](buffer#c.Py_buffer "Py_buffer") structure provided by the caller. In this case the resulting C string may contain embedded NUL bytes. Unicode objects are converted to C strings using `'utf-8'` encoding. `s# (str, read-only bytes-like object) [const char *, int or Py_ssize_t]` Like `s*`, except that it doesn’t accept mutable objects. The result is stored into two C variables, the first one a pointer to a C string, the second one its length. The string may contain embedded null bytes. Unicode objects are converted to C strings using `'utf-8'` encoding. `z (str or None) [const char *]` Like `s`, but the Python object may also be `None`, in which case the C pointer is set to `NULL`. `z* (str, bytes-like object or None) [Py_buffer]` Like `s*`, but the Python object may also be `None`, in which case the `buf` member of the [`Py_buffer`](buffer#c.Py_buffer "Py_buffer") structure is set to `NULL`. `z# (str, read-only bytes-like object or None) [const char *, int or Py_ssize_t]` Like `s#`, but the Python object may also be `None`, in which case the C pointer is set to `NULL`. `y (read-only bytes-like object) [const char *]` This format converts a bytes-like object to a C pointer to a character string; it does not accept Unicode objects. The bytes buffer must not contain embedded null bytes; if it does, a [`ValueError`](../library/exceptions#ValueError "ValueError") exception is raised. Changed in version 3.5: Previously, [`TypeError`](../library/exceptions#TypeError "TypeError") was raised when embedded null bytes were encountered in the bytes buffer. `y* (bytes-like object) [Py_buffer]` This variant on `s*` doesn’t accept Unicode objects, only bytes-like objects. **This is the recommended way to accept binary data.** `y# (read-only bytes-like object) [const char *, int or Py_ssize_t]` This variant on `s#` doesn’t accept Unicode objects, only bytes-like objects. `S (bytes) [PyBytesObject *]` Requires that the Python object is a [`bytes`](../library/stdtypes#bytes "bytes") object, without attempting any conversion. Raises [`TypeError`](../library/exceptions#TypeError "TypeError") if the object is not a bytes object. The C variable may also be declared as [`PyObject*`](structures#c.PyObject "PyObject"). `Y (bytearray) [PyByteArrayObject *]` Requires that the Python object is a [`bytearray`](../library/stdtypes#bytearray "bytearray") object, without attempting any conversion. Raises [`TypeError`](../library/exceptions#TypeError "TypeError") if the object is not a [`bytearray`](../library/stdtypes#bytearray "bytearray") object. The C variable may also be declared as [`PyObject*`](structures#c.PyObject "PyObject"). `u (str) [const Py_UNICODE *]` Convert a Python Unicode object to a C pointer to a NUL-terminated buffer of Unicode characters. You must pass the address of a [`Py_UNICODE`](unicode#c.Py_UNICODE "Py_UNICODE") pointer variable, which will be filled with the pointer to an existing Unicode buffer. Please note that the width of a [`Py_UNICODE`](unicode#c.Py_UNICODE "Py_UNICODE") character depends on compilation options (it is either 16 or 32 bits). The Python string must not contain embedded null code points; if it does, a [`ValueError`](../library/exceptions#ValueError "ValueError") exception is raised. Changed in version 3.5: Previously, [`TypeError`](../library/exceptions#TypeError "TypeError") was raised when embedded null code points were encountered in the Python string. Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style [`Py_UNICODE`](unicode#c.Py_UNICODE "Py_UNICODE") API; please migrate to using [`PyUnicode_AsWideCharString()`](unicode#c.PyUnicode_AsWideCharString "PyUnicode_AsWideCharString"). `u# (str) [const Py_UNICODE *, int or Py_ssize_t]` This variant on `u` stores into two C variables, the first one a pointer to a Unicode data buffer, the second one its length. This variant allows null code points. Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style [`Py_UNICODE`](unicode#c.Py_UNICODE "Py_UNICODE") API; please migrate to using [`PyUnicode_AsWideCharString()`](unicode#c.PyUnicode_AsWideCharString "PyUnicode_AsWideCharString"). `Z (str or None) [const Py_UNICODE *]` Like `u`, but the Python object may also be `None`, in which case the [`Py_UNICODE`](unicode#c.Py_UNICODE "Py_UNICODE") pointer is set to `NULL`. Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style [`Py_UNICODE`](unicode#c.Py_UNICODE "Py_UNICODE") API; please migrate to using [`PyUnicode_AsWideCharString()`](unicode#c.PyUnicode_AsWideCharString "PyUnicode_AsWideCharString"). `Z# (str or None) [const Py_UNICODE *, int or Py_ssize_t]` Like `u#`, but the Python object may also be `None`, in which case the [`Py_UNICODE`](unicode#c.Py_UNICODE "Py_UNICODE") pointer is set to `NULL`. Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style [`Py_UNICODE`](unicode#c.Py_UNICODE "Py_UNICODE") API; please migrate to using [`PyUnicode_AsWideCharString()`](unicode#c.PyUnicode_AsWideCharString "PyUnicode_AsWideCharString"). `U (str) [PyObject *]` Requires that the Python object is a Unicode object, without attempting any conversion. Raises [`TypeError`](../library/exceptions#TypeError "TypeError") if the object is not a Unicode object. The C variable may also be declared as [`PyObject*`](structures#c.PyObject "PyObject"). `w* (read-write bytes-like object) [Py_buffer]` This format accepts any object which implements the read-write buffer interface. It fills a [`Py_buffer`](buffer#c.Py_buffer "Py_buffer") structure provided by the caller. The buffer may contain embedded null bytes. The caller have to call [`PyBuffer_Release()`](buffer#c.PyBuffer_Release "PyBuffer_Release") when it is done with the buffer. `es (str) [const char *encoding, char **buffer]` This variant on `s` is used for encoding Unicode into a character buffer. It only works for encoded data without embedded NUL bytes. This format requires two arguments. The first is only used as input, and must be a `const char*` which points to the name of an encoding as a NUL-terminated string, or `NULL`, in which case `'utf-8'` encoding is used. An exception is raised if the named encoding is not known to Python. The second argument must be a `char**`; the value of the pointer it references will be set to a buffer with the contents of the argument text. The text will be encoded in the encoding specified by the first argument. [`PyArg_ParseTuple()`](#c.PyArg_ParseTuple "PyArg_ParseTuple") will allocate a buffer of the needed size, copy the encoded data into this buffer and adjust *\*buffer* to reference the newly allocated storage. The caller is responsible for calling [`PyMem_Free()`](memory#c.PyMem_Free "PyMem_Free") to free the allocated buffer after use. `et (str, bytes or bytearray) [const char *encoding, char **buffer]` Same as `es` except that byte string objects are passed through without recoding them. Instead, the implementation assumes that the byte string object uses the encoding passed in as parameter. `es# (str) [const char *encoding, char **buffer, int or Py_ssize_t *buffer_length]` This variant on `s#` is used for encoding Unicode into a character buffer. Unlike the `es` format, this variant allows input data which contains NUL characters. It requires three arguments. The first is only used as input, and must be a `const char*` which points to the name of an encoding as a NUL-terminated string, or `NULL`, in which case `'utf-8'` encoding is used. An exception is raised if the named encoding is not known to Python. The second argument must be a `char**`; the value of the pointer it references will be set to a buffer with the contents of the argument text. The text will be encoded in the encoding specified by the first argument. The third argument must be a pointer to an integer; the referenced integer will be set to the number of bytes in the output buffer. There are two modes of operation: If *\*buffer* points a `NULL` pointer, the function will allocate a buffer of the needed size, copy the encoded data into this buffer and set *\*buffer* to reference the newly allocated storage. The caller is responsible for calling [`PyMem_Free()`](memory#c.PyMem_Free "PyMem_Free") to free the allocated buffer after usage. If *\*buffer* points to a non-`NULL` pointer (an already allocated buffer), [`PyArg_ParseTuple()`](#c.PyArg_ParseTuple "PyArg_ParseTuple") will use this location as the buffer and interpret the initial value of *\*buffer\_length* as the buffer size. It will then copy the encoded data into the buffer and NUL-terminate it. If the buffer is not large enough, a [`ValueError`](../library/exceptions#ValueError "ValueError") will be set. In both cases, *\*buffer\_length* is set to the length of the encoded data without the trailing NUL byte. `et# (str, bytes or bytearray) [const char *encoding, char **buffer, int or Py_ssize_t *buffer_length]` Same as `es#` except that byte string objects are passed through without recoding them. Instead, the implementation assumes that the byte string object uses the encoding passed in as parameter. ### Numbers `b (int) [unsigned char]` Convert a nonnegative Python integer to an unsigned tiny int, stored in a C `unsigned char`. `B (int) [unsigned char]` Convert a Python integer to a tiny int without overflow checking, stored in a C `unsigned char`. `h (int) [short int]` Convert a Python integer to a C `short int`. `H (int) [unsigned short int]` Convert a Python integer to a C `unsigned short int`, without overflow checking. `i (int) [int]` Convert a Python integer to a plain C `int`. `I (int) [unsigned int]` Convert a Python integer to a C `unsigned int`, without overflow checking. `l (int) [long int]` Convert a Python integer to a C `long int`. `k (int) [unsigned long]` Convert a Python integer to a C `unsigned long` without overflow checking. `L (int) [long long]` Convert a Python integer to a C `long long`. `K (int) [unsigned long long]` Convert a Python integer to a C `unsigned long long` without overflow checking. `n (int) [Py_ssize_t]` Convert a Python integer to a C [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t"). `c (bytes or bytearray of length 1) [char]` Convert a Python byte, represented as a [`bytes`](../library/stdtypes#bytes "bytes") or [`bytearray`](../library/stdtypes#bytearray "bytearray") object of length 1, to a C `char`. Changed in version 3.3: Allow [`bytearray`](../library/stdtypes#bytearray "bytearray") objects. `C (str of length 1) [int]` Convert a Python character, represented as a [`str`](../library/stdtypes#str "str") object of length 1, to a C `int`. `f (float) [float]` Convert a Python floating point number to a C `float`. `d (float) [double]` Convert a Python floating point number to a C `double`. `D (complex) [Py_complex]` Convert a Python complex number to a C [`Py_complex`](complex#c.Py_complex "Py_complex") structure. ### Other objects `O (object) [PyObject *]` Store a Python object (without any conversion) in a C object pointer. The C program thus receives the actual object that was passed. The object’s reference count is not increased. The pointer stored is not `NULL`. `O! (object) [typeobject, PyObject *]` Store a Python object in a C object pointer. This is similar to `O`, but takes two C arguments: the first is the address of a Python type object, the second is the address of the C variable (of type [`PyObject*`](structures#c.PyObject "PyObject")) into which the object pointer is stored. If the Python object does not have the required type, [`TypeError`](../library/exceptions#TypeError "TypeError") is raised. `O& (object) [converter, anything]` Convert a Python object to a C variable through a *converter* function. This takes two arguments: the first is a function, the second is the address of a C variable (of arbitrary type), converted to `void *`. The *converter* function in turn is called as follows: ``` status = converter(object, address); ``` where *object* is the Python object to be converted and *address* is the `void*` argument that was passed to the [`PyArg_Parse*()`](#c.PyArg_Parse "PyArg_Parse") function. The returned *status* should be `1` for a successful conversion and `0` if the conversion has failed. When the conversion fails, the *converter* function should raise an exception and leave the content of *address* unmodified. If the *converter* returns `Py_CLEANUP_SUPPORTED`, it may get called a second time if the argument parsing eventually fails, giving the converter a chance to release any memory that it had already allocated. In this second call, the *object* parameter will be `NULL`; *address* will have the same value as in the original call. Changed in version 3.1: `Py_CLEANUP_SUPPORTED` was added. `p (bool) [int]` Tests the value passed in for truth (a boolean **p**redicate) and converts the result to its equivalent C true/false integer value. Sets the int to `1` if the expression was true and `0` if it was false. This accepts any valid Python value. See [Truth Value Testing](../library/stdtypes#truth) for more information about how Python tests values for truth. New in version 3.3. `(items) (tuple) [matching-items]` The object must be a Python sequence whose length is the number of format units in *items*. The C arguments must correspond to the individual format units in *items*. Format units for sequences may be nested. It is possible to pass “long” integers (integers whose value exceeds the platform’s `LONG_MAX`) however no proper range checking is done — the most significant bits are silently truncated when the receiving field is too small to receive the value (actually, the semantics are inherited from downcasts in C — your mileage may vary). A few other characters have a meaning in a format string. These may not occur inside nested parentheses. They are: `|` Indicates that the remaining arguments in the Python argument list are optional. The C variables corresponding to optional arguments should be initialized to their default value — when an optional argument is not specified, [`PyArg_ParseTuple()`](#c.PyArg_ParseTuple "PyArg_ParseTuple") does not touch the contents of the corresponding C variable(s). `$` [`PyArg_ParseTupleAndKeywords()`](#c.PyArg_ParseTupleAndKeywords "PyArg_ParseTupleAndKeywords") only: Indicates that the remaining arguments in the Python argument list are keyword-only. Currently, all keyword-only arguments must also be optional arguments, so `|` must always be specified before `$` in the format string. New in version 3.3. `:` The list of format units ends here; the string after the colon is used as the function name in error messages (the “associated value” of the exception that [`PyArg_ParseTuple()`](#c.PyArg_ParseTuple "PyArg_ParseTuple") raises). `;` The list of format units ends here; the string after the semicolon is used as the error message *instead* of the default error message. `:` and `;` mutually exclude each other. Note that any Python object references which are provided to the caller are *borrowed* references; do not decrement their reference count! Additional arguments passed to these functions must be addresses of variables whose type is determined by the format string; these are used to store values from the input tuple. There are a few cases, as described in the list of format units above, where these parameters are used as input values; they should match what is specified for the corresponding format unit in that case. For the conversion to succeed, the *arg* object must match the format and the format must be exhausted. On success, the [`PyArg_Parse*()`](#c.PyArg_Parse "PyArg_Parse") functions return true, otherwise they return false and raise an appropriate exception. When the [`PyArg_Parse*()`](#c.PyArg_Parse "PyArg_Parse") functions fail due to conversion failure in one of the format units, the variables at the addresses corresponding to that and the following format units are left untouched. ### API Functions `int PyArg_ParseTuple(PyObject *args, const char *format, ...)` Parse the parameters of a function that takes only positional parameters into local variables. Returns true on success; on failure, it returns false and raises the appropriate exception. `int PyArg_VaParse(PyObject *args, const char *format, va_list vargs)` Identical to [`PyArg_ParseTuple()`](#c.PyArg_ParseTuple "PyArg_ParseTuple"), except that it accepts a va\_list rather than a variable number of arguments. `int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], ...)` Parse the parameters of a function that takes both positional and keyword parameters into local variables. The *keywords* argument is a `NULL`-terminated array of keyword parameter names. Empty names denote [positional-only parameters](../glossary#positional-only-parameter). Returns true on success; on failure, it returns false and raises the appropriate exception. Changed in version 3.6: Added support for [positional-only parameters](../glossary#positional-only-parameter). `int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], va_list vargs)` Identical to [`PyArg_ParseTupleAndKeywords()`](#c.PyArg_ParseTupleAndKeywords "PyArg_ParseTupleAndKeywords"), except that it accepts a va\_list rather than a variable number of arguments. `int PyArg_ValidateKeywordArguments(PyObject *)` Ensure that the keys in the keywords argument dictionary are strings. This is only needed if [`PyArg_ParseTupleAndKeywords()`](#c.PyArg_ParseTupleAndKeywords "PyArg_ParseTupleAndKeywords") is not used, since the latter already does this check. New in version 3.2. `int PyArg_Parse(PyObject *args, const char *format, ...)` Function used to deconstruct the argument lists of “old-style” functions — these are functions which use the `METH_OLDARGS` parameter parsing method, which has been removed in Python 3. This is not recommended for use in parameter parsing in new code, and most code in the standard interpreter has been modified to no longer use this for that purpose. It does remain a convenient way to decompose other tuples, however, and may continue to be used for that purpose. `int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)` A simpler form of parameter retrieval which does not use a format string to specify the types of the arguments. Functions which use this method to retrieve their parameters should be declared as [`METH_VARARGS`](structures#METH_VARARGS "METH_VARARGS") in function or method tables. The tuple containing the actual parameters should be passed as *args*; it must actually be a tuple. The length of the tuple must be at least *min* and no more than *max*; *min* and *max* may be equal. Additional arguments must be passed to the function, each of which should be a pointer to a [`PyObject*`](structures#c.PyObject "PyObject") variable; these will be filled in with the values from *args*; they will contain borrowed references. The variables which correspond to optional parameters not given by *args* will not be filled in; these should be initialized by the caller. This function returns true on success and false if *args* is not a tuple or contains the wrong number of elements; an exception will be set if there was a failure. This is an example of the use of this function, taken from the sources for the `_weakref` helper module for weak references: ``` static PyObject * weakref_ref(PyObject *self, PyObject *args) { PyObject *object; PyObject *callback = NULL; PyObject *result = NULL; if (PyArg_UnpackTuple(args, "ref", 1, 2, &object, &callback)) { result = PyWeakref_NewRef(object, callback); } return result; } ``` The call to [`PyArg_UnpackTuple()`](#c.PyArg_UnpackTuple "PyArg_UnpackTuple") in this example is entirely equivalent to this call to [`PyArg_ParseTuple()`](#c.PyArg_ParseTuple "PyArg_ParseTuple"): ``` PyArg_ParseTuple(args, "O|O:ref", &object, &callback) ``` Building values --------------- `PyObject* Py_BuildValue(const char *format, ...)` *Return value: New reference.*Create a new value based on a format string similar to those accepted by the [`PyArg_Parse*()`](#c.PyArg_Parse "PyArg_Parse") family of functions and a sequence of values. Returns the value or `NULL` in the case of an error; an exception will be raised if `NULL` is returned. [`Py_BuildValue()`](#c.Py_BuildValue "Py_BuildValue") does not always build a tuple. It builds a tuple only if its format string contains two or more format units. If the format string is empty, it returns `None`; if it contains exactly one format unit, it returns whatever object is described by that format unit. To force it to return a tuple of size 0 or one, parenthesize the format string. When memory buffers are passed as parameters to supply data to build objects, as for the `s` and `s#` formats, the required data is copied. Buffers provided by the caller are never referenced by the objects created by [`Py_BuildValue()`](#c.Py_BuildValue "Py_BuildValue"). In other words, if your code invokes `malloc()` and passes the allocated memory to [`Py_BuildValue()`](#c.Py_BuildValue "Py_BuildValue"), your code is responsible for calling `free()` for that memory once [`Py_BuildValue()`](#c.Py_BuildValue "Py_BuildValue") returns. In the following description, the quoted form is the format unit; the entry in (round) parentheses is the Python object type that the format unit will return; and the entry in [square] brackets is the type of the C value(s) to be passed. The characters space, tab, colon and comma are ignored in format strings (but not within format units such as `s#`). This can be used to make long format strings a tad more readable. `s (str or None) [const char *]` Convert a null-terminated C string to a Python [`str`](../library/stdtypes#str "str") object using `'utf-8'` encoding. If the C string pointer is `NULL`, `None` is used. `s# (str or None) [const char *, int or Py_ssize_t]` Convert a C string and its length to a Python [`str`](../library/stdtypes#str "str") object using `'utf-8'` encoding. If the C string pointer is `NULL`, the length is ignored and `None` is returned. `y (bytes) [const char *]` This converts a C string to a Python [`bytes`](../library/stdtypes#bytes "bytes") object. If the C string pointer is `NULL`, `None` is returned. `y# (bytes) [const char *, int or Py_ssize_t]` This converts a C string and its lengths to a Python object. If the C string pointer is `NULL`, `None` is returned. `z (str or None) [const char *]` Same as `s`. `z# (str or None) [const char *, int or Py_ssize_t]` Same as `s#`. `u (str) [const wchar_t *]` Convert a null-terminated `wchar_t` buffer of Unicode (UTF-16 or UCS-4) data to a Python Unicode object. If the Unicode buffer pointer is `NULL`, `None` is returned. `u# (str) [const wchar_t *, int or Py_ssize_t]` Convert a Unicode (UTF-16 or UCS-4) data buffer and its length to a Python Unicode object. If the Unicode buffer pointer is `NULL`, the length is ignored and `None` is returned. `U (str or None) [const char *]` Same as `s`. `U# (str or None) [const char *, int or Py_ssize_t]` Same as `s#`. `i (int) [int]` Convert a plain C `int` to a Python integer object. `b (int) [char]` Convert a plain C `char` to a Python integer object. `h (int) [short int]` Convert a plain C `short int` to a Python integer object. `l (int) [long int]` Convert a C `long int` to a Python integer object. `B (int) [unsigned char]` Convert a C `unsigned char` to a Python integer object. `H (int) [unsigned short int]` Convert a C `unsigned short int` to a Python integer object. `I (int) [unsigned int]` Convert a C `unsigned int` to a Python integer object. `k (int) [unsigned long]` Convert a C `unsigned long` to a Python integer object. `L (int) [long long]` Convert a C `long long` to a Python integer object. `K (int) [unsigned long long]` Convert a C `unsigned long long` to a Python integer object. `n (int) [Py_ssize_t]` Convert a C [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t") to a Python integer. `c (bytes of length 1) [char]` Convert a C `int` representing a byte to a Python [`bytes`](../library/stdtypes#bytes "bytes") object of length 1. `C (str of length 1) [int]` Convert a C `int` representing a character to Python [`str`](../library/stdtypes#str "str") object of length 1. `d (float) [double]` Convert a C `double` to a Python floating point number. `f (float) [float]` Convert a C `float` to a Python floating point number. `D (complex) [Py_complex *]` Convert a C [`Py_complex`](complex#c.Py_complex "Py_complex") structure to a Python complex number. `O (object) [PyObject *]` Pass a Python object untouched (except for its reference count, which is incremented by one). If the object passed in is a `NULL` pointer, it is assumed that this was caused because the call producing the argument found an error and set an exception. Therefore, [`Py_BuildValue()`](#c.Py_BuildValue "Py_BuildValue") will return `NULL` but won’t raise an exception. If no exception has been raised yet, [`SystemError`](../library/exceptions#SystemError "SystemError") is set. `S (object) [PyObject *]` Same as `O`. `N (object) [PyObject *]` Same as `O`, except it doesn’t increment the reference count on the object. Useful when the object is created by a call to an object constructor in the argument list. `O& (object) [converter, anything]` Convert *anything* to a Python object through a *converter* function. The function is called with *anything* (which should be compatible with `void*`) as its argument and should return a “new” Python object, or `NULL` if an error occurred. `(items) (tuple) [matching-items]` Convert a sequence of C values to a Python tuple with the same number of items. `[items] (list) [matching-items]` Convert a sequence of C values to a Python list with the same number of items. `{items} (dict) [matching-items]` Convert a sequence of C values to a Python dictionary. Each pair of consecutive C values adds one item to the dictionary, serving as key and value, respectively. If there is an error in the format string, the [`SystemError`](../library/exceptions#SystemError "SystemError") exception is set and `NULL` returned. `PyObject* Py_VaBuildValue(const char *format, va_list vargs)` *Return value: New reference.*Identical to [`Py_BuildValue()`](#c.Py_BuildValue "Py_BuildValue"), except that it accepts a va\_list rather than a variable number of arguments.
programming_docs
python Supporting Cyclic Garbage Collection Supporting Cyclic Garbage Collection ==================================== Python’s support for detecting and collecting garbage which involves circular references requires support from object types which are “containers” for other objects which may also be containers. Types which do not store references to other objects, or which only store references to atomic types (such as numbers or strings), do not need to provide any explicit support for garbage collection. To create a container type, the [`tp_flags`](typeobj#c.PyTypeObject.tp_flags "PyTypeObject.tp_flags") field of the type object must include the [`Py_TPFLAGS_HAVE_GC`](typeobj#Py_TPFLAGS_HAVE_GC "Py_TPFLAGS_HAVE_GC") and provide an implementation of the [`tp_traverse`](typeobj#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse") handler. If instances of the type are mutable, a [`tp_clear`](typeobj#c.PyTypeObject.tp_clear "PyTypeObject.tp_clear") implementation must also be provided. `Py_TPFLAGS_HAVE_GC` Objects with a type with this flag set must conform with the rules documented here. For convenience these objects will be referred to as container objects. Constructors for container types must conform to two rules: 1. The memory for the object must be allocated using [`PyObject_GC_New()`](#c.PyObject_GC_New "PyObject_GC_New") or [`PyObject_GC_NewVar()`](#c.PyObject_GC_NewVar "PyObject_GC_NewVar"). 2. Once all the fields which may contain references to other containers are initialized, it must call [`PyObject_GC_Track()`](#c.PyObject_GC_Track "PyObject_GC_Track"). Similarly, the deallocator for the object must conform to a similar pair of rules: 1. Before fields which refer to other containers are invalidated, [`PyObject_GC_UnTrack()`](#c.PyObject_GC_UnTrack "PyObject_GC_UnTrack") must be called. 2. The object’s memory must be deallocated using [`PyObject_GC_Del()`](#c.PyObject_GC_Del "PyObject_GC_Del"). Warning If a type adds the Py\_TPFLAGS\_HAVE\_GC, then it *must* implement at least a [`tp_traverse`](typeobj#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse") handler or explicitly use one from its subclass or subclasses. When calling [`PyType_Ready()`](type#c.PyType_Ready "PyType_Ready") or some of the APIs that indirectly call it like [`PyType_FromSpecWithBases()`](type#c.PyType_FromSpecWithBases "PyType_FromSpecWithBases") or [`PyType_FromSpec()`](type#c.PyType_FromSpec "PyType_FromSpec") the interpreter will automatically populate the [`tp_flags`](typeobj#c.PyTypeObject.tp_flags "PyTypeObject.tp_flags"), [`tp_traverse`](typeobj#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse") and [`tp_clear`](typeobj#c.PyTypeObject.tp_clear "PyTypeObject.tp_clear") fields if the type inherits from a class that implements the garbage collector protocol and the child class does *not* include the [`Py_TPFLAGS_HAVE_GC`](typeobj#Py_TPFLAGS_HAVE_GC "Py_TPFLAGS_HAVE_GC") flag. `TYPE* PyObject_GC_New(TYPE, PyTypeObject *type)` Analogous to [`PyObject_New()`](allocation#c.PyObject_New "PyObject_New") but for container objects with the [`Py_TPFLAGS_HAVE_GC`](typeobj#Py_TPFLAGS_HAVE_GC "Py_TPFLAGS_HAVE_GC") flag set. `TYPE* PyObject_GC_NewVar(TYPE, PyTypeObject *type, Py_ssize_t size)` Analogous to [`PyObject_NewVar()`](allocation#c.PyObject_NewVar "PyObject_NewVar") but for container objects with the [`Py_TPFLAGS_HAVE_GC`](typeobj#Py_TPFLAGS_HAVE_GC "Py_TPFLAGS_HAVE_GC") flag set. `TYPE* PyObject_GC_Resize(TYPE, PyVarObject *op, Py_ssize_t newsize)` Resize an object allocated by [`PyObject_NewVar()`](allocation#c.PyObject_NewVar "PyObject_NewVar"). Returns the resized object or `NULL` on failure. *op* must not be tracked by the collector yet. `void PyObject_GC_Track(PyObject *op)` Adds the object *op* to the set of container objects tracked by the collector. The collector can run at unexpected times so objects must be valid while being tracked. This should be called once all the fields followed by the [`tp_traverse`](typeobj#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse") handler become valid, usually near the end of the constructor. `int PyObject_IS_GC(PyObject *obj)` Returns non-zero if the object implements the garbage collector protocol, otherwise returns 0. The object cannot be tracked by the garbage collector if this function returns 0. `int PyObject_GC_IsTracked(PyObject *op)` Returns 1 if the object type of *op* implements the GC protocol and *op* is being currently tracked by the garbage collector and 0 otherwise. This is analogous to the Python function [`gc.is_tracked()`](../library/gc#gc.is_tracked "gc.is_tracked"). New in version 3.9. `int PyObject_GC_IsFinalized(PyObject *op)` Returns 1 if the object type of *op* implements the GC protocol and *op* has been already finalized by the garbage collector and 0 otherwise. This is analogous to the Python function [`gc.is_finalized()`](../library/gc#gc.is_finalized "gc.is_finalized"). New in version 3.9. `void PyObject_GC_Del(void *op)` Releases memory allocated to an object using [`PyObject_GC_New()`](#c.PyObject_GC_New "PyObject_GC_New") or [`PyObject_GC_NewVar()`](#c.PyObject_GC_NewVar "PyObject_GC_NewVar"). `void PyObject_GC_UnTrack(void *op)` Remove the object *op* from the set of container objects tracked by the collector. Note that [`PyObject_GC_Track()`](#c.PyObject_GC_Track "PyObject_GC_Track") can be called again on this object to add it back to the set of tracked objects. The deallocator ([`tp_dealloc`](typeobj#c.PyTypeObject.tp_dealloc "PyTypeObject.tp_dealloc") handler) should call this for the object before any of the fields used by the [`tp_traverse`](typeobj#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse") handler become invalid. Changed in version 3.8: The `_PyObject_GC_TRACK()` and `_PyObject_GC_UNTRACK()` macros have been removed from the public C API. The [`tp_traverse`](typeobj#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse") handler accepts a function parameter of this type: `int (*visitproc)(PyObject *object, void *arg)` Type of the visitor function passed to the [`tp_traverse`](typeobj#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse") handler. The function should be called with an object to traverse as *object* and the third parameter to the [`tp_traverse`](typeobj#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse") handler as *arg*. The Python core uses several visitor functions to implement cyclic garbage detection; it’s not expected that users will need to write their own visitor functions. The [`tp_traverse`](typeobj#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse") handler must have the following type: `int (*traverseproc)(PyObject *self, visitproc visit, void *arg)` Traversal function for a container object. Implementations must call the *visit* function for each object directly contained by *self*, with the parameters to *visit* being the contained object and the *arg* value passed to the handler. The *visit* function must not be called with a `NULL` object argument. If *visit* returns a non-zero value that value should be returned immediately. To simplify writing [`tp_traverse`](typeobj#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse") handlers, a [`Py_VISIT()`](#c.Py_VISIT "Py_VISIT") macro is provided. In order to use this macro, the [`tp_traverse`](typeobj#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse") implementation must name its arguments exactly *visit* and *arg*: `void Py_VISIT(PyObject *o)` If *o* is not `NULL`, call the *visit* callback, with arguments *o* and *arg*. If *visit* returns a non-zero value, then return it. Using this macro, [`tp_traverse`](typeobj#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse") handlers look like: ``` static int my_traverse(Noddy *self, visitproc visit, void *arg) { Py_VISIT(self->foo); Py_VISIT(self->bar); return 0; } ``` The [`tp_clear`](typeobj#c.PyTypeObject.tp_clear "PyTypeObject.tp_clear") handler must be of the [`inquiry`](#c.inquiry "inquiry") type, or `NULL` if the object is immutable. `int (*inquiry)(PyObject *self)` Drop references that may have created reference cycles. Immutable objects do not have to define this method since they can never directly create reference cycles. Note that the object must still be valid after calling this method (don’t just call [`Py_DECREF()`](refcounting#c.Py_DECREF "Py_DECREF") on a reference). The collector will call this method if it detects that this object is involved in a reference cycle. python Sequence Protocol Sequence Protocol ================= `int PySequence_Check(PyObject *o)` Return `1` if the object provides the sequence protocol, and `0` otherwise. Note that it returns `1` for Python classes with a [`__getitem__()`](../reference/datamodel#object.__getitem__ "object.__getitem__") method, unless they are [`dict`](../library/stdtypes#dict "dict") subclasses, since in general it is impossible to determine what type of keys the class supports. This function always succeeds. `Py_ssize_t PySequence_Size(PyObject *o)` `Py_ssize_t PySequence_Length(PyObject *o)` Returns the number of objects in sequence *o* on success, and `-1` on failure. This is equivalent to the Python expression `len(o)`. `PyObject* PySequence_Concat(PyObject *o1, PyObject *o2)` *Return value: New reference.*Return the concatenation of *o1* and *o2* on success, and `NULL` on failure. This is the equivalent of the Python expression `o1 + o2`. `PyObject* PySequence_Repeat(PyObject *o, Py_ssize_t count)` *Return value: New reference.*Return the result of repeating sequence object *o* *count* times, or `NULL` on failure. This is the equivalent of the Python expression `o * count`. `PyObject* PySequence_InPlaceConcat(PyObject *o1, PyObject *o2)` *Return value: New reference.*Return the concatenation of *o1* and *o2* on success, and `NULL` on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python expression `o1 += o2`. `PyObject* PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)` *Return value: New reference.*Return the result of repeating sequence object *o* *count* times, or `NULL` on failure. The operation is done *in-place* when *o* supports it. This is the equivalent of the Python expression `o *= count`. `PyObject* PySequence_GetItem(PyObject *o, Py_ssize_t i)` *Return value: New reference.*Return the *i*th element of *o*, or `NULL` on failure. This is the equivalent of the Python expression `o[i]`. `PyObject* PySequence_GetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2)` *Return value: New reference.*Return the slice of sequence object *o* between *i1* and *i2*, or `NULL` on failure. This is the equivalent of the Python expression `o[i1:i2]`. `int PySequence_SetItem(PyObject *o, Py_ssize_t i, PyObject *v)` Assign object *v* to the *i*th element of *o*. Raise an exception and return `-1` on failure; return `0` on success. This is the equivalent of the Python statement `o[i] = v`. This function *does not* steal a reference to *v*. If *v* is `NULL`, the element is deleted, but this feature is deprecated in favour of using [`PySequence_DelItem()`](#c.PySequence_DelItem "PySequence_DelItem"). `int PySequence_DelItem(PyObject *o, Py_ssize_t i)` Delete the *i*th element of object *o*. Returns `-1` on failure. This is the equivalent of the Python statement `del o[i]`. `int PySequence_SetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2, PyObject *v)` Assign the sequence object *v* to the slice in sequence object *o* from *i1* to *i2*. This is the equivalent of the Python statement `o[i1:i2] = v`. `int PySequence_DelSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2)` Delete the slice in sequence object *o* from *i1* to *i2*. Returns `-1` on failure. This is the equivalent of the Python statement `del o[i1:i2]`. `Py_ssize_t PySequence_Count(PyObject *o, PyObject *value)` Return the number of occurrences of *value* in *o*, that is, return the number of keys for which `o[key] == value`. On failure, return `-1`. This is equivalent to the Python expression `o.count(value)`. `int PySequence_Contains(PyObject *o, PyObject *value)` Determine if *o* contains *value*. If an item in *o* is equal to *value*, return `1`, otherwise return `0`. On error, return `-1`. This is equivalent to the Python expression `value in o`. `Py_ssize_t PySequence_Index(PyObject *o, PyObject *value)` Return the first index *i* for which `o[i] == value`. On error, return `-1`. This is equivalent to the Python expression `o.index(value)`. `PyObject* PySequence_List(PyObject *o)` *Return value: New reference.*Return a list object with the same contents as the sequence or iterable *o*, or `NULL` on failure. The returned list is guaranteed to be new. This is equivalent to the Python expression `list(o)`. `PyObject* PySequence_Tuple(PyObject *o)` *Return value: New reference.*Return a tuple object with the same contents as the sequence or iterable *o*, or `NULL` on failure. If *o* is a tuple, a new reference will be returned, otherwise a tuple will be constructed with the appropriate contents. This is equivalent to the Python expression `tuple(o)`. `PyObject* PySequence_Fast(PyObject *o, const char *m)` *Return value: New reference.*Return the sequence or iterable *o* as an object usable by the other `PySequence_Fast*` family of functions. If the object is not a sequence or iterable, raises [`TypeError`](../library/exceptions#TypeError "TypeError") with *m* as the message text. Returns `NULL` on failure. The `PySequence_Fast*` functions are thus named because they assume *o* is a [`PyTupleObject`](tuple#c.PyTupleObject "PyTupleObject") or a [`PyListObject`](list#c.PyListObject "PyListObject") and access the data fields of *o* directly. As a CPython implementation detail, if *o* is already a sequence or list, it will be returned. `Py_ssize_t PySequence_Fast_GET_SIZE(PyObject *o)` Returns the length of *o*, assuming that *o* was returned by [`PySequence_Fast()`](#c.PySequence_Fast "PySequence_Fast") and that *o* is not `NULL`. The size can also be retrieved by calling [`PySequence_Size()`](#c.PySequence_Size "PySequence_Size") on *o*, but [`PySequence_Fast_GET_SIZE()`](#c.PySequence_Fast_GET_SIZE "PySequence_Fast_GET_SIZE") is faster because it can assume *o* is a list or tuple. `PyObject* PySequence_Fast_GET_ITEM(PyObject *o, Py_ssize_t i)` *Return value: Borrowed reference.*Return the *i*th element of *o*, assuming that *o* was returned by [`PySequence_Fast()`](#c.PySequence_Fast "PySequence_Fast"), *o* is not `NULL`, and that *i* is within bounds. `PyObject** PySequence_Fast_ITEMS(PyObject *o)` Return the underlying array of PyObject pointers. Assumes that *o* was returned by [`PySequence_Fast()`](#c.PySequence_Fast "PySequence_Fast") and *o* is not `NULL`. Note, if a list gets resized, the reallocation may relocate the items array. So, only use the underlying array pointer in contexts where the sequence cannot change. `PyObject* PySequence_ITEM(PyObject *o, Py_ssize_t i)` *Return value: New reference.*Return the *i*th element of *o* or `NULL` on failure. Faster form of [`PySequence_GetItem()`](#c.PySequence_GetItem "PySequence_GetItem") but without checking that [`PySequence_Check()`](#c.PySequence_Check "PySequence_Check") on *o* is true and without adjustment for negative indices. python Context Variables Objects Context Variables Objects ========================= Note Changed in version 3.7.1: In Python 3.7.1 the signatures of all context variables C APIs were **changed** to use [`PyObject`](structures#c.PyObject "PyObject") pointers instead of [`PyContext`](#c.PyContext "PyContext"), [`PyContextVar`](#c.PyContextVar "PyContextVar"), and [`PyContextToken`](#c.PyContextToken "PyContextToken"), e.g.: ``` // in 3.7.0: PyContext *PyContext_New(void); // in 3.7.1+: PyObject *PyContext_New(void); ``` See [bpo-34762](https://bugs.python.org/issue?@action=redirect&bpo=34762) for more details. New in version 3.7. This section details the public C API for the [`contextvars`](../library/contextvars#module-contextvars "contextvars: Context Variables") module. `PyContext` The C structure used to represent a [`contextvars.Context`](../library/contextvars#contextvars.Context "contextvars.Context") object. `PyContextVar` The C structure used to represent a [`contextvars.ContextVar`](../library/contextvars#contextvars.ContextVar "contextvars.ContextVar") object. `PyContextToken` The C structure used to represent a [`contextvars.Token`](../library/contextvars#contextvars.Token "contextvars.Token") object. `PyTypeObject PyContext_Type` The type object representing the *context* type. `PyTypeObject PyContextVar_Type` The type object representing the *context variable* type. `PyTypeObject PyContextToken_Type` The type object representing the *context variable token* type. Type-check macros: `int PyContext_CheckExact(PyObject *o)` Return true if *o* is of type [`PyContext_Type`](#c.PyContext_Type "PyContext_Type"). *o* must not be `NULL`. This function always succeeds. `int PyContextVar_CheckExact(PyObject *o)` Return true if *o* is of type [`PyContextVar_Type`](#c.PyContextVar_Type "PyContextVar_Type"). *o* must not be `NULL`. This function always succeeds. `int PyContextToken_CheckExact(PyObject *o)` Return true if *o* is of type [`PyContextToken_Type`](#c.PyContextToken_Type "PyContextToken_Type"). *o* must not be `NULL`. This function always succeeds. Context object management functions: `PyObject *PyContext_New(void)` *Return value: New reference.*Create a new empty context object. Returns `NULL` if an error has occurred. `PyObject *PyContext_Copy(PyObject *ctx)` *Return value: New reference.*Create a shallow copy of the passed *ctx* context object. Returns `NULL` if an error has occurred. `PyObject *PyContext_CopyCurrent(void)` *Return value: New reference.*Create a shallow copy of the current thread context. Returns `NULL` if an error has occurred. `int PyContext_Enter(PyObject *ctx)` Set *ctx* as the current context for the current thread. Returns `0` on success, and `-1` on error. `int PyContext_Exit(PyObject *ctx)` Deactivate the *ctx* context and restore the previous context as the current context for the current thread. Returns `0` on success, and `-1` on error. Context variable functions: `PyObject *PyContextVar_New(const char *name, PyObject *def)` *Return value: New reference.*Create a new `ContextVar` object. The *name* parameter is used for introspection and debug purposes. The *def* parameter specifies a default value for the context variable, or `NULL` for no default. If an error has occurred, this function returns `NULL`. `int PyContextVar_Get(PyObject *var, PyObject *default_value, PyObject **value)` Get the value of a context variable. Returns `-1` if an error has occurred during lookup, and `0` if no error occurred, whether or not a value was found. If the context variable was found, *value* will be a pointer to it. If the context variable was *not* found, *value* will point to: * *default\_value*, if not `NULL`; * the default value of *var*, if not `NULL`; * `NULL` Except for `NULL`, the function returns a new reference. `PyObject *PyContextVar_Set(PyObject *var, PyObject *value)` *Return value: New reference.*Set the value of *var* to *value* in the current context. Returns a new token object for this change, or `NULL` if an error has occurred. `int PyContextVar_Reset(PyObject *var, PyObject *token)` Reset the state of the *var* context variable to that it was in before [`PyContextVar_Set()`](#c.PyContextVar_Set "PyContextVar_Set") that returned the *token* was called. This function returns `0` on success and `-1` on error.
programming_docs
python Old Buffer Protocol Old Buffer Protocol =================== Deprecated since version 3.0. These functions were part of the “old buffer protocol” API in Python 2. In Python 3, this protocol doesn’t exist anymore but the functions are still exposed to ease porting 2.x code. They act as a compatibility wrapper around the [new buffer protocol](buffer#bufferobjects), but they don’t give you control over the lifetime of the resources acquired when a buffer is exported. Therefore, it is recommended that you call [`PyObject_GetBuffer()`](buffer#c.PyObject_GetBuffer "PyObject_GetBuffer") (or the `y*` or `w*` [format codes](arg#arg-parsing) with the [`PyArg_ParseTuple()`](arg#c.PyArg_ParseTuple "PyArg_ParseTuple") family of functions) to get a buffer view over an object, and [`PyBuffer_Release()`](buffer#c.PyBuffer_Release "PyBuffer_Release") when the buffer view can be released. `int PyObject_AsCharBuffer(PyObject *obj, const char **buffer, Py_ssize_t *buffer_len)` Returns a pointer to a read-only memory location usable as character-based input. The *obj* argument must support the single-segment character buffer interface. On success, returns `0`, sets *buffer* to the memory location and *buffer\_len* to the buffer length. Returns `-1` and sets a [`TypeError`](../library/exceptions#TypeError "TypeError") on error. `int PyObject_AsReadBuffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len)` Returns a pointer to a read-only memory location containing arbitrary data. The *obj* argument must support the single-segment readable buffer interface. On success, returns `0`, sets *buffer* to the memory location and *buffer\_len* to the buffer length. Returns `-1` and sets a [`TypeError`](../library/exceptions#TypeError "TypeError") on error. `int PyObject_CheckReadBuffer(PyObject *o)` Returns `1` if *o* supports the single-segment readable buffer interface. Otherwise returns `0`. This function always succeeds. Note that this function tries to get and release a buffer, and exceptions which occur while calling corresponding functions will get suppressed. To get error reporting use [`PyObject_GetBuffer()`](buffer#c.PyObject_GetBuffer "PyObject_GetBuffer") instead. `int PyObject_AsWriteBuffer(PyObject *obj, void **buffer, Py_ssize_t *buffer_len)` Returns a pointer to a writable memory location. The *obj* argument must support the single-segment, character buffer interface. On success, returns `0`, sets *buffer* to the memory location and *buffer\_len* to the buffer length. Returns `-1` and sets a [`TypeError`](../library/exceptions#TypeError "TypeError") on error. python Instance Method Objects Instance Method Objects ======================= An instance method is a wrapper for a [`PyCFunction`](structures#c.PyCFunction "PyCFunction") and the new way to bind a [`PyCFunction`](structures#c.PyCFunction "PyCFunction") to a class object. It replaces the former call `PyMethod_New(func, NULL, class)`. `PyTypeObject PyInstanceMethod_Type` This instance of [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject") represents the Python instance method type. It is not exposed to Python programs. `int PyInstanceMethod_Check(PyObject *o)` Return true if *o* is an instance method object (has type [`PyInstanceMethod_Type`](#c.PyInstanceMethod_Type "PyInstanceMethod_Type")). The parameter must not be `NULL`. This function always succeeds. `PyObject* PyInstanceMethod_New(PyObject *func)` *Return value: New reference.*Return a new instance method object, with *func* being any callable object. *func* is the function that will be called when the instance method is called. `PyObject* PyInstanceMethod_Function(PyObject *im)` *Return value: Borrowed reference.*Return the function object associated with the instance method *im*. `PyObject* PyInstanceMethod_GET_FUNCTION(PyObject *im)` *Return value: Borrowed reference.*Macro version of [`PyInstanceMethod_Function()`](#c.PyInstanceMethod_Function "PyInstanceMethod_Function") which avoids error checking. python Abstract Objects Layer Abstract Objects Layer ====================== The functions in this chapter interact with Python objects regardless of their type, or with wide classes of object types (e.g. all numerical types, or all sequence types). When used on object types for which they do not apply, they will raise a Python exception. It is not possible to use these functions on objects that are not properly initialized, such as a list object that has been created by [`PyList_New()`](list#c.PyList_New "PyList_New"), but whose items have not been set to some non-`NULL` value yet. * [Object Protocol](object) * [Call Protocol](call) + [The tp\_call Protocol](call#the-tp-call-protocol) + [The Vectorcall Protocol](call#the-vectorcall-protocol) - [Recursion Control](call#recursion-control) - [Vectorcall Support API](call#vectorcall-support-api) + [Object Calling API](call#object-calling-api) + [Call Support API](call#call-support-api) * [Number Protocol](number) * [Sequence Protocol](sequence) * [Mapping Protocol](mapping) * [Iterator Protocol](iter) * [Buffer Protocol](buffer) + [Buffer structure](buffer#buffer-structure) + [Buffer request types](buffer#buffer-request-types) - [request-independent fields](buffer#request-independent-fields) - [readonly, format](buffer#readonly-format) - [shape, strides, suboffsets](buffer#shape-strides-suboffsets) - [contiguity requests](buffer#contiguity-requests) - [compound requests](buffer#compound-requests) + [Complex arrays](buffer#complex-arrays) - [NumPy-style: shape and strides](buffer#numpy-style-shape-and-strides) - [PIL-style: shape, strides and suboffsets](buffer#pil-style-shape-strides-and-suboffsets) + [Buffer-related functions](buffer#buffer-related-functions) * [Old Buffer Protocol](objbuffer) python Initialization, Finalization, and Threads Initialization, Finalization, and Threads ========================================= See also [Python Initialization Configuration](init_config#init-config). Before Python Initialization ---------------------------- In an application embedding Python, the [`Py_Initialize()`](#c.Py_Initialize "Py_Initialize") function must be called before using any other Python/C API functions; with the exception of a few functions and the [global configuration variables](#global-conf-vars). The following functions can be safely called before Python is initialized: * Configuration functions: + [`PyImport_AppendInittab()`](import#c.PyImport_AppendInittab "PyImport_AppendInittab") + [`PyImport_ExtendInittab()`](import#c.PyImport_ExtendInittab "PyImport_ExtendInittab") + `PyInitFrozenExtensions()` + [`PyMem_SetAllocator()`](memory#c.PyMem_SetAllocator "PyMem_SetAllocator") + [`PyMem_SetupDebugHooks()`](memory#c.PyMem_SetupDebugHooks "PyMem_SetupDebugHooks") + [`PyObject_SetArenaAllocator()`](memory#c.PyObject_SetArenaAllocator "PyObject_SetArenaAllocator") + [`Py_SetPath()`](#c.Py_SetPath "Py_SetPath") + [`Py_SetProgramName()`](#c.Py_SetProgramName "Py_SetProgramName") + [`Py_SetPythonHome()`](#c.Py_SetPythonHome "Py_SetPythonHome") + [`Py_SetStandardStreamEncoding()`](#c.Py_SetStandardStreamEncoding "Py_SetStandardStreamEncoding") + [`PySys_AddWarnOption()`](sys#c.PySys_AddWarnOption "PySys_AddWarnOption") + [`PySys_AddXOption()`](sys#c.PySys_AddXOption "PySys_AddXOption") + [`PySys_ResetWarnOptions()`](sys#c.PySys_ResetWarnOptions "PySys_ResetWarnOptions") * Informative functions: + [`Py_IsInitialized()`](#c.Py_IsInitialized "Py_IsInitialized") + [`PyMem_GetAllocator()`](memory#c.PyMem_GetAllocator "PyMem_GetAllocator") + [`PyObject_GetArenaAllocator()`](memory#c.PyObject_GetArenaAllocator "PyObject_GetArenaAllocator") + [`Py_GetBuildInfo()`](#c.Py_GetBuildInfo "Py_GetBuildInfo") + [`Py_GetCompiler()`](#c.Py_GetCompiler "Py_GetCompiler") + [`Py_GetCopyright()`](#c.Py_GetCopyright "Py_GetCopyright") + [`Py_GetPlatform()`](#c.Py_GetPlatform "Py_GetPlatform") + [`Py_GetVersion()`](#c.Py_GetVersion "Py_GetVersion") * Utilities: + [`Py_DecodeLocale()`](sys#c.Py_DecodeLocale "Py_DecodeLocale") * Memory allocators: + [`PyMem_RawMalloc()`](memory#c.PyMem_RawMalloc "PyMem_RawMalloc") + [`PyMem_RawRealloc()`](memory#c.PyMem_RawRealloc "PyMem_RawRealloc") + [`PyMem_RawCalloc()`](memory#c.PyMem_RawCalloc "PyMem_RawCalloc") + [`PyMem_RawFree()`](memory#c.PyMem_RawFree "PyMem_RawFree") Note The following functions **should not be called** before [`Py_Initialize()`](#c.Py_Initialize "Py_Initialize"): [`Py_EncodeLocale()`](sys#c.Py_EncodeLocale "Py_EncodeLocale"), [`Py_GetPath()`](#c.Py_GetPath "Py_GetPath"), [`Py_GetPrefix()`](#c.Py_GetPrefix "Py_GetPrefix"), [`Py_GetExecPrefix()`](#c.Py_GetExecPrefix "Py_GetExecPrefix"), [`Py_GetProgramFullPath()`](#c.Py_GetProgramFullPath "Py_GetProgramFullPath"), [`Py_GetPythonHome()`](#c.Py_GetPythonHome "Py_GetPythonHome"), [`Py_GetProgramName()`](#c.Py_GetProgramName "Py_GetProgramName") and [`PyEval_InitThreads()`](#c.PyEval_InitThreads "PyEval_InitThreads"). Global configuration variables ------------------------------ Python has variables for the global configuration to control different features and options. By default, these flags are controlled by [command line options](../using/cmdline#using-on-interface-options). When a flag is set by an option, the value of the flag is the number of times that the option was set. For example, `-b` sets [`Py_BytesWarningFlag`](#c.Py_BytesWarningFlag "Py_BytesWarningFlag") to 1 and `-bb` sets [`Py_BytesWarningFlag`](#c.Py_BytesWarningFlag "Py_BytesWarningFlag") to 2. `int Py_BytesWarningFlag` Issue a warning when comparing [`bytes`](../library/stdtypes#bytes "bytes") or [`bytearray`](../library/stdtypes#bytearray "bytearray") with [`str`](../library/stdtypes#str "str") or [`bytes`](../library/stdtypes#bytes "bytes") with [`int`](../library/functions#int "int"). Issue an error if greater or equal to `2`. Set by the [`-b`](../using/cmdline#cmdoption-b) option. `int Py_DebugFlag` Turn on parser debugging output (for expert only, depending on compilation options). Set by the [`-d`](../using/cmdline#cmdoption-d) option and the [`PYTHONDEBUG`](../using/cmdline#envvar-PYTHONDEBUG) environment variable. `int Py_DontWriteBytecodeFlag` If set to non-zero, Python won’t try to write `.pyc` files on the import of source modules. Set by the [`-B`](../using/cmdline#id1) option and the [`PYTHONDONTWRITEBYTECODE`](../using/cmdline#envvar-PYTHONDONTWRITEBYTECODE) environment variable. `int Py_FrozenFlag` Suppress error messages when calculating the module search path in [`Py_GetPath()`](#c.Py_GetPath "Py_GetPath"). Private flag used by `_freeze_importlib` and `frozenmain` programs. `int Py_HashRandomizationFlag` Set to `1` if the [`PYTHONHASHSEED`](../using/cmdline#envvar-PYTHONHASHSEED) environment variable is set to a non-empty string. If the flag is non-zero, read the [`PYTHONHASHSEED`](../using/cmdline#envvar-PYTHONHASHSEED) environment variable to initialize the secret hash seed. `int Py_IgnoreEnvironmentFlag` Ignore all `PYTHON*` environment variables, e.g. [`PYTHONPATH`](../using/cmdline#envvar-PYTHONPATH) and [`PYTHONHOME`](../using/cmdline#envvar-PYTHONHOME), that might be set. Set by the [`-E`](../using/cmdline#cmdoption-e) and [`-I`](../using/cmdline#id2) options. `int Py_InspectFlag` When a script is passed as first argument or the [`-c`](../using/cmdline#cmdoption-c) option is used, enter interactive mode after executing the script or the command, even when [`sys.stdin`](../library/sys#sys.stdin "sys.stdin") does not appear to be a terminal. Set by the [`-i`](../using/cmdline#cmdoption-i) option and the [`PYTHONINSPECT`](../using/cmdline#envvar-PYTHONINSPECT) environment variable. `int Py_InteractiveFlag` Set by the [`-i`](../using/cmdline#cmdoption-i) option. `int Py_IsolatedFlag` Run Python in isolated mode. In isolated mode [`sys.path`](../library/sys#sys.path "sys.path") contains neither the script’s directory nor the user’s site-packages directory. Set by the [`-I`](../using/cmdline#id2) option. New in version 3.4. `int Py_LegacyWindowsFSEncodingFlag` If the flag is non-zero, use the `mbcs` encoding instead of the UTF-8 encoding for the filesystem encoding. Set to `1` if the [`PYTHONLEGACYWINDOWSFSENCODING`](../using/cmdline#envvar-PYTHONLEGACYWINDOWSFSENCODING) environment variable is set to a non-empty string. See [**PEP 529**](https://www.python.org/dev/peps/pep-0529) for more details. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Windows. `int Py_LegacyWindowsStdioFlag` If the flag is non-zero, use [`io.FileIO`](../library/io#io.FileIO "io.FileIO") instead of `WindowsConsoleIO` for [`sys`](../library/sys#module-sys "sys: Access system-specific parameters and functions.") standard streams. Set to `1` if the [`PYTHONLEGACYWINDOWSSTDIO`](../using/cmdline#envvar-PYTHONLEGACYWINDOWSSTDIO) environment variable is set to a non-empty string. See [**PEP 528**](https://www.python.org/dev/peps/pep-0528) for more details. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Windows. `int Py_NoSiteFlag` Disable the import of the module [`site`](../library/site#module-site "site: Module responsible for site-specific configuration.") and the site-dependent manipulations of [`sys.path`](../library/sys#sys.path "sys.path") that it entails. Also disable these manipulations if [`site`](../library/site#module-site "site: Module responsible for site-specific configuration.") is explicitly imported later (call [`site.main()`](../library/site#site.main "site.main") if you want them to be triggered). Set by the [`-S`](../using/cmdline#id3) option. `int Py_NoUserSiteDirectory` Don’t add the [`user site-packages directory`](../library/site#site.USER_SITE "site.USER_SITE") to [`sys.path`](../library/sys#sys.path "sys.path"). Set by the [`-s`](../using/cmdline#cmdoption-s) and [`-I`](../using/cmdline#id2) options, and the [`PYTHONNOUSERSITE`](../using/cmdline#envvar-PYTHONNOUSERSITE) environment variable. `int Py_OptimizeFlag` Set by the [`-O`](../using/cmdline#cmdoption-o) option and the [`PYTHONOPTIMIZE`](../using/cmdline#envvar-PYTHONOPTIMIZE) environment variable. `int Py_QuietFlag` Don’t display the copyright and version messages even in interactive mode. Set by the [`-q`](../using/cmdline#cmdoption-q) option. New in version 3.2. `int Py_UnbufferedStdioFlag` Force the stdout and stderr streams to be unbuffered. Set by the [`-u`](../using/cmdline#cmdoption-u) option and the [`PYTHONUNBUFFERED`](../using/cmdline#envvar-PYTHONUNBUFFERED) environment variable. `int Py_VerboseFlag` Print a message each time a module is initialized, showing the place (filename or built-in module) from which it is loaded. If greater or equal to `2`, print a message for each file that is checked for when searching for a module. Also provides information on module cleanup at exit. Set by the [`-v`](../using/cmdline#id4) option and the [`PYTHONVERBOSE`](../using/cmdline#envvar-PYTHONVERBOSE) environment variable. Initializing and finalizing the interpreter ------------------------------------------- `void Py_Initialize()` Initialize the Python interpreter. In an application embedding Python, this should be called before using any other Python/C API functions; see [Before Python Initialization](#pre-init-safe) for the few exceptions. This initializes the table of loaded modules (`sys.modules`), and creates the fundamental modules [`builtins`](../library/builtins#module-builtins "builtins: The module that provides the built-in namespace."), [`__main__`](../library/__main__#module-__main__ "__main__: The environment where the top-level script is run.") and [`sys`](../library/sys#module-sys "sys: Access system-specific parameters and functions."). It also initializes the module search path (`sys.path`). It does not set `sys.argv`; use [`PySys_SetArgvEx()`](#c.PySys_SetArgvEx "PySys_SetArgvEx") for that. This is a no-op when called for a second time (without calling [`Py_FinalizeEx()`](#c.Py_FinalizeEx "Py_FinalizeEx") first). There is no return value; it is a fatal error if the initialization fails. Note On Windows, changes the console mode from `O_TEXT` to `O_BINARY`, which will also affect non-Python uses of the console using the C Runtime. `void Py_InitializeEx(int initsigs)` This function works like [`Py_Initialize()`](#c.Py_Initialize "Py_Initialize") if *initsigs* is `1`. If *initsigs* is `0`, it skips initialization registration of signal handlers, which might be useful when Python is embedded. `int Py_IsInitialized()` Return true (nonzero) when the Python interpreter has been initialized, false (zero) if not. After [`Py_FinalizeEx()`](#c.Py_FinalizeEx "Py_FinalizeEx") is called, this returns false until [`Py_Initialize()`](#c.Py_Initialize "Py_Initialize") is called again. `int Py_FinalizeEx()` Undo all initializations made by [`Py_Initialize()`](#c.Py_Initialize "Py_Initialize") and subsequent use of Python/C API functions, and destroy all sub-interpreters (see [`Py_NewInterpreter()`](#c.Py_NewInterpreter "Py_NewInterpreter") below) that were created and not yet destroyed since the last call to [`Py_Initialize()`](#c.Py_Initialize "Py_Initialize"). Ideally, this frees all memory allocated by the Python interpreter. This is a no-op when called for a second time (without calling [`Py_Initialize()`](#c.Py_Initialize "Py_Initialize") again first). Normally the return value is `0`. If there were errors during finalization (flushing buffered data), `-1` is returned. This function is provided for a number of reasons. An embedding application might want to restart Python without having to restart the application itself. An application that has loaded the Python interpreter from a dynamically loadable library (or DLL) might want to free all memory allocated by Python before unloading the DLL. During a hunt for memory leaks in an application a developer might want to free all memory allocated by Python before exiting from the application. **Bugs and caveats:** The destruction of modules and objects in modules is done in random order; this may cause destructors ([`__del__()`](../reference/datamodel#object.__del__ "object.__del__") methods) to fail when they depend on other objects (even functions) or modules. Dynamically loaded extension modules loaded by Python are not unloaded. Small amounts of memory allocated by the Python interpreter may not be freed (if you find a leak, please report it). Memory tied up in circular references between objects is not freed. Some memory allocated by extension modules may not be freed. Some extensions may not work properly if their initialization routine is called more than once; this can happen if an application calls [`Py_Initialize()`](#c.Py_Initialize "Py_Initialize") and [`Py_FinalizeEx()`](#c.Py_FinalizeEx "Py_FinalizeEx") more than once. Raises an [auditing event](../library/sys#auditing) `cpython._PySys_ClearAuditHooks` with no arguments. New in version 3.6. `void Py_Finalize()` This is a backwards-compatible version of [`Py_FinalizeEx()`](#c.Py_FinalizeEx "Py_FinalizeEx") that disregards the return value. Process-wide parameters ----------------------- `int Py_SetStandardStreamEncoding(const char *encoding, const char *errors)` This function should be called before [`Py_Initialize()`](#c.Py_Initialize "Py_Initialize"), if it is called at all. It specifies which encoding and error handling to use with standard IO, with the same meanings as in [`str.encode()`](../library/stdtypes#str.encode "str.encode"). It overrides [`PYTHONIOENCODING`](../using/cmdline#envvar-PYTHONIOENCODING) values, and allows embedding code to control IO encoding when the environment variable does not work. *encoding* and/or *errors* may be `NULL` to use [`PYTHONIOENCODING`](../using/cmdline#envvar-PYTHONIOENCODING) and/or default values (depending on other settings). Note that [`sys.stderr`](../library/sys#sys.stderr "sys.stderr") always uses the “backslashreplace” error handler, regardless of this (or any other) setting. If [`Py_FinalizeEx()`](#c.Py_FinalizeEx "Py_FinalizeEx") is called, this function will need to be called again in order to affect subsequent calls to [`Py_Initialize()`](#c.Py_Initialize "Py_Initialize"). Returns `0` if successful, a nonzero value on error (e.g. calling after the interpreter has already been initialized). New in version 3.4. `void Py_SetProgramName(const wchar_t *name)` This function should be called before [`Py_Initialize()`](#c.Py_Initialize "Py_Initialize") is called for the first time, if it is called at all. It tells the interpreter the value of the `argv[0]` argument to the `main()` function of the program (converted to wide characters). This is used by [`Py_GetPath()`](#c.Py_GetPath "Py_GetPath") and some other functions below to find the Python run-time libraries relative to the interpreter executable. The default value is `'python'`. The argument should point to a zero-terminated wide character string in static storage whose contents will not change for the duration of the program’s execution. No code in the Python interpreter will change the contents of this storage. Use [`Py_DecodeLocale()`](sys#c.Py_DecodeLocale "Py_DecodeLocale") to decode a bytes string to get a `wchar_*` string. `wchar* Py_GetProgramName()` Return the program name set with [`Py_SetProgramName()`](#c.Py_SetProgramName "Py_SetProgramName"), or the default. The returned string points into static storage; the caller should not modify its value. `wchar_t* Py_GetPrefix()` Return the *prefix* for installed platform-independent files. This is derived through a number of complicated rules from the program name set with [`Py_SetProgramName()`](#c.Py_SetProgramName "Py_SetProgramName") and some environment variables; for example, if the program name is `'/usr/local/bin/python'`, the prefix is `'/usr/local'`. The returned string points into static storage; the caller should not modify its value. This corresponds to the **prefix** variable in the top-level `Makefile` and the `--prefix` argument to the **configure** script at build time. The value is available to Python code as `sys.prefix`. It is only useful on Unix. See also the next function. `wchar_t* Py_GetExecPrefix()` Return the *exec-prefix* for installed platform-*dependent* files. This is derived through a number of complicated rules from the program name set with [`Py_SetProgramName()`](#c.Py_SetProgramName "Py_SetProgramName") and some environment variables; for example, if the program name is `'/usr/local/bin/python'`, the exec-prefix is `'/usr/local'`. The returned string points into static storage; the caller should not modify its value. This corresponds to the **exec\_prefix** variable in the top-level `Makefile` and the `--exec-prefix` argument to the **configure** script at build time. The value is available to Python code as `sys.exec_prefix`. It is only useful on Unix. Background: The exec-prefix differs from the prefix when platform dependent files (such as executables and shared libraries) are installed in a different directory tree. In a typical installation, platform dependent files may be installed in the `/usr/local/plat` subtree while platform independent may be installed in `/usr/local`. Generally speaking, a platform is a combination of hardware and software families, e.g. Sparc machines running the Solaris 2.x operating system are considered the same platform, but Intel machines running Solaris 2.x are another platform, and Intel machines running Linux are yet another platform. Different major revisions of the same operating system generally also form different platforms. Non-Unix operating systems are a different story; the installation strategies on those systems are so different that the prefix and exec-prefix are meaningless, and set to the empty string. Note that compiled Python bytecode files are platform independent (but not independent from the Python version by which they were compiled!). System administrators will know how to configure the **mount** or **automount** programs to share `/usr/local` between platforms while having `/usr/local/plat` be a different filesystem for each platform. `wchar_t* Py_GetProgramFullPath()` Return the full program name of the Python executable; this is computed as a side-effect of deriving the default module search path from the program name (set by [`Py_SetProgramName()`](#c.Py_SetProgramName "Py_SetProgramName") above). The returned string points into static storage; the caller should not modify its value. The value is available to Python code as `sys.executable`. `wchar_t* Py_GetPath()` Return the default module search path; this is computed from the program name (set by [`Py_SetProgramName()`](#c.Py_SetProgramName "Py_SetProgramName") above) and some environment variables. The returned string consists of a series of directory names separated by a platform dependent delimiter character. The delimiter character is `':'` on Unix and macOS, `';'` on Windows. The returned string points into static storage; the caller should not modify its value. The list [`sys.path`](../library/sys#sys.path "sys.path") is initialized with this value on interpreter startup; it can be (and usually is) modified later to change the search path for loading modules. `void Py_SetPath(const wchar_t *)` Set the default module search path. If this function is called before [`Py_Initialize()`](#c.Py_Initialize "Py_Initialize"), then [`Py_GetPath()`](#c.Py_GetPath "Py_GetPath") won’t attempt to compute a default search path but uses the one provided instead. This is useful if Python is embedded by an application that has full knowledge of the location of all modules. The path components should be separated by the platform dependent delimiter character, which is `':'` on Unix and macOS, `';'` on Windows. This also causes [`sys.executable`](../library/sys#sys.executable "sys.executable") to be set to the program full path (see [`Py_GetProgramFullPath()`](#c.Py_GetProgramFullPath "Py_GetProgramFullPath")) and for [`sys.prefix`](../library/sys#sys.prefix "sys.prefix") and [`sys.exec_prefix`](../library/sys#sys.exec_prefix "sys.exec_prefix") to be empty. It is up to the caller to modify these if required after calling [`Py_Initialize()`](#c.Py_Initialize "Py_Initialize"). Use [`Py_DecodeLocale()`](sys#c.Py_DecodeLocale "Py_DecodeLocale") to decode a bytes string to get a `wchar_*` string. The path argument is copied internally, so the caller may free it after the call completes. Changed in version 3.8: The program full path is now used for [`sys.executable`](../library/sys#sys.executable "sys.executable"), instead of the program name. `const char* Py_GetVersion()` Return the version of this Python interpreter. This is a string that looks something like ``` "3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]" ``` The first word (up to the first space character) is the current Python version; the first characters are the major and minor version separated by a period. The returned string points into static storage; the caller should not modify its value. The value is available to Python code as [`sys.version`](../library/sys#sys.version "sys.version"). `const char* Py_GetPlatform()` Return the platform identifier for the current platform. On Unix, this is formed from the “official” name of the operating system, converted to lower case, followed by the major revision number; e.g., for Solaris 2.x, which is also known as SunOS 5.x, the value is `'sunos5'`. On macOS, it is `'darwin'`. On Windows, it is `'win'`. The returned string points into static storage; the caller should not modify its value. The value is available to Python code as `sys.platform`. `const char* Py_GetCopyright()` Return the official copyright string for the current Python version, for example `'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'` The returned string points into static storage; the caller should not modify its value. The value is available to Python code as `sys.copyright`. `const char* Py_GetCompiler()` Return an indication of the compiler used to build the current Python version, in square brackets, for example: ``` "[GCC 2.7.2.2]" ``` The returned string points into static storage; the caller should not modify its value. The value is available to Python code as part of the variable `sys.version`. `const char* Py_GetBuildInfo()` Return information about the sequence number and build date and time of the current Python interpreter instance, for example ``` "#67, Aug 1 1997, 22:34:28" ``` The returned string points into static storage; the caller should not modify its value. The value is available to Python code as part of the variable `sys.version`. `void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)` Set [`sys.argv`](../library/sys#sys.argv "sys.argv") based on *argc* and *argv*. These parameters are similar to those passed to the program’s `main()` function with the difference that the first entry should refer to the script file to be executed rather than the executable hosting the Python interpreter. If there isn’t a script that will be run, the first entry in *argv* can be an empty string. If this function fails to initialize [`sys.argv`](../library/sys#sys.argv "sys.argv"), a fatal condition is signalled using [`Py_FatalError()`](sys#c.Py_FatalError "Py_FatalError"). If *updatepath* is zero, this is all the function does. If *updatepath* is non-zero, the function also modifies [`sys.path`](../library/sys#sys.path "sys.path") according to the following algorithm: * If the name of an existing script is passed in `argv[0]`, the absolute path of the directory where the script is located is prepended to [`sys.path`](../library/sys#sys.path "sys.path"). * Otherwise (that is, if *argc* is `0` or `argv[0]` doesn’t point to an existing file name), an empty string is prepended to [`sys.path`](../library/sys#sys.path "sys.path"), which is the same as prepending the current working directory (`"."`). Use [`Py_DecodeLocale()`](sys#c.Py_DecodeLocale "Py_DecodeLocale") to decode a bytes string to get a `wchar_*` string. Note It is recommended that applications embedding the Python interpreter for purposes other than executing a single script pass `0` as *updatepath*, and update [`sys.path`](../library/sys#sys.path "sys.path") themselves if desired. See [CVE-2008-5983](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983). On versions before 3.1.3, you can achieve the same effect by manually popping the first [`sys.path`](../library/sys#sys.path "sys.path") element after having called [`PySys_SetArgv()`](#c.PySys_SetArgv "PySys_SetArgv"), for example using: ``` PyRun_SimpleString("import sys; sys.path.pop(0)\n"); ``` New in version 3.1.3. `void PySys_SetArgv(int argc, wchar_t **argv)` This function works like [`PySys_SetArgvEx()`](#c.PySys_SetArgvEx "PySys_SetArgvEx") with *updatepath* set to `1` unless the **python** interpreter was started with the [`-I`](../using/cmdline#id2). Use [`Py_DecodeLocale()`](sys#c.Py_DecodeLocale "Py_DecodeLocale") to decode a bytes string to get a `wchar_*` string. Changed in version 3.4: The *updatepath* value depends on [`-I`](../using/cmdline#id2). `void Py_SetPythonHome(const wchar_t *home)` Set the default “home” directory, that is, the location of the standard Python libraries. See [`PYTHONHOME`](../using/cmdline#envvar-PYTHONHOME) for the meaning of the argument string. The argument should point to a zero-terminated character string in static storage whose contents will not change for the duration of the program’s execution. No code in the Python interpreter will change the contents of this storage. Use [`Py_DecodeLocale()`](sys#c.Py_DecodeLocale "Py_DecodeLocale") to decode a bytes string to get a `wchar_*` string. `w_char* Py_GetPythonHome()` Return the default “home”, that is, the value set by a previous call to [`Py_SetPythonHome()`](#c.Py_SetPythonHome "Py_SetPythonHome"), or the value of the [`PYTHONHOME`](../using/cmdline#envvar-PYTHONHOME) environment variable if it is set. Thread State and the Global Interpreter Lock -------------------------------------------- The Python interpreter is not fully thread-safe. In order to support multi-threaded Python programs, there’s a global lock, called the [global interpreter lock](../glossary#term-global-interpreter-lock) or [GIL](../glossary#term-gil), that must be held by the current thread before it can safely access Python objects. Without the lock, even the simplest operations could cause problems in a multi-threaded program: for example, when two threads simultaneously increment the reference count of the same object, the reference count could end up being incremented only once instead of twice. Therefore, the rule exists that only the thread that has acquired the [GIL](../glossary#term-gil) may operate on Python objects or call Python/C API functions. In order to emulate concurrency of execution, the interpreter regularly tries to switch threads (see [`sys.setswitchinterval()`](../library/sys#sys.setswitchinterval "sys.setswitchinterval")). The lock is also released around potentially blocking I/O operations like reading or writing a file, so that other Python threads can run in the meantime. The Python interpreter keeps some thread-specific bookkeeping information inside a data structure called [`PyThreadState`](#c.PyThreadState "PyThreadState"). There’s also one global variable pointing to the current [`PyThreadState`](#c.PyThreadState "PyThreadState"): it can be retrieved using [`PyThreadState_Get()`](#c.PyThreadState_Get "PyThreadState_Get"). ### Releasing the GIL from extension code Most extension code manipulating the [GIL](../glossary#term-gil) has the following simple structure: ``` Save the thread state in a local variable. Release the global interpreter lock. ... Do some blocking I/O operation ... Reacquire the global interpreter lock. Restore the thread state from the local variable. ``` This is so common that a pair of macros exists to simplify it: ``` Py_BEGIN_ALLOW_THREADS ... Do some blocking I/O operation ... Py_END_ALLOW_THREADS ``` The [`Py_BEGIN_ALLOW_THREADS`](#c.Py_BEGIN_ALLOW_THREADS "Py_BEGIN_ALLOW_THREADS") macro opens a new block and declares a hidden local variable; the [`Py_END_ALLOW_THREADS`](#c.Py_END_ALLOW_THREADS "Py_END_ALLOW_THREADS") macro closes the block. The block above expands to the following code: ``` PyThreadState *_save; _save = PyEval_SaveThread(); ... Do some blocking I/O operation ... PyEval_RestoreThread(_save); ``` Here is how these functions work: the global interpreter lock is used to protect the pointer to the current thread state. When releasing the lock and saving the thread state, the current thread state pointer must be retrieved before the lock is released (since another thread could immediately acquire the lock and store its own thread state in the global variable). Conversely, when acquiring the lock and restoring the thread state, the lock must be acquired before storing the thread state pointer. Note Calling system I/O functions is the most common use case for releasing the GIL, but it can also be useful before calling long-running computations which don’t need access to Python objects, such as compression or cryptographic functions operating over memory buffers. For example, the standard [`zlib`](../library/zlib#module-zlib "zlib: Low-level interface to compression and decompression routines compatible with gzip.") and [`hashlib`](../library/hashlib#module-hashlib "hashlib: Secure hash and message digest algorithms.") modules release the GIL when compressing or hashing data. ### Non-Python created threads When threads are created using the dedicated Python APIs (such as the [`threading`](../library/threading#module-threading "threading: Thread-based parallelism.") module), a thread state is automatically associated to them and the code showed above is therefore correct. However, when threads are created from C (for example by a third-party library with its own thread management), they don’t hold the GIL, nor is there a thread state structure for them. If you need to call Python code from these threads (often this will be part of a callback API provided by the aforementioned third-party library), you must first register these threads with the interpreter by creating a thread state data structure, then acquiring the GIL, and finally storing their thread state pointer, before you can start using the Python/C API. When you are done, you should reset the thread state pointer, release the GIL, and finally free the thread state data structure. The [`PyGILState_Ensure()`](#c.PyGILState_Ensure "PyGILState_Ensure") and [`PyGILState_Release()`](#c.PyGILState_Release "PyGILState_Release") functions do all of the above automatically. The typical idiom for calling into Python from a C thread is: ``` PyGILState_STATE gstate; gstate = PyGILState_Ensure(); /* Perform Python actions here. */ result = CallSomeFunction(); /* evaluate result or handle exception */ /* Release the thread. No Python API allowed beyond this point. */ PyGILState_Release(gstate); ``` Note that the `PyGILState_*()` functions assume there is only one global interpreter (created automatically by [`Py_Initialize()`](#c.Py_Initialize "Py_Initialize")). Python supports the creation of additional interpreters (using [`Py_NewInterpreter()`](#c.Py_NewInterpreter "Py_NewInterpreter")), but mixing multiple interpreters and the `PyGILState_*()` API is unsupported. ### Cautions about fork() Another important thing to note about threads is their behaviour in the face of the C `fork()` call. On most systems with `fork()`, after a process forks only the thread that issued the fork will exist. This has a concrete impact both on how locks must be handled and on all stored state in CPython’s runtime. The fact that only the “current” thread remains means any locks held by other threads will never be released. Python solves this for [`os.fork()`](../library/os#os.fork "os.fork") by acquiring the locks it uses internally before the fork, and releasing them afterwards. In addition, it resets any [Lock Objects](../library/threading#lock-objects) in the child. When extending or embedding Python, there is no way to inform Python of additional (non-Python) locks that need to be acquired before or reset after a fork. OS facilities such as `pthread_atfork()` would need to be used to accomplish the same thing. Additionally, when extending or embedding Python, calling `fork()` directly rather than through [`os.fork()`](../library/os#os.fork "os.fork") (and returning to or calling into Python) may result in a deadlock by one of Python’s internal locks being held by a thread that is defunct after the fork. [`PyOS_AfterFork_Child()`](sys#c.PyOS_AfterFork_Child "PyOS_AfterFork_Child") tries to reset the necessary locks, but is not always able to. The fact that all other threads go away also means that CPython’s runtime state there must be cleaned up properly, which [`os.fork()`](../library/os#os.fork "os.fork") does. This means finalizing all other [`PyThreadState`](#c.PyThreadState "PyThreadState") objects belonging to the current interpreter and all other [`PyInterpreterState`](#c.PyInterpreterState "PyInterpreterState") objects. Due to this and the special nature of the [“main” interpreter](#sub-interpreter-support), `fork()` should only be called in that interpreter’s “main” thread, where the CPython global runtime was originally initialized. The only exception is if `exec()` will be called immediately after. ### High-level API These are the most commonly used types and functions when writing C extension code, or when embedding the Python interpreter: `PyInterpreterState` This data structure represents the state shared by a number of cooperating threads. Threads belonging to the same interpreter share their module administration and a few other internal items. There are no public members in this structure. Threads belonging to different interpreters initially share nothing, except process state like available memory, open file descriptors and such. The global interpreter lock is also shared by all threads, regardless of to which interpreter they belong. `PyThreadState` This data structure represents the state of a single thread. The only public data member is `interp` ([`PyInterpreterState *`](#c.PyInterpreterState "PyInterpreterState")), which points to this thread’s interpreter state. `void PyEval_InitThreads()` Deprecated function which does nothing. In Python 3.6 and older, this function created the GIL if it didn’t exist. Changed in version 3.9: The function now does nothing. Changed in version 3.7: This function is now called by [`Py_Initialize()`](#c.Py_Initialize "Py_Initialize"), so you don’t have to call it yourself anymore. Changed in version 3.2: This function cannot be called before [`Py_Initialize()`](#c.Py_Initialize "Py_Initialize") anymore. Deprecated since version 3.9, will be removed in version 3.11. `int PyEval_ThreadsInitialized()` Returns a non-zero value if [`PyEval_InitThreads()`](#c.PyEval_InitThreads "PyEval_InitThreads") has been called. This function can be called without holding the GIL, and therefore can be used to avoid calls to the locking API when running single-threaded. Changed in version 3.7: The [GIL](../glossary#term-gil) is now initialized by [`Py_Initialize()`](#c.Py_Initialize "Py_Initialize"). Deprecated since version 3.9, will be removed in version 3.11. `PyThreadState* PyEval_SaveThread()` Release the global interpreter lock (if it has been created) and reset the thread state to `NULL`, returning the previous thread state (which is not `NULL`). If the lock has been created, the current thread must have acquired it. `void PyEval_RestoreThread(PyThreadState *tstate)` Acquire the global interpreter lock (if it has been created) and set the thread state to *tstate*, which must not be `NULL`. If the lock has been created, the current thread must not have acquired it, otherwise deadlock ensues. Note Calling this function from a thread when the runtime is finalizing will terminate the thread, even if the thread was not created by Python. You can use `_Py_IsFinalizing()` or [`sys.is_finalizing()`](../library/sys#sys.is_finalizing "sys.is_finalizing") to check if the interpreter is in process of being finalized before calling this function to avoid unwanted termination. `PyThreadState* PyThreadState_Get()` Return the current thread state. The global interpreter lock must be held. When the current thread state is `NULL`, this issues a fatal error (so that the caller needn’t check for `NULL`). `PyThreadState* PyThreadState_Swap(PyThreadState *tstate)` Swap the current thread state with the thread state given by the argument *tstate*, which may be `NULL`. The global interpreter lock must be held and is not released. The following functions use thread-local storage, and are not compatible with sub-interpreters: `PyGILState_STATE PyGILState_Ensure()` Ensure that the current thread is ready to call the Python C API regardless of the current state of Python, or of the global interpreter lock. This may be called as many times as desired by a thread as long as each call is matched with a call to [`PyGILState_Release()`](#c.PyGILState_Release "PyGILState_Release"). In general, other thread-related APIs may be used between [`PyGILState_Ensure()`](#c.PyGILState_Ensure "PyGILState_Ensure") and [`PyGILState_Release()`](#c.PyGILState_Release "PyGILState_Release") calls as long as the thread state is restored to its previous state before the Release(). For example, normal usage of the [`Py_BEGIN_ALLOW_THREADS`](#c.Py_BEGIN_ALLOW_THREADS "Py_BEGIN_ALLOW_THREADS") and [`Py_END_ALLOW_THREADS`](#c.Py_END_ALLOW_THREADS "Py_END_ALLOW_THREADS") macros is acceptable. The return value is an opaque “handle” to the thread state when [`PyGILState_Ensure()`](#c.PyGILState_Ensure "PyGILState_Ensure") was called, and must be passed to [`PyGILState_Release()`](#c.PyGILState_Release "PyGILState_Release") to ensure Python is left in the same state. Even though recursive calls are allowed, these handles *cannot* be shared - each unique call to [`PyGILState_Ensure()`](#c.PyGILState_Ensure "PyGILState_Ensure") must save the handle for its call to [`PyGILState_Release()`](#c.PyGILState_Release "PyGILState_Release"). When the function returns, the current thread will hold the GIL and be able to call arbitrary Python code. Failure is a fatal error. Note Calling this function from a thread when the runtime is finalizing will terminate the thread, even if the thread was not created by Python. You can use `_Py_IsFinalizing()` or [`sys.is_finalizing()`](../library/sys#sys.is_finalizing "sys.is_finalizing") to check if the interpreter is in process of being finalized before calling this function to avoid unwanted termination. `void PyGILState_Release(PyGILState_STATE)` Release any resources previously acquired. After this call, Python’s state will be the same as it was prior to the corresponding [`PyGILState_Ensure()`](#c.PyGILState_Ensure "PyGILState_Ensure") call (but generally this state will be unknown to the caller, hence the use of the GILState API). Every call to [`PyGILState_Ensure()`](#c.PyGILState_Ensure "PyGILState_Ensure") must be matched by a call to [`PyGILState_Release()`](#c.PyGILState_Release "PyGILState_Release") on the same thread. `PyThreadState* PyGILState_GetThisThreadState()` Get the current thread state for this thread. May return `NULL` if no GILState API has been used on the current thread. Note that the main thread always has such a thread-state, even if no auto-thread-state call has been made on the main thread. This is mainly a helper/diagnostic function. `int PyGILState_Check()` Return `1` if the current thread is holding the GIL and `0` otherwise. This function can be called from any thread at any time. Only if it has had its Python thread state initialized and currently is holding the GIL will it return `1`. This is mainly a helper/diagnostic function. It can be useful for example in callback contexts or memory allocation functions when knowing that the GIL is locked can allow the caller to perform sensitive actions or otherwise behave differently. New in version 3.4. The following macros are normally used without a trailing semicolon; look for example usage in the Python source distribution. `Py_BEGIN_ALLOW_THREADS` This macro expands to `{ PyThreadState *_save; _save = PyEval_SaveThread();`. Note that it contains an opening brace; it must be matched with a following [`Py_END_ALLOW_THREADS`](#c.Py_END_ALLOW_THREADS "Py_END_ALLOW_THREADS") macro. See above for further discussion of this macro. `Py_END_ALLOW_THREADS` This macro expands to `PyEval_RestoreThread(_save); }`. Note that it contains a closing brace; it must be matched with an earlier [`Py_BEGIN_ALLOW_THREADS`](#c.Py_BEGIN_ALLOW_THREADS "Py_BEGIN_ALLOW_THREADS") macro. See above for further discussion of this macro. `Py_BLOCK_THREADS` This macro expands to `PyEval_RestoreThread(_save);`: it is equivalent to [`Py_END_ALLOW_THREADS`](#c.Py_END_ALLOW_THREADS "Py_END_ALLOW_THREADS") without the closing brace. `Py_UNBLOCK_THREADS` This macro expands to `_save = PyEval_SaveThread();`: it is equivalent to [`Py_BEGIN_ALLOW_THREADS`](#c.Py_BEGIN_ALLOW_THREADS "Py_BEGIN_ALLOW_THREADS") without the opening brace and variable declaration. ### Low-level API All of the following functions must be called after [`Py_Initialize()`](#c.Py_Initialize "Py_Initialize"). Changed in version 3.7: [`Py_Initialize()`](#c.Py_Initialize "Py_Initialize") now initializes the [GIL](../glossary#term-gil). `PyInterpreterState* PyInterpreterState_New()` Create a new interpreter state object. The global interpreter lock need not be held, but may be held if it is necessary to serialize calls to this function. Raises an [auditing event](../library/sys#auditing) `cpython.PyInterpreterState_New` with no arguments. `void PyInterpreterState_Clear(PyInterpreterState *interp)` Reset all information in an interpreter state object. The global interpreter lock must be held. Raises an [auditing event](../library/sys#auditing) `cpython.PyInterpreterState_Clear` with no arguments. `void PyInterpreterState_Delete(PyInterpreterState *interp)` Destroy an interpreter state object. The global interpreter lock need not be held. The interpreter state must have been reset with a previous call to [`PyInterpreterState_Clear()`](#c.PyInterpreterState_Clear "PyInterpreterState_Clear"). `PyThreadState* PyThreadState_New(PyInterpreterState *interp)` Create a new thread state object belonging to the given interpreter object. The global interpreter lock need not be held, but may be held if it is necessary to serialize calls to this function. `void PyThreadState_Clear(PyThreadState *tstate)` Reset all information in a thread state object. The global interpreter lock must be held. Changed in version 3.9: This function now calls the `PyThreadState.on_delete` callback. Previously, that happened in [`PyThreadState_Delete()`](#c.PyThreadState_Delete "PyThreadState_Delete"). `void PyThreadState_Delete(PyThreadState *tstate)` Destroy a thread state object. The global interpreter lock need not be held. The thread state must have been reset with a previous call to [`PyThreadState_Clear()`](#c.PyThreadState_Clear "PyThreadState_Clear"). `void PyThreadState_DeleteCurrent(void)` Destroy the current thread state and release the global interpreter lock. Like [`PyThreadState_Delete()`](#c.PyThreadState_Delete "PyThreadState_Delete"), the global interpreter lock need not be held. The thread state must have been reset with a previous call to [`PyThreadState_Clear()`](#c.PyThreadState_Clear "PyThreadState_Clear"). `PyFrameObject* PyThreadState_GetFrame(PyThreadState *tstate)` Get the current frame of the Python thread state *tstate*. Return a strong reference. Return `NULL` if no frame is currently executing. See also [`PyEval_GetFrame()`](reflection#c.PyEval_GetFrame "PyEval_GetFrame"). *tstate* must not be `NULL`. New in version 3.9. `uint64_t PyThreadState_GetID(PyThreadState *tstate)` Get the unique thread state identifier of the Python thread state *tstate*. *tstate* must not be `NULL`. New in version 3.9. `PyInterpreterState* PyThreadState_GetInterpreter(PyThreadState *tstate)` Get the interpreter of the Python thread state *tstate*. *tstate* must not be `NULL`. New in version 3.9. `PyInterpreterState* PyInterpreterState_Get(void)` Get the current interpreter. Issue a fatal error if there no current Python thread state or no current interpreter. It cannot return NULL. The caller must hold the GIL. New in version 3.9. `int64_t PyInterpreterState_GetID(PyInterpreterState *interp)` Return the interpreter’s unique ID. If there was any error in doing so then `-1` is returned and an error is set. The caller must hold the GIL. New in version 3.7. `PyObject* PyInterpreterState_GetDict(PyInterpreterState *interp)` Return a dictionary in which interpreter-specific data may be stored. If this function returns `NULL` then no exception has been raised and the caller should assume no interpreter-specific dict is available. This is not a replacement for [`PyModule_GetState()`](module#c.PyModule_GetState "PyModule_GetState"), which extensions should use to store interpreter-specific state information. New in version 3.8. `PyObject* (*_PyFrameEvalFunction)(PyThreadState *tstate, PyFrameObject *frame, int throwflag)` Type of a frame evaluation function. The *throwflag* parameter is used by the `throw()` method of generators: if non-zero, handle the current exception. Changed in version 3.9: The function now takes a *tstate* parameter. `_PyFrameEvalFunction _PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)` Get the frame evaluation function. See the [**PEP 523**](https://www.python.org/dev/peps/pep-0523) “Adding a frame evaluation API to CPython”. New in version 3.9. `void _PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp, _PyFrameEvalFunction eval_frame)` Set the frame evaluation function. See the [**PEP 523**](https://www.python.org/dev/peps/pep-0523) “Adding a frame evaluation API to CPython”. New in version 3.9. `PyObject* PyThreadState_GetDict()` *Return value: Borrowed reference.*Return a dictionary in which extensions can store thread-specific state information. Each extension should use a unique key to use to store state in the dictionary. It is okay to call this function when no current thread state is available. If this function returns `NULL`, no exception has been raised and the caller should assume no current thread state is available. `int PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)` Asynchronously raise an exception in a thread. The *id* argument is the thread id of the target thread; *exc* is the exception object to be raised. This function does not steal any references to *exc*. To prevent naive misuse, you must write your own C extension to call this. Must be called with the GIL held. Returns the number of thread states modified; this is normally one, but will be zero if the thread id isn’t found. If *exc* is `NULL`, the pending exception (if any) for the thread is cleared. This raises no exceptions. Changed in version 3.7: The type of the *id* parameter changed from `long` to `unsigned long`. `void PyEval_AcquireThread(PyThreadState *tstate)` Acquire the global interpreter lock and set the current thread state to *tstate*, which must not be `NULL`. The lock must have been created earlier. If this thread already has the lock, deadlock ensues. Note Calling this function from a thread when the runtime is finalizing will terminate the thread, even if the thread was not created by Python. You can use `_Py_IsFinalizing()` or [`sys.is_finalizing()`](../library/sys#sys.is_finalizing "sys.is_finalizing") to check if the interpreter is in process of being finalized before calling this function to avoid unwanted termination. Changed in version 3.8: Updated to be consistent with [`PyEval_RestoreThread()`](#c.PyEval_RestoreThread "PyEval_RestoreThread"), [`Py_END_ALLOW_THREADS()`](#c.Py_END_ALLOW_THREADS "Py_END_ALLOW_THREADS"), and [`PyGILState_Ensure()`](#c.PyGILState_Ensure "PyGILState_Ensure"), and terminate the current thread if called while the interpreter is finalizing. [`PyEval_RestoreThread()`](#c.PyEval_RestoreThread "PyEval_RestoreThread") is a higher-level function which is always available (even when threads have not been initialized). `void PyEval_ReleaseThread(PyThreadState *tstate)` Reset the current thread state to `NULL` and release the global interpreter lock. The lock must have been created earlier and must be held by the current thread. The *tstate* argument, which must not be `NULL`, is only used to check that it represents the current thread state — if it isn’t, a fatal error is reported. [`PyEval_SaveThread()`](#c.PyEval_SaveThread "PyEval_SaveThread") is a higher-level function which is always available (even when threads have not been initialized). `void PyEval_AcquireLock()` Acquire the global interpreter lock. The lock must have been created earlier. If this thread already has the lock, a deadlock ensues. Deprecated since version 3.2: This function does not update the current thread state. Please use [`PyEval_RestoreThread()`](#c.PyEval_RestoreThread "PyEval_RestoreThread") or [`PyEval_AcquireThread()`](#c.PyEval_AcquireThread "PyEval_AcquireThread") instead. Note Calling this function from a thread when the runtime is finalizing will terminate the thread, even if the thread was not created by Python. You can use `_Py_IsFinalizing()` or [`sys.is_finalizing()`](../library/sys#sys.is_finalizing "sys.is_finalizing") to check if the interpreter is in process of being finalized before calling this function to avoid unwanted termination. Changed in version 3.8: Updated to be consistent with [`PyEval_RestoreThread()`](#c.PyEval_RestoreThread "PyEval_RestoreThread"), [`Py_END_ALLOW_THREADS()`](#c.Py_END_ALLOW_THREADS "Py_END_ALLOW_THREADS"), and [`PyGILState_Ensure()`](#c.PyGILState_Ensure "PyGILState_Ensure"), and terminate the current thread if called while the interpreter is finalizing. `void PyEval_ReleaseLock()` Release the global interpreter lock. The lock must have been created earlier. Deprecated since version 3.2: This function does not update the current thread state. Please use [`PyEval_SaveThread()`](#c.PyEval_SaveThread "PyEval_SaveThread") or [`PyEval_ReleaseThread()`](#c.PyEval_ReleaseThread "PyEval_ReleaseThread") instead. Sub-interpreter support ----------------------- While in most uses, you will only embed a single Python interpreter, there are cases where you need to create several independent interpreters in the same process and perhaps even in the same thread. Sub-interpreters allow you to do that. The “main” interpreter is the first one created when the runtime initializes. It is usually the only Python interpreter in a process. Unlike sub-interpreters, the main interpreter has unique process-global responsibilities like signal handling. It is also responsible for execution during runtime initialization and is usually the active interpreter during runtime finalization. The [`PyInterpreterState_Main()`](#c.PyInterpreterState_Main "PyInterpreterState_Main") function returns a pointer to its state. You can switch between sub-interpreters using the [`PyThreadState_Swap()`](#c.PyThreadState_Swap "PyThreadState_Swap") function. You can create and destroy them using the following functions: `PyThreadState* Py_NewInterpreter()` Create a new sub-interpreter. This is an (almost) totally separate environment for the execution of Python code. In particular, the new interpreter has separate, independent versions of all imported modules, including the fundamental modules [`builtins`](../library/builtins#module-builtins "builtins: The module that provides the built-in namespace."), [`__main__`](../library/__main__#module-__main__ "__main__: The environment where the top-level script is run.") and [`sys`](../library/sys#module-sys "sys: Access system-specific parameters and functions."). The table of loaded modules (`sys.modules`) and the module search path (`sys.path`) are also separate. The new environment has no `sys.argv` variable. It has new standard I/O stream file objects `sys.stdin`, `sys.stdout` and `sys.stderr` (however these refer to the same underlying file descriptors). The return value points to the first thread state created in the new sub-interpreter. This thread state is made in the current thread state. Note that no actual thread is created; see the discussion of thread states below. If creation of the new interpreter is unsuccessful, `NULL` is returned; no exception is set since the exception state is stored in the current thread state and there may not be a current thread state. (Like all other Python/C API functions, the global interpreter lock must be held before calling this function and is still held when it returns; however, unlike most other Python/C API functions, there needn’t be a current thread state on entry.) Extension modules are shared between (sub-)interpreters as follows: * For modules using multi-phase initialization, e.g. [`PyModule_FromDefAndSpec()`](module#c.PyModule_FromDefAndSpec "PyModule_FromDefAndSpec"), a separate module object is created and initialized for each interpreter. Only C-level static and global variables are shared between these module objects. * For modules using single-phase initialization, e.g. [`PyModule_Create()`](module#c.PyModule_Create "PyModule_Create"), the first time a particular extension is imported, it is initialized normally, and a (shallow) copy of its module’s dictionary is squirreled away. When the same extension is imported by another (sub-)interpreter, a new module is initialized and filled with the contents of this copy; the extension’s `init` function is not called. Objects in the module’s dictionary thus end up shared across (sub-)interpreters, which might cause unwanted behavior (see [Bugs and caveats](#bugs-and-caveats) below). Note that this is different from what happens when an extension is imported after the interpreter has been completely re-initialized by calling [`Py_FinalizeEx()`](#c.Py_FinalizeEx "Py_FinalizeEx") and [`Py_Initialize()`](#c.Py_Initialize "Py_Initialize"); in that case, the extension’s `initmodule` function *is* called again. As with multi-phase initialization, this means that only C-level static and global variables are shared between these modules. `void Py_EndInterpreter(PyThreadState *tstate)` Destroy the (sub-)interpreter represented by the given thread state. The given thread state must be the current thread state. See the discussion of thread states below. When the call returns, the current thread state is `NULL`. All thread states associated with this interpreter are destroyed. (The global interpreter lock must be held before calling this function and is still held when it returns.) [`Py_FinalizeEx()`](#c.Py_FinalizeEx "Py_FinalizeEx") will destroy all sub-interpreters that haven’t been explicitly destroyed at that point. ### Bugs and caveats Because sub-interpreters (and the main interpreter) are part of the same process, the insulation between them isn’t perfect — for example, using low-level file operations like [`os.close()`](../library/os#os.close "os.close") they can (accidentally or maliciously) affect each other’s open files. Because of the way extensions are shared between (sub-)interpreters, some extensions may not work properly; this is especially likely when using single-phase initialization or (static) global variables. It is possible to insert objects created in one sub-interpreter into a namespace of another (sub-)interpreter; this should be avoided if possible. Special care should be taken to avoid sharing user-defined functions, methods, instances or classes between sub-interpreters, since import operations executed by such objects may affect the wrong (sub-)interpreter’s dictionary of loaded modules. It is equally important to avoid sharing objects from which the above are reachable. Also note that combining this functionality with `PyGILState_*()` APIs is delicate, because these APIs assume a bijection between Python thread states and OS-level threads, an assumption broken by the presence of sub-interpreters. It is highly recommended that you don’t switch sub-interpreters between a pair of matching [`PyGILState_Ensure()`](#c.PyGILState_Ensure "PyGILState_Ensure") and [`PyGILState_Release()`](#c.PyGILState_Release "PyGILState_Release") calls. Furthermore, extensions (such as [`ctypes`](../library/ctypes#module-ctypes "ctypes: A foreign function library for Python.")) using these APIs to allow calling of Python code from non-Python created threads will probably be broken when using sub-interpreters. Asynchronous Notifications -------------------------- A mechanism is provided to make asynchronous notifications to the main interpreter thread. These notifications take the form of a function pointer and a void pointer argument. `int Py_AddPendingCall(int (*func)(void *), void *arg)` Schedule a function to be called from the main interpreter thread. On success, `0` is returned and *func* is queued for being called in the main thread. On failure, `-1` is returned without setting any exception. When successfully queued, *func* will be *eventually* called from the main interpreter thread with the argument *arg*. It will be called asynchronously with respect to normally running Python code, but with both these conditions met: * on a [bytecode](../glossary#term-bytecode) boundary; * with the main thread holding the [global interpreter lock](../glossary#term-global-interpreter-lock) (*func* can therefore use the full C API). *func* must return `0` on success, or `-1` on failure with an exception set. *func* won’t be interrupted to perform another asynchronous notification recursively, but it can still be interrupted to switch threads if the global interpreter lock is released. This function doesn’t need a current thread state to run, and it doesn’t need the global interpreter lock. To call this function in a subinterpreter, the caller must hold the GIL. Otherwise, the function *func* can be scheduled to be called from the wrong interpreter. Warning This is a low-level function, only useful for very special cases. There is no guarantee that *func* will be called as quick as possible. If the main thread is busy executing a system call, *func* won’t be called before the system call returns. This function is generally **not** suitable for calling Python code from arbitrary C threads. Instead, use the [PyGILState API](#gilstate). Changed in version 3.9: If this function is called in a subinterpreter, the function *func* is now scheduled to be called from the subinterpreter, rather than being called from the main interpreter. Each subinterpreter now has its own list of scheduled calls. New in version 3.1. Profiling and Tracing --------------------- The Python interpreter provides some low-level support for attaching profiling and execution tracing facilities. These are used for profiling, debugging, and coverage analysis tools. This C interface allows the profiling or tracing code to avoid the overhead of calling through Python-level callable objects, making a direct C function call instead. The essential attributes of the facility have not changed; the interface allows trace functions to be installed per-thread, and the basic events reported to the trace function are the same as had been reported to the Python-level trace functions in previous versions. `int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg)` The type of the trace function registered using [`PyEval_SetProfile()`](#c.PyEval_SetProfile "PyEval_SetProfile") and [`PyEval_SetTrace()`](#c.PyEval_SetTrace "PyEval_SetTrace"). The first parameter is the object passed to the registration function as *obj*, *frame* is the frame object to which the event pertains, *what* is one of the constants `PyTrace_CALL`, `PyTrace_EXCEPTION`, `PyTrace_LINE`, `PyTrace_RETURN`, `PyTrace_C_CALL`, `PyTrace_C_EXCEPTION`, `PyTrace_C_RETURN`, or `PyTrace_OPCODE`, and *arg* depends on the value of *what*: | Value of *what* | Meaning of *arg* | | --- | --- | | `PyTrace_CALL` | Always [`Py_None`](none#c.Py_None "Py_None"). | | `PyTrace_EXCEPTION` | Exception information as returned by [`sys.exc_info()`](../library/sys#sys.exc_info "sys.exc_info"). | | `PyTrace_LINE` | Always [`Py_None`](none#c.Py_None "Py_None"). | | `PyTrace_RETURN` | Value being returned to the caller, or `NULL` if caused by an exception. | | `PyTrace_C_CALL` | Function object being called. | | `PyTrace_C_EXCEPTION` | Function object being called. | | `PyTrace_C_RETURN` | Function object being called. | | `PyTrace_OPCODE` | Always [`Py_None`](none#c.Py_None "Py_None"). | `int PyTrace_CALL` The value of the *what* parameter to a [`Py_tracefunc`](#c.Py_tracefunc "Py_tracefunc") function when a new call to a function or method is being reported, or a new entry into a generator. Note that the creation of the iterator for a generator function is not reported as there is no control transfer to the Python bytecode in the corresponding frame. `int PyTrace_EXCEPTION` The value of the *what* parameter to a [`Py_tracefunc`](#c.Py_tracefunc "Py_tracefunc") function when an exception has been raised. The callback function is called with this value for *what* when after any bytecode is processed after which the exception becomes set within the frame being executed. The effect of this is that as exception propagation causes the Python stack to unwind, the callback is called upon return to each frame as the exception propagates. Only trace functions receives these events; they are not needed by the profiler. `int PyTrace_LINE` The value passed as the *what* parameter to a [`Py_tracefunc`](#c.Py_tracefunc "Py_tracefunc") function (but not a profiling function) when a line-number event is being reported. It may be disabled for a frame by setting `f_trace_lines` to *0* on that frame. `int PyTrace_RETURN` The value for the *what* parameter to [`Py_tracefunc`](#c.Py_tracefunc "Py_tracefunc") functions when a call is about to return. `int PyTrace_C_CALL` The value for the *what* parameter to [`Py_tracefunc`](#c.Py_tracefunc "Py_tracefunc") functions when a C function is about to be called. `int PyTrace_C_EXCEPTION` The value for the *what* parameter to [`Py_tracefunc`](#c.Py_tracefunc "Py_tracefunc") functions when a C function has raised an exception. `int PyTrace_C_RETURN` The value for the *what* parameter to [`Py_tracefunc`](#c.Py_tracefunc "Py_tracefunc") functions when a C function has returned. `int PyTrace_OPCODE` The value for the *what* parameter to [`Py_tracefunc`](#c.Py_tracefunc "Py_tracefunc") functions (but not profiling functions) when a new opcode is about to be executed. This event is not emitted by default: it must be explicitly requested by setting `f_trace_opcodes` to *1* on the frame. `void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)` Set the profiler function to *func*. The *obj* parameter is passed to the function as its first parameter, and may be any Python object, or `NULL`. If the profile function needs to maintain state, using a different value for *obj* for each thread provides a convenient and thread-safe place to store it. The profile function is called for all monitored events except `PyTrace_LINE` `PyTrace_OPCODE` and `PyTrace_EXCEPTION`. The caller must hold the [GIL](../glossary#term-gil). `void PyEval_SetTrace(Py_tracefunc func, PyObject *obj)` Set the tracing function to *func*. This is similar to [`PyEval_SetProfile()`](#c.PyEval_SetProfile "PyEval_SetProfile"), except the tracing function does receive line-number events and per-opcode events, but does not receive any event related to C function objects being called. Any trace function registered using [`PyEval_SetTrace()`](#c.PyEval_SetTrace "PyEval_SetTrace") will not receive `PyTrace_C_CALL`, `PyTrace_C_EXCEPTION` or `PyTrace_C_RETURN` as a value for the *what* parameter. The caller must hold the [GIL](../glossary#term-gil). Advanced Debugger Support ------------------------- These functions are only intended to be used by advanced debugging tools. `PyInterpreterState* PyInterpreterState_Head()` Return the interpreter state object at the head of the list of all such objects. `PyInterpreterState* PyInterpreterState_Main()` Return the main interpreter state object. `PyInterpreterState* PyInterpreterState_Next(PyInterpreterState *interp)` Return the next interpreter state object after *interp* from the list of all such objects. `PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp)` Return the pointer to the first [`PyThreadState`](#c.PyThreadState "PyThreadState") object in the list of threads associated with the interpreter *interp*. `PyThreadState* PyThreadState_Next(PyThreadState *tstate)` Return the next thread state object after *tstate* from the list of all such objects belonging to the same [`PyInterpreterState`](#c.PyInterpreterState "PyInterpreterState") object. Thread Local Storage Support ---------------------------- The Python interpreter provides low-level support for thread-local storage (TLS) which wraps the underlying native TLS implementation to support the Python-level thread local storage API ([`threading.local`](../library/threading#threading.local "threading.local")). The CPython C level APIs are similar to those offered by pthreads and Windows: use a thread key and functions to associate a `void*` value per thread. The GIL does *not* need to be held when calling these functions; they supply their own locking. Note that `Python.h` does not include the declaration of the TLS APIs, you need to include `pythread.h` to use thread-local storage. Note None of these API functions handle memory management on behalf of the `void*` values. You need to allocate and deallocate them yourself. If the `void*` values happen to be [`PyObject*`](structures#c.PyObject "PyObject"), these functions don’t do refcount operations on them either. ### Thread Specific Storage (TSS) API TSS API is introduced to supersede the use of the existing TLS API within the CPython interpreter. This API uses a new type [`Py_tss_t`](#c.Py_tss_t "Py_tss_t") instead of `int` to represent thread keys. New in version 3.7. See also “A New C-API for Thread-Local Storage in CPython” ([**PEP 539**](https://www.python.org/dev/peps/pep-0539)) `Py_tss_t` This data structure represents the state of a thread key, the definition of which may depend on the underlying TLS implementation, and it has an internal field representing the key’s initialization state. There are no public members in this structure. When [Py\_LIMITED\_API](stable#stable) is not defined, static allocation of this type by [`Py_tss_NEEDS_INIT`](#c.Py_tss_NEEDS_INIT "Py_tss_NEEDS_INIT") is allowed. `Py_tss_NEEDS_INIT` This macro expands to the initializer for [`Py_tss_t`](#c.Py_tss_t "Py_tss_t") variables. Note that this macro won’t be defined with [Py\_LIMITED\_API](stable#stable). #### Dynamic Allocation Dynamic allocation of the [`Py_tss_t`](#c.Py_tss_t "Py_tss_t"), required in extension modules built with [Py\_LIMITED\_API](stable#stable), where static allocation of this type is not possible due to its implementation being opaque at build time. `Py_tss_t* PyThread_tss_alloc()` Return a value which is the same state as a value initialized with [`Py_tss_NEEDS_INIT`](#c.Py_tss_NEEDS_INIT "Py_tss_NEEDS_INIT"), or `NULL` in the case of dynamic allocation failure. `void PyThread_tss_free(Py_tss_t *key)` Free the given *key* allocated by [`PyThread_tss_alloc()`](#c.PyThread_tss_alloc "PyThread_tss_alloc"), after first calling [`PyThread_tss_delete()`](#c.PyThread_tss_delete "PyThread_tss_delete") to ensure any associated thread locals have been unassigned. This is a no-op if the *key* argument is `NULL`. Note A freed key becomes a dangling pointer. You should reset the key to `NULL`. #### Methods The parameter *key* of these functions must not be `NULL`. Moreover, the behaviors of [`PyThread_tss_set()`](#c.PyThread_tss_set "PyThread_tss_set") and [`PyThread_tss_get()`](#c.PyThread_tss_get "PyThread_tss_get") are undefined if the given [`Py_tss_t`](#c.Py_tss_t "Py_tss_t") has not been initialized by [`PyThread_tss_create()`](#c.PyThread_tss_create "PyThread_tss_create"). `int PyThread_tss_is_created(Py_tss_t *key)` Return a non-zero value if the given [`Py_tss_t`](#c.Py_tss_t "Py_tss_t") has been initialized by [`PyThread_tss_create()`](#c.PyThread_tss_create "PyThread_tss_create"). `int PyThread_tss_create(Py_tss_t *key)` Return a zero value on successful initialization of a TSS key. The behavior is undefined if the value pointed to by the *key* argument is not initialized by [`Py_tss_NEEDS_INIT`](#c.Py_tss_NEEDS_INIT "Py_tss_NEEDS_INIT"). This function can be called repeatedly on the same key – calling it on an already initialized key is a no-op and immediately returns success. `void PyThread_tss_delete(Py_tss_t *key)` Destroy a TSS key to forget the values associated with the key across all threads, and change the key’s initialization state to uninitialized. A destroyed key is able to be initialized again by [`PyThread_tss_create()`](#c.PyThread_tss_create "PyThread_tss_create"). This function can be called repeatedly on the same key – calling it on an already destroyed key is a no-op. `int PyThread_tss_set(Py_tss_t *key, void *value)` Return a zero value to indicate successfully associating a `void*` value with a TSS key in the current thread. Each thread has a distinct mapping of the key to a `void*` value. `void* PyThread_tss_get(Py_tss_t *key)` Return the `void*` value associated with a TSS key in the current thread. This returns `NULL` if no value is associated with the key in the current thread. ### Thread Local Storage (TLS) API Deprecated since version 3.7: This API is superseded by [Thread Specific Storage (TSS) API](#thread-specific-storage-api). Note This version of the API does not support platforms where the native TLS key is defined in a way that cannot be safely cast to `int`. On such platforms, [`PyThread_create_key()`](#c.PyThread_create_key "PyThread_create_key") will return immediately with a failure status, and the other TLS functions will all be no-ops on such platforms. Due to the compatibility problem noted above, this version of the API should not be used in new code. `int PyThread_create_key()` `void PyThread_delete_key(int key)` `int PyThread_set_key_value(int key, void *value)` `void* PyThread_get_key_value(int key)` `void PyThread_delete_key_value(int key)` `void PyThread_ReInitTLS()`
programming_docs
python Python/C API Reference Manual Python/C API Reference Manual ============================= This manual documents the API used by C and C++ programmers who want to write extension modules or embed Python. It is a companion to [Extending and Embedding the Python Interpreter](../extending/index#extending-index), which describes the general principles of extension writing but does not document the API functions in detail. * [Introduction](intro) + [Coding standards](intro#coding-standards) + [Include Files](intro#include-files) + [Useful macros](intro#useful-macros) + [Objects, Types and Reference Counts](intro#objects-types-and-reference-counts) + [Exceptions](intro#exceptions) + [Embedding Python](intro#embedding-python) + [Debugging Builds](intro#debugging-builds) * [Stable Application Binary Interface](stable) * [The Very High Level Layer](veryhigh) * [Reference Counting](refcounting) * [Exception Handling](exceptions) + [Printing and clearing](exceptions#printing-and-clearing) + [Raising exceptions](exceptions#raising-exceptions) + [Issuing warnings](exceptions#issuing-warnings) + [Querying the error indicator](exceptions#querying-the-error-indicator) + [Signal Handling](exceptions#signal-handling) + [Exception Classes](exceptions#exception-classes) + [Exception Objects](exceptions#exception-objects) + [Unicode Exception Objects](exceptions#unicode-exception-objects) + [Recursion Control](exceptions#recursion-control) + [Standard Exceptions](exceptions#standard-exceptions) + [Standard Warning Categories](exceptions#standard-warning-categories) * [Utilities](utilities) + [Operating System Utilities](sys) + [System Functions](sys#system-functions) + [Process Control](sys#process-control) + [Importing Modules](import) + [Data marshalling support](marshal) + [Parsing arguments and building values](arg) + [String conversion and formatting](conversion) + [Reflection](reflection) + [Codec registry and support functions](codec) * [Abstract Objects Layer](abstract) + [Object Protocol](object) + [Call Protocol](call) + [Number Protocol](number) + [Sequence Protocol](sequence) + [Mapping Protocol](mapping) + [Iterator Protocol](iter) + [Buffer Protocol](buffer) + [Old Buffer Protocol](objbuffer) * [Concrete Objects Layer](concrete) + [Fundamental Objects](concrete#fundamental-objects) + [Numeric Objects](concrete#numeric-objects) + [Sequence Objects](concrete#sequence-objects) + [Container Objects](concrete#container-objects) + [Function Objects](concrete#function-objects) + [Other Objects](concrete#other-objects) * [Initialization, Finalization, and Threads](init) + [Before Python Initialization](init#before-python-initialization) + [Global configuration variables](init#global-configuration-variables) + [Initializing and finalizing the interpreter](init#initializing-and-finalizing-the-interpreter) + [Process-wide parameters](init#process-wide-parameters) + [Thread State and the Global Interpreter Lock](init#thread-state-and-the-global-interpreter-lock) + [Sub-interpreter support](init#sub-interpreter-support) + [Asynchronous Notifications](init#asynchronous-notifications) + [Profiling and Tracing](init#profiling-and-tracing) + [Advanced Debugger Support](init#advanced-debugger-support) + [Thread Local Storage Support](init#thread-local-storage-support) * [Python Initialization Configuration](init_config) + [PyWideStringList](init_config#pywidestringlist) + [PyStatus](init_config#pystatus) + [PyPreConfig](init_config#pypreconfig) + [Preinitialization with PyPreConfig](init_config#preinitialization-with-pypreconfig) + [PyConfig](init_config#pyconfig) + [Initialization with PyConfig](init_config#initialization-with-pyconfig) + [Isolated Configuration](init_config#isolated-configuration) + [Python Configuration](init_config#python-configuration) + [Path Configuration](init_config#path-configuration) + [Py\_RunMain()](init_config#py-runmain) + [Py\_GetArgcArgv()](init_config#py-getargcargv) + [Multi-Phase Initialization Private Provisional API](init_config#multi-phase-initialization-private-provisional-api) * [Memory Management](memory) + [Overview](memory#overview) + [Raw Memory Interface](memory#raw-memory-interface) + [Memory Interface](memory#memory-interface) + [Object allocators](memory#object-allocators) + [Default Memory Allocators](memory#default-memory-allocators) + [Customize Memory Allocators](memory#customize-memory-allocators) + [The pymalloc allocator](memory#the-pymalloc-allocator) + [tracemalloc C API](memory#tracemalloc-c-api) + [Examples](memory#examples) * [Object Implementation Support](objimpl) + [Allocating Objects on the Heap](allocation) + [Common Object Structures](structures) + [Type Objects](typeobj) + [Number Object Structures](typeobj#number-object-structures) + [Mapping Object Structures](typeobj#mapping-object-structures) + [Sequence Object Structures](typeobj#sequence-object-structures) + [Buffer Object Structures](typeobj#buffer-object-structures) + [Async Object Structures](typeobj#async-object-structures) + [Slot Type typedefs](typeobj#slot-type-typedefs) + [Examples](typeobj#examples) + [Supporting Cyclic Garbage Collection](gcsupport) * [API and ABI Versioning](apiabiversion) python Type Objects Type Objects ============ `PyTypeObject` The C structure of the objects used to describe built-in types. `PyTypeObject PyType_Type` This is the type object for type objects; it is the same object as [`type`](../library/functions#type "type") in the Python layer. `int PyType_Check(PyObject *o)` Return non-zero if the object *o* is a type object, including instances of types derived from the standard type object. Return 0 in all other cases. This function always succeeds. `int PyType_CheckExact(PyObject *o)` Return non-zero if the object *o* is a type object, but not a subtype of the standard type object. Return 0 in all other cases. This function always succeeds. `unsigned int PyType_ClearCache()` Clear the internal lookup cache. Return the current version tag. `unsigned long PyType_GetFlags(PyTypeObject* type)` Return the [`tp_flags`](typeobj#c.PyTypeObject.tp_flags "PyTypeObject.tp_flags") member of *type*. This function is primarily meant for use with `Py_LIMITED_API`; the individual flag bits are guaranteed to be stable across Python releases, but access to [`tp_flags`](typeobj#c.PyTypeObject.tp_flags "PyTypeObject.tp_flags") itself is not part of the limited API. New in version 3.2. Changed in version 3.4: The return type is now `unsigned long` rather than `long`. `void PyType_Modified(PyTypeObject *type)` Invalidate the internal lookup cache for the type and all of its subtypes. This function must be called after any manual modification of the attributes or base classes of the type. `int PyType_HasFeature(PyTypeObject *o, int feature)` Return non-zero if the type object *o* sets the feature *feature*. Type features are denoted by single bit flags. `int PyType_IS_GC(PyTypeObject *o)` Return true if the type object includes support for the cycle detector; this tests the type flag [`Py_TPFLAGS_HAVE_GC`](typeobj#Py_TPFLAGS_HAVE_GC "Py_TPFLAGS_HAVE_GC"). `int PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)` Return true if *a* is a subtype of *b*. This function only checks for actual subtypes, which means that [`__subclasscheck__()`](../reference/datamodel#class.__subclasscheck__ "class.__subclasscheck__") is not called on *b*. Call [`PyObject_IsSubclass()`](object#c.PyObject_IsSubclass "PyObject_IsSubclass") to do the same check that [`issubclass()`](../library/functions#issubclass "issubclass") would do. `PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)` *Return value: New reference.*Generic handler for the [`tp_alloc`](typeobj#c.PyTypeObject.tp_alloc "PyTypeObject.tp_alloc") slot of a type object. Use Python’s default memory allocation mechanism to allocate a new instance and initialize all its contents to `NULL`. `PyObject* PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)` *Return value: New reference.*Generic handler for the [`tp_new`](typeobj#c.PyTypeObject.tp_new "PyTypeObject.tp_new") slot of a type object. Create a new instance using the type’s [`tp_alloc`](typeobj#c.PyTypeObject.tp_alloc "PyTypeObject.tp_alloc") slot. `int PyType_Ready(PyTypeObject *type)` Finalize a type object. This should be called on all type objects to finish their initialization. This function is responsible for adding inherited slots from a type’s base class. Return `0` on success, or return `-1` and sets an exception on error. Note If some of the base classes implements the GC protocol and the provided type does not include the [`Py_TPFLAGS_HAVE_GC`](typeobj#Py_TPFLAGS_HAVE_GC "Py_TPFLAGS_HAVE_GC") in its flags, then the GC protocol will be automatically implemented from its parents. On the contrary, if the type being created does include [`Py_TPFLAGS_HAVE_GC`](typeobj#Py_TPFLAGS_HAVE_GC "Py_TPFLAGS_HAVE_GC") in its flags then it **must** implement the GC protocol itself by at least implementing the [`tp_traverse`](typeobj#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse") handle. `void* PyType_GetSlot(PyTypeObject *type, int slot)` Return the function pointer stored in the given slot. If the result is `NULL`, this indicates that either the slot is `NULL`, or that the function was called with invalid parameters. Callers will typically cast the result pointer into the appropriate function type. See `PyType_Slot.slot` for possible values of the *slot* argument. An exception is raised if *type* is not a heap type. New in version 3.4. `PyObject* PyType_GetModule(PyTypeObject *type)` Return the module object associated with the given type when the type was created using [`PyType_FromModuleAndSpec()`](#c.PyType_FromModuleAndSpec "PyType_FromModuleAndSpec"). If no module is associated with the given type, sets [`TypeError`](../library/exceptions#TypeError "TypeError") and returns `NULL`. This function is usually used to get the module in which a method is defined. Note that in such a method, `PyType_GetModule(Py_TYPE(self))` may not return the intended result. `Py_TYPE(self)` may be a *subclass* of the intended class, and subclasses are not necessarily defined in the same module as their superclass. See [`PyCMethod`](structures#c.PyCMethod "PyCMethod") to get the class that defines the method. New in version 3.9. `void* PyType_GetModuleState(PyTypeObject *type)` Return the state of the module object associated with the given type. This is a shortcut for calling [`PyModule_GetState()`](module#c.PyModule_GetState "PyModule_GetState") on the result of [`PyType_GetModule()`](#c.PyType_GetModule "PyType_GetModule"). If no module is associated with the given type, sets [`TypeError`](../library/exceptions#TypeError "TypeError") and returns `NULL`. If the *type* has an associated module but its state is `NULL`, returns `NULL` without setting an exception. New in version 3.9. Creating Heap-Allocated Types ----------------------------- The following functions and structs are used to create [heap types](typeobj#heap-types). `PyObject* PyType_FromModuleAndSpec(PyObject *module, PyType_Spec *spec, PyObject *bases)` *Return value: New reference.*Creates and returns a heap type object from the *spec* ([`Py_TPFLAGS_HEAPTYPE`](typeobj#Py_TPFLAGS_HEAPTYPE "Py_TPFLAGS_HEAPTYPE")). If *bases* is a tuple, the created heap type contains all types contained in it as base types. If *bases* is `NULL`, the *Py\_tp\_bases* slot is used instead. If that also is `NULL`, the *Py\_tp\_base* slot is used instead. If that also is `NULL`, the new type derives from [`object`](../library/functions#object "object"). The *module* argument can be used to record the module in which the new class is defined. It must be a module object or `NULL`. If not `NULL`, the module is associated with the new type and can later be retrieved with [`PyType_GetModule()`](#c.PyType_GetModule "PyType_GetModule"). The associated module is not inherited by subclasses; it must be specified for each class individually. This function calls [`PyType_Ready()`](#c.PyType_Ready "PyType_Ready") on the new type. New in version 3.9. `PyObject* PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)` *Return value: New reference.*Equivalent to `PyType_FromModuleAndSpec(NULL, spec, bases)`. New in version 3.3. `PyObject* PyType_FromSpec(PyType_Spec *spec)` *Return value: New reference.*Equivalent to `PyType_FromSpecWithBases(spec, NULL)`. `PyType_Spec` Structure defining a type’s behavior. `const char* PyType_Spec.name` Name of the type, used to set [`PyTypeObject.tp_name`](typeobj#c.PyTypeObject.tp_name "PyTypeObject.tp_name"). `int PyType_Spec.basicsize` `int PyType_Spec.itemsize` Size of the instance in bytes, used to set [`PyTypeObject.tp_basicsize`](typeobj#c.PyTypeObject.tp_basicsize "PyTypeObject.tp_basicsize") and [`PyTypeObject.tp_itemsize`](typeobj#c.PyTypeObject.tp_itemsize "PyTypeObject.tp_itemsize"). `int PyType_Spec.flags` Type flags, used to set [`PyTypeObject.tp_flags`](typeobj#c.PyTypeObject.tp_flags "PyTypeObject.tp_flags"). If the `Py_TPFLAGS_HEAPTYPE` flag is not set, [`PyType_FromSpecWithBases()`](#c.PyType_FromSpecWithBases "PyType_FromSpecWithBases") sets it automatically. `PyType_Slot *PyType_Spec.slots` Array of [`PyType_Slot`](#c.PyType_Slot "PyType_Slot") structures. Terminated by the special slot value `{0, NULL}`. `PyType_Slot` Structure defining optional functionality of a type, containing a slot ID and a value pointer. `int PyType_Slot.slot` A slot ID. Slot IDs are named like the field names of the structures [`PyTypeObject`](#c.PyTypeObject "PyTypeObject"), [`PyNumberMethods`](typeobj#c.PyNumberMethods "PyNumberMethods"), [`PySequenceMethods`](typeobj#c.PySequenceMethods "PySequenceMethods"), [`PyMappingMethods`](typeobj#c.PyMappingMethods "PyMappingMethods") and [`PyAsyncMethods`](typeobj#c.PyAsyncMethods "PyAsyncMethods") with an added `Py_` prefix. For example, use: * `Py_tp_dealloc` to set [`PyTypeObject.tp_dealloc`](typeobj#c.PyTypeObject.tp_dealloc "PyTypeObject.tp_dealloc") * `Py_nb_add` to set [`PyNumberMethods.nb_add`](typeobj#c.PyNumberMethods.nb_add "PyNumberMethods.nb_add") * `Py_sq_length` to set [`PySequenceMethods.sq_length`](typeobj#c.PySequenceMethods.sq_length "PySequenceMethods.sq_length") The following fields cannot be set at all using [`PyType_Spec`](#c.PyType_Spec "PyType_Spec") and [`PyType_Slot`](#c.PyType_Slot "PyType_Slot"): * [`tp_dict`](typeobj#c.PyTypeObject.tp_dict "PyTypeObject.tp_dict") * [`tp_mro`](typeobj#c.PyTypeObject.tp_mro "PyTypeObject.tp_mro") * [`tp_cache`](typeobj#c.PyTypeObject.tp_cache "PyTypeObject.tp_cache") * [`tp_subclasses`](typeobj#c.PyTypeObject.tp_subclasses "PyTypeObject.tp_subclasses") * [`tp_weaklist`](typeobj#c.PyTypeObject.tp_weaklist "PyTypeObject.tp_weaklist") * [`tp_vectorcall`](typeobj#c.PyTypeObject.tp_vectorcall "PyTypeObject.tp_vectorcall") * [`tp_weaklistoffset`](typeobj#c.PyTypeObject.tp_weaklistoffset "PyTypeObject.tp_weaklistoffset") (see [PyMemberDef](structures#pymemberdef-offsets)) * [`tp_dictoffset`](typeobj#c.PyTypeObject.tp_dictoffset "PyTypeObject.tp_dictoffset") (see [PyMemberDef](structures#pymemberdef-offsets)) * [`tp_vectorcall_offset`](typeobj#c.PyTypeObject.tp_vectorcall_offset "PyTypeObject.tp_vectorcall_offset") (see [PyMemberDef](structures#pymemberdef-offsets)) The following fields cannot be set using [`PyType_Spec`](#c.PyType_Spec "PyType_Spec") and [`PyType_Slot`](#c.PyType_Slot "PyType_Slot") under the limited API: * [`bf_getbuffer`](typeobj#c.PyBufferProcs.bf_getbuffer "PyBufferProcs.bf_getbuffer") * [`bf_releasebuffer`](typeobj#c.PyBufferProcs.bf_releasebuffer "PyBufferProcs.bf_releasebuffer") Setting `Py_tp_bases` or `Py_tp_base` may be problematic on some platforms. To avoid issues, use the *bases* argument of `PyType_FromSpecWithBases()` instead. Changed in version 3.9: Slots in [`PyBufferProcs`](typeobj#c.PyBufferProcs "PyBufferProcs") may be set in the unlimited API. `void *PyType_Slot.pfunc` The desired value of the slot. In most cases, this is a pointer to a function. May not be `NULL`. python Coroutine Objects Coroutine Objects ================= New in version 3.5. Coroutine objects are what functions declared with an `async` keyword return. `PyCoroObject` The C structure used for coroutine objects. `PyTypeObject PyCoro_Type` The type object corresponding to coroutine objects. `int PyCoro_CheckExact(PyObject *ob)` Return true if *ob*’s type is [`PyCoro_Type`](#c.PyCoro_Type "PyCoro_Type"); *ob* must not be `NULL`. This function always succeeds. `PyObject* PyCoro_New(PyFrameObject *frame, PyObject *name, PyObject *qualname)` *Return value: New reference.*Create and return a new coroutine object based on the *frame* object, with `__name__` and `__qualname__` set to *name* and *qualname*. A reference to *frame* is stolen by this function. The *frame* argument must not be `NULL`. python Weak Reference Objects Weak Reference Objects ====================== Python supports *weak references* as first-class objects. There are two specific object types which directly implement weak references. The first is a simple reference object, and the second acts as a proxy for the original object as much as it can. `int PyWeakref_Check(ob)` Return true if *ob* is either a reference or proxy object. This function always succeeds. `int PyWeakref_CheckRef(ob)` Return true if *ob* is a reference object. This function always succeeds. `int PyWeakref_CheckProxy(ob)` Return true if *ob* is a proxy object. This function always succeeds. `PyObject* PyWeakref_NewRef(PyObject *ob, PyObject *callback)` *Return value: New reference.*Return a weak reference object for the object *ob*. This will always return a new reference, but is not guaranteed to create a new object; an existing reference object may be returned. The second parameter, *callback*, can be a callable object that receives notification when *ob* is garbage collected; it should accept a single parameter, which will be the weak reference object itself. *callback* may also be `None` or `NULL`. If *ob* is not a weakly-referencable object, or if *callback* is not callable, `None`, or `NULL`, this will return `NULL` and raise [`TypeError`](../library/exceptions#TypeError "TypeError"). `PyObject* PyWeakref_NewProxy(PyObject *ob, PyObject *callback)` *Return value: New reference.*Return a weak reference proxy object for the object *ob*. This will always return a new reference, but is not guaranteed to create a new object; an existing proxy object may be returned. The second parameter, *callback*, can be a callable object that receives notification when *ob* is garbage collected; it should accept a single parameter, which will be the weak reference object itself. *callback* may also be `None` or `NULL`. If *ob* is not a weakly-referencable object, or if *callback* is not callable, `None`, or `NULL`, this will return `NULL` and raise [`TypeError`](../library/exceptions#TypeError "TypeError"). `PyObject* PyWeakref_GetObject(PyObject *ref)` *Return value: Borrowed reference.*Return the referenced object from a weak reference, *ref*. If the referent is no longer live, returns `Py_None`. Note This function returns a **borrowed reference** to the referenced object. This means that you should always call [`Py_INCREF()`](refcounting#c.Py_INCREF "Py_INCREF") on the object except if you know that it cannot be destroyed while you are still using it. `PyObject* PyWeakref_GET_OBJECT(PyObject *ref)` *Return value: Borrowed reference.*Similar to [`PyWeakref_GetObject()`](#c.PyWeakref_GetObject "PyWeakref_GetObject"), but implemented as a macro that does no error checking.
programming_docs
python Descriptor Objects Descriptor Objects ================== “Descriptors” are objects that describe some attribute of an object. They are found in the dictionary of type objects. `PyTypeObject PyProperty_Type` The type object for the built-in descriptor types. `PyObject* PyDescr_NewGetSet(PyTypeObject *type, struct PyGetSetDef *getset)` *Return value: New reference.* `PyObject* PyDescr_NewMember(PyTypeObject *type, struct PyMemberDef *meth)` *Return value: New reference.* `PyObject* PyDescr_NewMethod(PyTypeObject *type, struct PyMethodDef *meth)` *Return value: New reference.* `PyObject* PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *wrapper, void *wrapped)` *Return value: New reference.* `PyObject* PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method)` *Return value: New reference.* `int PyDescr_IsData(PyObject *descr)` Return true if the descriptor objects *descr* describes a data attribute, or false if it describes a method. *descr* must be a descriptor object; there is no error checking. `PyObject* PyWrapper_New(PyObject *, PyObject *)` *Return value: New reference.* python Tuple Objects Tuple Objects ============= `PyTupleObject` This subtype of [`PyObject`](structures#c.PyObject "PyObject") represents a Python tuple object. `PyTypeObject PyTuple_Type` This instance of [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject") represents the Python tuple type; it is the same object as [`tuple`](../library/stdtypes#tuple "tuple") in the Python layer. `int PyTuple_Check(PyObject *p)` Return true if *p* is a tuple object or an instance of a subtype of the tuple type. This function always succeeds. `int PyTuple_CheckExact(PyObject *p)` Return true if *p* is a tuple object, but not an instance of a subtype of the tuple type. This function always succeeds. `PyObject* PyTuple_New(Py_ssize_t len)` *Return value: New reference.*Return a new tuple object of size *len*, or `NULL` on failure. `PyObject* PyTuple_Pack(Py_ssize_t n, ...)` *Return value: New reference.*Return a new tuple object of size *n*, or `NULL` on failure. The tuple values are initialized to the subsequent *n* C arguments pointing to Python objects. `PyTuple_Pack(2, a, b)` is equivalent to `Py_BuildValue("(OO)", a, b)`. `Py_ssize_t PyTuple_Size(PyObject *p)` Take a pointer to a tuple object, and return the size of that tuple. `Py_ssize_t PyTuple_GET_SIZE(PyObject *p)` Return the size of the tuple *p*, which must be non-`NULL` and point to a tuple; no error checking is performed. `PyObject* PyTuple_GetItem(PyObject *p, Py_ssize_t pos)` *Return value: Borrowed reference.*Return the object at position *pos* in the tuple pointed to by *p*. If *pos* is out of bounds, return `NULL` and set an [`IndexError`](../library/exceptions#IndexError "IndexError") exception. `PyObject* PyTuple_GET_ITEM(PyObject *p, Py_ssize_t pos)` *Return value: Borrowed reference.*Like [`PyTuple_GetItem()`](#c.PyTuple_GetItem "PyTuple_GetItem"), but does no checking of its arguments. `PyObject* PyTuple_GetSlice(PyObject *p, Py_ssize_t low, Py_ssize_t high)` *Return value: New reference.*Return the slice of the tuple pointed to by *p* between *low* and *high*, or `NULL` on failure. This is the equivalent of the Python expression `p[low:high]`. Indexing from the end of the list is not supported. `int PyTuple_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o)` Insert a reference to object *o* at position *pos* of the tuple pointed to by *p*. Return `0` on success. If *pos* is out of bounds, return `-1` and set an [`IndexError`](../library/exceptions#IndexError "IndexError") exception. Note This function “steals” a reference to *o* and discards a reference to an item already in the tuple at the affected position. `void PyTuple_SET_ITEM(PyObject *p, Py_ssize_t pos, PyObject *o)` Like [`PyTuple_SetItem()`](#c.PyTuple_SetItem "PyTuple_SetItem"), but does no error checking, and should *only* be used to fill in brand new tuples. Note This macro “steals” a reference to *o*, and, unlike [`PyTuple_SetItem()`](#c.PyTuple_SetItem "PyTuple_SetItem"), does *not* discard a reference to any item that is being replaced; any reference in the tuple at position *pos* will be leaked. `int _PyTuple_Resize(PyObject **p, Py_ssize_t newsize)` Can be used to resize a tuple. *newsize* will be the new length of the tuple. Because tuples are *supposed* to be immutable, this should only be used if there is only one reference to the object. Do *not* use this if the tuple may already be known to some other part of the code. The tuple will always grow or shrink at the end. Think of this as destroying the old tuple and creating a new one, only more efficiently. Returns `0` on success. Client code should never assume that the resulting value of `*p` will be the same as before calling this function. If the object referenced by `*p` is replaced, the original `*p` is destroyed. On failure, returns `-1` and sets `*p` to `NULL`, and raises [`MemoryError`](../library/exceptions#MemoryError "MemoryError") or [`SystemError`](../library/exceptions#SystemError "SystemError"). python Reflection Reflection ========== `PyObject* PyEval_GetBuiltins(void)` *Return value: Borrowed reference.*Return a dictionary of the builtins in the current execution frame, or the interpreter of the thread state if no frame is currently executing. `PyObject* PyEval_GetLocals(void)` *Return value: Borrowed reference.*Return a dictionary of the local variables in the current execution frame, or `NULL` if no frame is currently executing. `PyObject* PyEval_GetGlobals(void)` *Return value: Borrowed reference.*Return a dictionary of the global variables in the current execution frame, or `NULL` if no frame is currently executing. `PyFrameObject* PyEval_GetFrame(void)` *Return value: Borrowed reference.*Return the current thread state’s frame, which is `NULL` if no frame is currently executing. See also [`PyThreadState_GetFrame()`](init#c.PyThreadState_GetFrame "PyThreadState_GetFrame"). `PyFrameObject* PyFrame_GetBack(PyFrameObject *frame)` Get the *frame* next outer frame. Return a strong reference, or `NULL` if *frame* has no outer frame. *frame* must not be `NULL`. New in version 3.9. `PyCodeObject* PyFrame_GetCode(PyFrameObject *frame)` Get the *frame* code. Return a strong reference. *frame* must not be `NULL`. The result (frame code) cannot be `NULL`. New in version 3.9. `int PyFrame_GetLineNumber(PyFrameObject *frame)` Return the line number that *frame* is currently executing. *frame* must not be `NULL`. `const char* PyEval_GetFuncName(PyObject *func)` Return the name of *func* if it is a function, class or instance object, else the name of *func*s type. `const char* PyEval_GetFuncDesc(PyObject *func)` Return a description string, depending on the type of *func*. Return values include “()” for functions and methods, ” constructor”, ” instance”, and ” object”. Concatenated with the result of [`PyEval_GetFuncName()`](#c.PyEval_GetFuncName "PyEval_GetFuncName"), the result will be a description of *func*. python Utilities Utilities ========= The functions in this chapter perform various utility tasks, ranging from helping C code be more portable across platforms, using Python modules from C, and parsing function arguments and constructing Python values from C values. * [Operating System Utilities](sys) * [System Functions](sys#system-functions) * [Process Control](sys#process-control) * [Importing Modules](import) * [Data marshalling support](marshal) * [Parsing arguments and building values](arg) + [Parsing arguments](arg#parsing-arguments) - [Strings and buffers](arg#strings-and-buffers) - [Numbers](arg#numbers) - [Other objects](arg#other-objects) - [API Functions](arg#api-functions) + [Building values](arg#building-values) * [String conversion and formatting](conversion) * [Reflection](reflection) * [Codec registry and support functions](codec) + [Codec lookup API](codec#codec-lookup-api) + [Registry API for Unicode encoding error handlers](codec#registry-api-for-unicode-encoding-error-handlers) python Module Objects Module Objects ============== `PyTypeObject PyModule_Type` This instance of [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject") represents the Python module type. This is exposed to Python programs as `types.ModuleType`. `int PyModule_Check(PyObject *p)` Return true if *p* is a module object, or a subtype of a module object. This function always succeeds. `int PyModule_CheckExact(PyObject *p)` Return true if *p* is a module object, but not a subtype of [`PyModule_Type`](#c.PyModule_Type "PyModule_Type"). This function always succeeds. `PyObject* PyModule_NewObject(PyObject *name)` *Return value: New reference.*Return a new module object with the [`__name__`](../reference/import#__name__ "__name__") attribute set to *name*. The module’s [`__name__`](../reference/import#__name__ "__name__"), `__doc__`, [`__package__`](../reference/import#__package__ "__package__"), and [`__loader__`](../reference/import#__loader__ "__loader__") attributes are filled in (all but [`__name__`](../reference/import#__name__ "__name__") are set to `None`); the caller is responsible for providing a [`__file__`](../reference/import#__file__ "__file__") attribute. New in version 3.3. Changed in version 3.4: [`__package__`](../reference/import#__package__ "__package__") and [`__loader__`](../reference/import#__loader__ "__loader__") are set to `None`. `PyObject* PyModule_New(const char *name)` *Return value: New reference.*Similar to [`PyModule_NewObject()`](#c.PyModule_NewObject "PyModule_NewObject"), but the name is a UTF-8 encoded string instead of a Unicode object. `PyObject* PyModule_GetDict(PyObject *module)` *Return value: Borrowed reference.*Return the dictionary object that implements *module*’s namespace; this object is the same as the [`__dict__`](../library/stdtypes#object.__dict__ "object.__dict__") attribute of the module object. If *module* is not a module object (or a subtype of a module object), [`SystemError`](../library/exceptions#SystemError "SystemError") is raised and `NULL` is returned. It is recommended extensions use other `PyModule_*()` and `PyObject_*()` functions rather than directly manipulate a module’s [`__dict__`](../library/stdtypes#object.__dict__ "object.__dict__"). `PyObject* PyModule_GetNameObject(PyObject *module)` *Return value: New reference.*Return *module*’s [`__name__`](../reference/import#__name__ "__name__") value. If the module does not provide one, or if it is not a string, [`SystemError`](../library/exceptions#SystemError "SystemError") is raised and `NULL` is returned. New in version 3.3. `const char* PyModule_GetName(PyObject *module)` Similar to [`PyModule_GetNameObject()`](#c.PyModule_GetNameObject "PyModule_GetNameObject") but return the name encoded to `'utf-8'`. `void* PyModule_GetState(PyObject *module)` Return the “state” of the module, that is, a pointer to the block of memory allocated at module creation time, or `NULL`. See [`PyModuleDef.m_size`](#c.PyModuleDef.m_size "PyModuleDef.m_size"). `PyModuleDef* PyModule_GetDef(PyObject *module)` Return a pointer to the [`PyModuleDef`](#c.PyModuleDef "PyModuleDef") struct from which the module was created, or `NULL` if the module wasn’t created from a definition. `PyObject* PyModule_GetFilenameObject(PyObject *module)` *Return value: New reference.*Return the name of the file from which *module* was loaded using *module*’s [`__file__`](../reference/import#__file__ "__file__") attribute. If this is not defined, or if it is not a unicode string, raise [`SystemError`](../library/exceptions#SystemError "SystemError") and return `NULL`; otherwise return a reference to a Unicode object. New in version 3.2. `const char* PyModule_GetFilename(PyObject *module)` Similar to [`PyModule_GetFilenameObject()`](#c.PyModule_GetFilenameObject "PyModule_GetFilenameObject") but return the filename encoded to ‘utf-8’. Deprecated since version 3.2: [`PyModule_GetFilename()`](#c.PyModule_GetFilename "PyModule_GetFilename") raises `UnicodeEncodeError` on unencodable filenames, use [`PyModule_GetFilenameObject()`](#c.PyModule_GetFilenameObject "PyModule_GetFilenameObject") instead. Initializing C modules ---------------------- Modules objects are usually created from extension modules (shared libraries which export an initialization function), or compiled-in modules (where the initialization function is added using [`PyImport_AppendInittab()`](import#c.PyImport_AppendInittab "PyImport_AppendInittab")). See [Building C and C++ Extensions](../extending/building#building) or [Extending Embedded Python](../extending/embedding#extending-with-embedding) for details. The initialization function can either pass a module definition instance to [`PyModule_Create()`](#c.PyModule_Create "PyModule_Create"), and return the resulting module object, or request “multi-phase initialization” by returning the definition struct itself. `PyModuleDef` The module definition struct, which holds all information needed to create a module object. There is usually only one statically initialized variable of this type for each module. `PyModuleDef_Base m_base` Always initialize this member to `PyModuleDef_HEAD_INIT`. `const char *m_name` Name for the new module. `const char *m_doc` Docstring for the module; usually a docstring variable created with [`PyDoc_STRVAR`](intro#c.PyDoc_STRVAR "PyDoc_STRVAR") is used. `Py_ssize_t m_size` Module state may be kept in a per-module memory area that can be retrieved with [`PyModule_GetState()`](#c.PyModule_GetState "PyModule_GetState"), rather than in static globals. This makes modules safe for use in multiple sub-interpreters. This memory area is allocated based on *m\_size* on module creation, and freed when the module object is deallocated, after the `m_free` function has been called, if present. Setting `m_size` to `-1` means that the module does not support sub-interpreters, because it has global state. Setting it to a non-negative value means that the module can be re-initialized and specifies the additional amount of memory it requires for its state. Non-negative `m_size` is required for multi-phase initialization. See [**PEP 3121**](https://www.python.org/dev/peps/pep-3121) for more details. `PyMethodDef* m_methods` A pointer to a table of module-level functions, described by [`PyMethodDef`](structures#c.PyMethodDef "PyMethodDef") values. Can be `NULL` if no functions are present. `PyModuleDef_Slot* m_slots` An array of slot definitions for multi-phase initialization, terminated by a `{0, NULL}` entry. When using single-phase initialization, *m\_slots* must be `NULL`. Changed in version 3.5: Prior to version 3.5, this member was always set to `NULL`, and was defined as: `inquiry m_reload` `traverseproc m_traverse` A traversal function to call during GC traversal of the module object, or `NULL` if not needed. This function is not called if the module state was requested but is not allocated yet. This is the case immediately after the module is created and before the module is executed ([`Py_mod_exec`](#c.Py_mod_exec "Py_mod_exec") function). More precisely, this function is not called if `m_size` is greater than 0 and the module state (as returned by [`PyModule_GetState()`](#c.PyModule_GetState "PyModule_GetState")) is `NULL`. Changed in version 3.9: No longer called before the module state is allocated. `inquiry m_clear` A clear function to call during GC clearing of the module object, or `NULL` if not needed. This function is not called if the module state was requested but is not allocated yet. This is the case immediately after the module is created and before the module is executed ([`Py_mod_exec`](#c.Py_mod_exec "Py_mod_exec") function). More precisely, this function is not called if `m_size` is greater than 0 and the module state (as returned by [`PyModule_GetState()`](#c.PyModule_GetState "PyModule_GetState")) is `NULL`. Like [`PyTypeObject.tp_clear`](typeobj#c.PyTypeObject.tp_clear "PyTypeObject.tp_clear"), this function is not *always* called before a module is deallocated. For example, when reference counting is enough to determine that an object is no longer used, the cyclic garbage collector is not involved and [`m_free`](#c.PyModuleDef.m_free "PyModuleDef.m_free") is called directly. Changed in version 3.9: No longer called before the module state is allocated. `freefunc m_free` A function to call during deallocation of the module object, or `NULL` if not needed. This function is not called if the module state was requested but is not allocated yet. This is the case immediately after the module is created and before the module is executed ([`Py_mod_exec`](#c.Py_mod_exec "Py_mod_exec") function). More precisely, this function is not called if `m_size` is greater than 0 and the module state (as returned by [`PyModule_GetState()`](#c.PyModule_GetState "PyModule_GetState")) is `NULL`. Changed in version 3.9: No longer called before the module state is allocated. ### Single-phase initialization The module initialization function may create and return the module object directly. This is referred to as “single-phase initialization”, and uses one of the following two module creation functions: `PyObject* PyModule_Create(PyModuleDef *def)` *Return value: New reference.*Create a new module object, given the definition in *def*. This behaves like [`PyModule_Create2()`](#c.PyModule_Create2 "PyModule_Create2") with *module\_api\_version* set to `PYTHON_API_VERSION`. `PyObject* PyModule_Create2(PyModuleDef *def, int module_api_version)` *Return value: New reference.*Create a new module object, given the definition in *def*, assuming the API version *module\_api\_version*. If that version does not match the version of the running interpreter, a [`RuntimeWarning`](../library/exceptions#RuntimeWarning "RuntimeWarning") is emitted. Note Most uses of this function should be using [`PyModule_Create()`](#c.PyModule_Create "PyModule_Create") instead; only use this if you are sure you need it. Before it is returned from in the initialization function, the resulting module object is typically populated using functions like [`PyModule_AddObject()`](#c.PyModule_AddObject "PyModule_AddObject"). ### Multi-phase initialization An alternate way to specify extensions is to request “multi-phase initialization”. Extension modules created this way behave more like Python modules: the initialization is split between the *creation phase*, when the module object is created, and the *execution phase*, when it is populated. The distinction is similar to the [`__new__()`](../reference/datamodel#object.__new__ "object.__new__") and [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") methods of classes. Unlike modules created using single-phase initialization, these modules are not singletons: if the *sys.modules* entry is removed and the module is re-imported, a new module object is created, and the old module is subject to normal garbage collection – as with Python modules. By default, multiple modules created from the same definition should be independent: changes to one should not affect the others. This means that all state should be specific to the module object (using e.g. using [`PyModule_GetState()`](#c.PyModule_GetState "PyModule_GetState")), or its contents (such as the module’s [`__dict__`](../library/stdtypes#object.__dict__ "object.__dict__") or individual classes created with [`PyType_FromSpec()`](type#c.PyType_FromSpec "PyType_FromSpec")). All modules created using multi-phase initialization are expected to support [sub-interpreters](init#sub-interpreter-support). Making sure multiple modules are independent is typically enough to achieve this. To request multi-phase initialization, the initialization function (PyInit\_modulename) returns a [`PyModuleDef`](#c.PyModuleDef "PyModuleDef") instance with non-empty [`m_slots`](#c.PyModuleDef.m_slots "PyModuleDef.m_slots"). Before it is returned, the `PyModuleDef` instance must be initialized with the following function: `PyObject* PyModuleDef_Init(PyModuleDef *def)` *Return value: Borrowed reference.*Ensures a module definition is a properly initialized Python object that correctly reports its type and reference count. Returns *def* cast to `PyObject*`, or `NULL` if an error occurred. New in version 3.5. The *m\_slots* member of the module definition must point to an array of `PyModuleDef_Slot` structures: `PyModuleDef_Slot` `int slot` A slot ID, chosen from the available values explained below. `void* value` Value of the slot, whose meaning depends on the slot ID. New in version 3.5. The *m\_slots* array must be terminated by a slot with id 0. The available slot types are: `Py_mod_create` Specifies a function that is called to create the module object itself. The *value* pointer of this slot must point to a function of the signature: `PyObject* create_module(PyObject *spec, PyModuleDef *def)` The function receives a [`ModuleSpec`](../library/importlib#importlib.machinery.ModuleSpec "importlib.machinery.ModuleSpec") instance, as defined in [**PEP 451**](https://www.python.org/dev/peps/pep-0451), and the module definition. It should return a new module object, or set an error and return `NULL`. This function should be kept minimal. In particular, it should not call arbitrary Python code, as trying to import the same module again may result in an infinite loop. Multiple `Py_mod_create` slots may not be specified in one module definition. If `Py_mod_create` is not specified, the import machinery will create a normal module object using [`PyModule_New()`](#c.PyModule_New "PyModule_New"). The name is taken from *spec*, not the definition, to allow extension modules to dynamically adjust to their place in the module hierarchy and be imported under different names through symlinks, all while sharing a single module definition. There is no requirement for the returned object to be an instance of [`PyModule_Type`](#c.PyModule_Type "PyModule_Type"). Any type can be used, as long as it supports setting and getting import-related attributes. However, only `PyModule_Type` instances may be returned if the `PyModuleDef` has non-`NULL` `m_traverse`, `m_clear`, `m_free`; non-zero `m_size`; or slots other than `Py_mod_create`. `Py_mod_exec` Specifies a function that is called to *execute* the module. This is equivalent to executing the code of a Python module: typically, this function adds classes and constants to the module. The signature of the function is: `int exec_module(PyObject* module)` If multiple `Py_mod_exec` slots are specified, they are processed in the order they appear in the *m\_slots* array. See [**PEP 489**](https://www.python.org/dev/peps/pep-0489) for more details on multi-phase initialization. ### Low-level module creation functions The following functions are called under the hood when using multi-phase initialization. They can be used directly, for example when creating module objects dynamically. Note that both `PyModule_FromDefAndSpec` and `PyModule_ExecDef` must be called to fully initialize a module. `PyObject * PyModule_FromDefAndSpec(PyModuleDef *def, PyObject *spec)` *Return value: New reference.*Create a new module object, given the definition in *module* and the ModuleSpec *spec*. This behaves like [`PyModule_FromDefAndSpec2()`](#c.PyModule_FromDefAndSpec2 "PyModule_FromDefAndSpec2") with *module\_api\_version* set to `PYTHON_API_VERSION`. New in version 3.5. `PyObject * PyModule_FromDefAndSpec2(PyModuleDef *def, PyObject *spec, int module_api_version)` *Return value: New reference.*Create a new module object, given the definition in *module* and the ModuleSpec *spec*, assuming the API version *module\_api\_version*. If that version does not match the version of the running interpreter, a [`RuntimeWarning`](../library/exceptions#RuntimeWarning "RuntimeWarning") is emitted. Note Most uses of this function should be using [`PyModule_FromDefAndSpec()`](#c.PyModule_FromDefAndSpec "PyModule_FromDefAndSpec") instead; only use this if you are sure you need it. New in version 3.5. `int PyModule_ExecDef(PyObject *module, PyModuleDef *def)` Process any execution slots ([`Py_mod_exec`](#c.Py_mod_exec "Py_mod_exec")) given in *def*. New in version 3.5. `int PyModule_SetDocString(PyObject *module, const char *docstring)` Set the docstring for *module* to *docstring*. This function is called automatically when creating a module from `PyModuleDef`, using either `PyModule_Create` or `PyModule_FromDefAndSpec`. New in version 3.5. `int PyModule_AddFunctions(PyObject *module, PyMethodDef *functions)` Add the functions from the `NULL` terminated *functions* array to *module*. Refer to the [`PyMethodDef`](structures#c.PyMethodDef "PyMethodDef") documentation for details on individual entries (due to the lack of a shared module namespace, module level “functions” implemented in C typically receive the module as their first parameter, making them similar to instance methods on Python classes). This function is called automatically when creating a module from `PyModuleDef`, using either `PyModule_Create` or `PyModule_FromDefAndSpec`. New in version 3.5. ### Support functions The module initialization function (if using single phase initialization) or a function called from a module execution slot (if using multi-phase initialization), can use the following functions to help initialize the module state: `int PyModule_AddObject(PyObject *module, const char *name, PyObject *value)` Add an object to *module* as *name*. This is a convenience function which can be used from the module’s initialization function. This steals a reference to *value* on success. Return `-1` on error, `0` on success. Note Unlike other functions that steal references, `PyModule_AddObject()` only decrements the reference count of *value* **on success**. This means that its return value must be checked, and calling code must [`Py_DECREF()`](refcounting#c.Py_DECREF "Py_DECREF") *value* manually on error. Example usage: ``` Py_INCREF(spam); if (PyModule_AddObject(module, "spam", spam) < 0) { Py_DECREF(module); Py_DECREF(spam); return NULL; } ``` `int PyModule_AddIntConstant(PyObject *module, const char *name, long value)` Add an integer constant to *module* as *name*. This convenience function can be used from the module’s initialization function. Return `-1` on error, `0` on success. `int PyModule_AddStringConstant(PyObject *module, const char *name, const char *value)` Add a string constant to *module* as *name*. This convenience function can be used from the module’s initialization function. The string *value* must be `NULL`-terminated. Return `-1` on error, `0` on success. `int PyModule_AddIntMacro(PyObject *module, macro)` Add an int constant to *module*. The name and the value are taken from *macro*. For example `PyModule_AddIntMacro(module, AF_INET)` adds the int constant *AF\_INET* with the value of *AF\_INET* to *module*. Return `-1` on error, `0` on success. `int PyModule_AddStringMacro(PyObject *module, macro)` Add a string constant to *module*. `int PyModule_AddType(PyObject *module, PyTypeObject *type)` Add a type object to *module*. The type object is finalized by calling internally [`PyType_Ready()`](type#c.PyType_Ready "PyType_Ready"). The name of the type object is taken from the last component of [`tp_name`](typeobj#c.PyTypeObject.tp_name "PyTypeObject.tp_name") after dot. Return `-1` on error, `0` on success. New in version 3.9. Module lookup ------------- Single-phase initialization creates singleton modules that can be looked up in the context of the current interpreter. This allows the module object to be retrieved later with only a reference to the module definition. These functions will not work on modules created using multi-phase initialization, since multiple such modules can be created from a single definition. `PyObject* PyState_FindModule(PyModuleDef *def)` *Return value: Borrowed reference.*Returns the module object that was created from *def* for the current interpreter. This method requires that the module object has been attached to the interpreter state with [`PyState_AddModule()`](#c.PyState_AddModule "PyState_AddModule") beforehand. In case the corresponding module object is not found or has not been attached to the interpreter state yet, it returns `NULL`. `int PyState_AddModule(PyObject *module, PyModuleDef *def)` Attaches the module object passed to the function to the interpreter state. This allows the module object to be accessible via [`PyState_FindModule()`](#c.PyState_FindModule "PyState_FindModule"). Only effective on modules created using single-phase initialization. Python calls `PyState_AddModule` automatically after importing a module, so it is unnecessary (but harmless) to call it from module initialization code. An explicit call is needed only if the module’s own init code subsequently calls `PyState_FindModule`. The function is mainly intended for implementing alternative import mechanisms (either by calling it directly, or by referring to its implementation for details of the required state updates). The caller must hold the GIL. Return 0 on success or -1 on failure. New in version 3.3. `int PyState_RemoveModule(PyModuleDef *def)` Removes the module object created from *def* from the interpreter state. Return 0 on success or -1 on failure. The caller must hold the GIL. New in version 3.3.
programming_docs
python List Objects List Objects ============ `PyListObject` This subtype of [`PyObject`](structures#c.PyObject "PyObject") represents a Python list object. `PyTypeObject PyList_Type` This instance of [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject") represents the Python list type. This is the same object as [`list`](../library/stdtypes#list "list") in the Python layer. `int PyList_Check(PyObject *p)` Return true if *p* is a list object or an instance of a subtype of the list type. This function always succeeds. `int PyList_CheckExact(PyObject *p)` Return true if *p* is a list object, but not an instance of a subtype of the list type. This function always succeeds. `PyObject* PyList_New(Py_ssize_t len)` *Return value: New reference.*Return a new list of length *len* on success, or `NULL` on failure. Note If *len* is greater than zero, the returned list object’s items are set to `NULL`. Thus you cannot use abstract API functions such as [`PySequence_SetItem()`](sequence#c.PySequence_SetItem "PySequence_SetItem") or expose the object to Python code before setting all items to a real object with [`PyList_SetItem()`](#c.PyList_SetItem "PyList_SetItem"). `Py_ssize_t PyList_Size(PyObject *list)` Return the length of the list object in *list*; this is equivalent to `len(list)` on a list object. `Py_ssize_t PyList_GET_SIZE(PyObject *list)` Macro form of [`PyList_Size()`](#c.PyList_Size "PyList_Size") without error checking. `PyObject* PyList_GetItem(PyObject *list, Py_ssize_t index)` *Return value: Borrowed reference.*Return the object at position *index* in the list pointed to by *list*. The position must be non-negative; indexing from the end of the list is not supported. If *index* is out of bounds (<0 or >=len(list)), return `NULL` and set an [`IndexError`](../library/exceptions#IndexError "IndexError") exception. `PyObject* PyList_GET_ITEM(PyObject *list, Py_ssize_t i)` *Return value: Borrowed reference.*Macro form of [`PyList_GetItem()`](#c.PyList_GetItem "PyList_GetItem") without error checking. `int PyList_SetItem(PyObject *list, Py_ssize_t index, PyObject *item)` Set the item at index *index* in list to *item*. Return `0` on success. If *index* is out of bounds, return `-1` and set an [`IndexError`](../library/exceptions#IndexError "IndexError") exception. Note This function “steals” a reference to *item* and discards a reference to an item already in the list at the affected position. `void PyList_SET_ITEM(PyObject *list, Py_ssize_t i, PyObject *o)` Macro form of [`PyList_SetItem()`](#c.PyList_SetItem "PyList_SetItem") without error checking. This is normally only used to fill in new lists where there is no previous content. Note This macro “steals” a reference to *item*, and, unlike [`PyList_SetItem()`](#c.PyList_SetItem "PyList_SetItem"), does *not* discard a reference to any item that is being replaced; any reference in *list* at position *i* will be leaked. `int PyList_Insert(PyObject *list, Py_ssize_t index, PyObject *item)` Insert the item *item* into list *list* in front of index *index*. Return `0` if successful; return `-1` and set an exception if unsuccessful. Analogous to `list.insert(index, item)`. `int PyList_Append(PyObject *list, PyObject *item)` Append the object *item* at the end of list *list*. Return `0` if successful; return `-1` and set an exception if unsuccessful. Analogous to `list.append(item)`. `PyObject* PyList_GetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high)` *Return value: New reference.*Return a list of the objects in *list* containing the objects *between* *low* and *high*. Return `NULL` and set an exception if unsuccessful. Analogous to `list[low:high]`. Indexing from the end of the list is not supported. `int PyList_SetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high, PyObject *itemlist)` Set the slice of *list* between *low* and *high* to the contents of *itemlist*. Analogous to `list[low:high] = itemlist`. The *itemlist* may be `NULL`, indicating the assignment of an empty list (slice deletion). Return `0` on success, `-1` on failure. Indexing from the end of the list is not supported. `int PyList_Sort(PyObject *list)` Sort the items of *list* in place. Return `0` on success, `-1` on failure. This is equivalent to `list.sort()`. `int PyList_Reverse(PyObject *list)` Reverse the items of *list* in place. Return `0` on success, `-1` on failure. This is the equivalent of `list.reverse()`. `PyObject* PyList_AsTuple(PyObject *list)` *Return value: New reference.*Return a new tuple object containing the contents of *list*; equivalent to `tuple(list)`. python Bytes Objects Bytes Objects ============= These functions raise [`TypeError`](../library/exceptions#TypeError "TypeError") when expecting a bytes parameter and called with a non-bytes parameter. `PyBytesObject` This subtype of [`PyObject`](structures#c.PyObject "PyObject") represents a Python bytes object. `PyTypeObject PyBytes_Type` This instance of [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject") represents the Python bytes type; it is the same object as [`bytes`](../library/stdtypes#bytes "bytes") in the Python layer. `int PyBytes_Check(PyObject *o)` Return true if the object *o* is a bytes object or an instance of a subtype of the bytes type. This function always succeeds. `int PyBytes_CheckExact(PyObject *o)` Return true if the object *o* is a bytes object, but not an instance of a subtype of the bytes type. This function always succeeds. `PyObject* PyBytes_FromString(const char *v)` *Return value: New reference.*Return a new bytes object with a copy of the string *v* as value on success, and `NULL` on failure. The parameter *v* must not be `NULL`; it will not be checked. `PyObject* PyBytes_FromStringAndSize(const char *v, Py_ssize_t len)` *Return value: New reference.*Return a new bytes object with a copy of the string *v* as value and length *len* on success, and `NULL` on failure. If *v* is `NULL`, the contents of the bytes object are uninitialized. `PyObject* PyBytes_FromFormat(const char *format, ...)` *Return value: New reference.*Take a C `printf()`-style *format* string and a variable number of arguments, calculate the size of the resulting Python bytes object and return a bytes object with the values formatted into it. The variable arguments must be C types and must correspond exactly to the format characters in the *format* string. The following format characters are allowed: | Format Characters | Type | Comment | | --- | --- | --- | | `%%` | *n/a* | The literal % character. | | `%c` | int | A single byte, represented as a C int. | | `%d` | int | Equivalent to `printf("%d")`. [1](#id9) | | `%u` | unsigned int | Equivalent to `printf("%u")`. [1](#id9) | | `%ld` | long | Equivalent to `printf("%ld")`. [1](#id9) | | `%lu` | unsigned long | Equivalent to `printf("%lu")`. [1](#id9) | | `%zd` | [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t") | Equivalent to `printf("%zd")`. [1](#id9) | | `%zu` | size\_t | Equivalent to `printf("%zu")`. [1](#id9) | | `%i` | int | Equivalent to `printf("%i")`. [1](#id9) | | `%x` | int | Equivalent to `printf("%x")`. [1](#id9) | | `%s` | const char\* | A null-terminated C character array. | | `%p` | const void\* | The hex representation of a C pointer. Mostly equivalent to `printf("%p")` except that it is guaranteed to start with the literal `0x` regardless of what the platform’s `printf` yields. | An unrecognized format character causes all the rest of the format string to be copied as-is to the result object, and any extra arguments discarded. `1(1,2,3,4,5,6,7,8)` For integer specifiers (d, u, ld, lu, zd, zu, i, x): the 0-conversion flag has effect even when a precision is given. `PyObject* PyBytes_FromFormatV(const char *format, va_list vargs)` *Return value: New reference.*Identical to [`PyBytes_FromFormat()`](#c.PyBytes_FromFormat "PyBytes_FromFormat") except that it takes exactly two arguments. `PyObject* PyBytes_FromObject(PyObject *o)` *Return value: New reference.*Return the bytes representation of object *o* that implements the buffer protocol. `Py_ssize_t PyBytes_Size(PyObject *o)` Return the length of the bytes in bytes object *o*. `Py_ssize_t PyBytes_GET_SIZE(PyObject *o)` Macro form of [`PyBytes_Size()`](#c.PyBytes_Size "PyBytes_Size") but without error checking. `char* PyBytes_AsString(PyObject *o)` Return a pointer to the contents of *o*. The pointer refers to the internal buffer of *o*, which consists of `len(o) + 1` bytes. The last byte in the buffer is always null, regardless of whether there are any other null bytes. The data must not be modified in any way, unless the object was just created using `PyBytes_FromStringAndSize(NULL, size)`. It must not be deallocated. If *o* is not a bytes object at all, [`PyBytes_AsString()`](#c.PyBytes_AsString "PyBytes_AsString") returns `NULL` and raises [`TypeError`](../library/exceptions#TypeError "TypeError"). `char* PyBytes_AS_STRING(PyObject *string)` Macro form of [`PyBytes_AsString()`](#c.PyBytes_AsString "PyBytes_AsString") but without error checking. `int PyBytes_AsStringAndSize(PyObject *obj, char **buffer, Py_ssize_t *length)` Return the null-terminated contents of the object *obj* through the output variables *buffer* and *length*. If *length* is `NULL`, the bytes object may not contain embedded null bytes; if it does, the function returns `-1` and a [`ValueError`](../library/exceptions#ValueError "ValueError") is raised. The buffer refers to an internal buffer of *obj*, which includes an additional null byte at the end (not counted in *length*). The data must not be modified in any way, unless the object was just created using `PyBytes_FromStringAndSize(NULL, size)`. It must not be deallocated. If *obj* is not a bytes object at all, [`PyBytes_AsStringAndSize()`](#c.PyBytes_AsStringAndSize "PyBytes_AsStringAndSize") returns `-1` and raises [`TypeError`](../library/exceptions#TypeError "TypeError"). Changed in version 3.5: Previously, [`TypeError`](../library/exceptions#TypeError "TypeError") was raised when embedded null bytes were encountered in the bytes object. `void PyBytes_Concat(PyObject **bytes, PyObject *newpart)` Create a new bytes object in *\*bytes* containing the contents of *newpart* appended to *bytes*; the caller will own the new reference. The reference to the old value of *bytes* will be stolen. If the new object cannot be created, the old reference to *bytes* will still be discarded and the value of *\*bytes* will be set to `NULL`; the appropriate exception will be set. `void PyBytes_ConcatAndDel(PyObject **bytes, PyObject *newpart)` Create a new bytes object in *\*bytes* containing the contents of *newpart* appended to *bytes*. This version decrements the reference count of *newpart*. `int _PyBytes_Resize(PyObject **bytes, Py_ssize_t newsize)` A way to resize a bytes object even though it is “immutable”. Only use this to build up a brand new bytes object; don’t use this if the bytes may already be known in other parts of the code. It is an error to call this function if the refcount on the input bytes object is not one. Pass the address of an existing bytes object as an lvalue (it may be written into), and the new size desired. On success, *\*bytes* holds the resized bytes object and `0` is returned; the address in *\*bytes* may differ from its input value. If the reallocation fails, the original bytes object at *\*bytes* is deallocated, *\*bytes* is set to `NULL`, [`MemoryError`](../library/exceptions#MemoryError "MemoryError") is set, and `-1` is returned. python Allocating Objects on the Heap Allocating Objects on the Heap ============================== `PyObject* _PyObject_New(PyTypeObject *type)` *Return value: New reference.* `PyVarObject* _PyObject_NewVar(PyTypeObject *type, Py_ssize_t size)` *Return value: New reference.* `PyObject* PyObject_Init(PyObject *op, PyTypeObject *type)` *Return value: Borrowed reference.*Initialize a newly-allocated object *op* with its type and initial reference. Returns the initialized object. If *type* indicates that the object participates in the cyclic garbage detector, it is added to the detector’s set of observed objects. Other fields of the object are not affected. `PyVarObject* PyObject_InitVar(PyVarObject *op, PyTypeObject *type, Py_ssize_t size)` *Return value: Borrowed reference.*This does everything [`PyObject_Init()`](#c.PyObject_Init "PyObject_Init") does, and also initializes the length information for a variable-size object. `TYPE* PyObject_New(TYPE, PyTypeObject *type)` *Return value: New reference.*Allocate a new Python object using the C structure type *TYPE* and the Python type object *type*. Fields not defined by the Python object header are not initialized; the object’s reference count will be one. The size of the memory allocation is determined from the [`tp_basicsize`](typeobj#c.PyTypeObject.tp_basicsize "PyTypeObject.tp_basicsize") field of the type object. `TYPE* PyObject_NewVar(TYPE, PyTypeObject *type, Py_ssize_t size)` *Return value: New reference.*Allocate a new Python object using the C structure type *TYPE* and the Python type object *type*. Fields not defined by the Python object header are not initialized. The allocated memory allows for the *TYPE* structure plus *size* fields of the size given by the [`tp_itemsize`](typeobj#c.PyTypeObject.tp_itemsize "PyTypeObject.tp_itemsize") field of *type*. This is useful for implementing objects like tuples, which are able to determine their size at construction time. Embedding the array of fields into the same allocation decreases the number of allocations, improving the memory management efficiency. `void PyObject_Del(void *op)` Releases memory allocated to an object using [`PyObject_New()`](#c.PyObject_New "PyObject_New") or [`PyObject_NewVar()`](#c.PyObject_NewVar "PyObject_NewVar"). This is normally called from the [`tp_dealloc`](typeobj#c.PyTypeObject.tp_dealloc "PyTypeObject.tp_dealloc") handler specified in the object’s type. The fields of the object should not be accessed after this call as the memory is no longer a valid Python object. `PyObject _Py_NoneStruct` Object which is visible in Python as `None`. This should only be accessed using the [`Py_None`](none#c.Py_None "Py_None") macro, which evaluates to a pointer to this object. See also [`PyModule_Create()`](module#c.PyModule_Create "PyModule_Create") To allocate and create extension modules. python Python Initialization Configuration Python Initialization Configuration =================================== New in version 3.8. Structures: * [`PyConfig`](#c.PyConfig "PyConfig") * [`PyPreConfig`](#c.PyPreConfig "PyPreConfig") * [`PyStatus`](#c.PyStatus "PyStatus") * [`PyWideStringList`](#c.PyWideStringList "PyWideStringList") Functions: * [`PyConfig_Clear()`](#c.PyConfig_Clear "PyConfig_Clear") * [`PyConfig_InitIsolatedConfig()`](#c.PyConfig_InitIsolatedConfig "PyConfig_InitIsolatedConfig") * [`PyConfig_InitPythonConfig()`](#c.PyConfig_InitPythonConfig "PyConfig_InitPythonConfig") * [`PyConfig_Read()`](#c.PyConfig_Read "PyConfig_Read") * [`PyConfig_SetArgv()`](#c.PyConfig_SetArgv "PyConfig_SetArgv") * [`PyConfig_SetBytesArgv()`](#c.PyConfig_SetBytesArgv "PyConfig_SetBytesArgv") * [`PyConfig_SetBytesString()`](#c.PyConfig_SetBytesString "PyConfig_SetBytesString") * [`PyConfig_SetString()`](#c.PyConfig_SetString "PyConfig_SetString") * [`PyConfig_SetWideStringList()`](#c.PyConfig_SetWideStringList "PyConfig_SetWideStringList") * [`PyPreConfig_InitIsolatedConfig()`](#c.PyPreConfig_InitIsolatedConfig "PyPreConfig_InitIsolatedConfig") * [`PyPreConfig_InitPythonConfig()`](#c.PyPreConfig_InitPythonConfig "PyPreConfig_InitPythonConfig") * [`PyStatus_Error()`](#c.PyStatus_Error "PyStatus_Error") * [`PyStatus_Exception()`](#c.PyStatus_Exception "PyStatus_Exception") * [`PyStatus_Exit()`](#c.PyStatus_Exit "PyStatus_Exit") * [`PyStatus_IsError()`](#c.PyStatus_IsError "PyStatus_IsError") * [`PyStatus_IsExit()`](#c.PyStatus_IsExit "PyStatus_IsExit") * [`PyStatus_NoMemory()`](#c.PyStatus_NoMemory "PyStatus_NoMemory") * [`PyStatus_Ok()`](#c.PyStatus_Ok "PyStatus_Ok") * [`PyWideStringList_Append()`](#c.PyWideStringList_Append "PyWideStringList_Append") * [`PyWideStringList_Insert()`](#c.PyWideStringList_Insert "PyWideStringList_Insert") * [`Py_ExitStatusException()`](#c.Py_ExitStatusException "Py_ExitStatusException") * [`Py_InitializeFromConfig()`](#c.Py_InitializeFromConfig "Py_InitializeFromConfig") * [`Py_PreInitialize()`](#c.Py_PreInitialize "Py_PreInitialize") * [`Py_PreInitializeFromArgs()`](#c.Py_PreInitializeFromArgs "Py_PreInitializeFromArgs") * [`Py_PreInitializeFromBytesArgs()`](#c.Py_PreInitializeFromBytesArgs "Py_PreInitializeFromBytesArgs") * [`Py_RunMain()`](#c.Py_RunMain "Py_RunMain") * [`Py_GetArgcArgv()`](#c.Py_GetArgcArgv "Py_GetArgcArgv") The preconfiguration (`PyPreConfig` type) is stored in `_PyRuntime.preconfig` and the configuration (`PyConfig` type) is stored in `PyInterpreterState.config`. See also [Initialization, Finalization, and Threads](init#initialization). See also [**PEP 587**](https://www.python.org/dev/peps/pep-0587) “Python Initialization Configuration”. PyWideStringList ---------------- `PyWideStringList` List of `wchar_t*` strings. If *length* is non-zero, *items* must be non-`NULL` and all strings must be non-`NULL`. Methods: `PyStatus PyWideStringList_Append(PyWideStringList *list, const wchar_t *item)` Append *item* to *list*. Python must be preinitialized to call this function. `PyStatus PyWideStringList_Insert(PyWideStringList *list, Py_ssize_t index, const wchar_t *item)` Insert *item* into *list* at *index*. If *index* is greater than or equal to *list* length, append *item* to *list*. *index* must be greater than or equal to 0. Python must be preinitialized to call this function. Structure fields: `Py_ssize_t length` List length. `wchar_t** items` List items. PyStatus -------- `PyStatus` Structure to store an initialization function status: success, error or exit. For an error, it can store the C function name which created the error. Structure fields: `int exitcode` Exit code. Argument passed to `exit()`. `const char *err_msg` Error message. `const char *func` Name of the function which created an error, can be `NULL`. Functions to create a status: `PyStatus PyStatus_Ok(void)` Success. `PyStatus PyStatus_Error(const char *err_msg)` Initialization error with a message. `PyStatus PyStatus_NoMemory(void)` Memory allocation failure (out of memory). `PyStatus PyStatus_Exit(int exitcode)` Exit Python with the specified exit code. Functions to handle a status: `int PyStatus_Exception(PyStatus status)` Is the status an error or an exit? If true, the exception must be handled; by calling [`Py_ExitStatusException()`](#c.Py_ExitStatusException "Py_ExitStatusException") for example. `int PyStatus_IsError(PyStatus status)` Is the result an error? `int PyStatus_IsExit(PyStatus status)` Is the result an exit? `void Py_ExitStatusException(PyStatus status)` Call `exit(exitcode)` if *status* is an exit. Print the error message and exit with a non-zero exit code if *status* is an error. Must only be called if `PyStatus_Exception(status)` is non-zero. Note Internally, Python uses macros which set `PyStatus.func`, whereas functions to create a status set `func` to `NULL`. Example: ``` PyStatus alloc(void **ptr, size_t size) { *ptr = PyMem_RawMalloc(size); if (*ptr == NULL) { return PyStatus_NoMemory(); } return PyStatus_Ok(); } int main(int argc, char **argv) { void *ptr; PyStatus status = alloc(&ptr, 16); if (PyStatus_Exception(status)) { Py_ExitStatusException(status); } PyMem_Free(ptr); return 0; } ``` PyPreConfig ----------- `PyPreConfig` Structure used to preinitialize Python: * Set the Python memory allocator * Configure the LC\_CTYPE locale * Set the UTF-8 mode Function to initialize a preconfiguration: `void PyPreConfig_InitPythonConfig(PyPreConfig *preconfig)` Initialize the preconfiguration with [Python Configuration](#init-python-config). `void PyPreConfig_InitIsolatedConfig(PyPreConfig *preconfig)` Initialize the preconfiguration with [Isolated Configuration](#init-isolated-conf). Structure fields: `int allocator` Name of the memory allocator: * `PYMEM_ALLOCATOR_NOT_SET` (`0`): don’t change memory allocators (use defaults) * `PYMEM_ALLOCATOR_DEFAULT` (`1`): default memory allocators * `PYMEM_ALLOCATOR_DEBUG` (`2`): default memory allocators with debug hooks * `PYMEM_ALLOCATOR_MALLOC` (`3`): force usage of `malloc()` * `PYMEM_ALLOCATOR_MALLOC_DEBUG` (`4`): force usage of `malloc()` with debug hooks * `PYMEM_ALLOCATOR_PYMALLOC` (`5`): [Python pymalloc memory allocator](memory#pymalloc) * `PYMEM_ALLOCATOR_PYMALLOC_DEBUG` (`6`): [Python pymalloc memory allocator](memory#pymalloc) with debug hooks `PYMEM_ALLOCATOR_PYMALLOC` and `PYMEM_ALLOCATOR_PYMALLOC_DEBUG` are not supported if Python is configured using `--without-pymalloc` See [Memory Management](memory#memory). `int configure_locale` Set the LC\_CTYPE locale to the user preferred locale? If equals to 0, set `coerce_c_locale` and `coerce_c_locale_warn` to 0. `int coerce_c_locale` If equals to 2, coerce the C locale; if equals to 1, read the LC\_CTYPE locale to decide if it should be coerced. `int coerce_c_locale_warn` If non-zero, emit a warning if the C locale is coerced. `int dev_mode` See [`PyConfig.dev_mode`](#c.PyConfig.dev_mode "PyConfig.dev_mode"). `int isolated` See [`PyConfig.isolated`](#c.PyConfig.isolated "PyConfig.isolated"). `int legacy_windows_fs_encoding(Windows only)` If non-zero, disable UTF-8 Mode, set the Python filesystem encoding to `mbcs`, set the filesystem error handler to `replace`. Only available on Windows. `#ifdef MS_WINDOWS` macro can be used for Windows specific code. `int parse_argv` If non-zero, [`Py_PreInitializeFromArgs()`](#c.Py_PreInitializeFromArgs "Py_PreInitializeFromArgs") and [`Py_PreInitializeFromBytesArgs()`](#c.Py_PreInitializeFromBytesArgs "Py_PreInitializeFromBytesArgs") parse their `argv` argument the same way the regular Python parses command line arguments: see [Command Line Arguments](../using/cmdline#using-on-cmdline). `int use_environment` See [`PyConfig.use_environment`](#c.PyConfig.use_environment "PyConfig.use_environment"). `int utf8_mode` If non-zero, enable the UTF-8 mode. Preinitialization with PyPreConfig ---------------------------------- Functions to preinitialize Python: `PyStatus Py_PreInitialize(const PyPreConfig *preconfig)` Preinitialize Python from *preconfig* preconfiguration. `PyStatus Py_PreInitializeFromBytesArgs(const PyPreConfig *preconfig, int argc, char * const *argv)` Preinitialize Python from *preconfig* preconfiguration and command line arguments (bytes strings). `PyStatus Py_PreInitializeFromArgs(const PyPreConfig *preconfig, int argc, wchar_t * const * argv)` Preinitialize Python from *preconfig* preconfiguration and command line arguments (wide strings). The caller is responsible to handle exceptions (error or exit) using [`PyStatus_Exception()`](#c.PyStatus_Exception "PyStatus_Exception") and [`Py_ExitStatusException()`](#c.Py_ExitStatusException "Py_ExitStatusException"). For [Python Configuration](#init-python-config) ([`PyPreConfig_InitPythonConfig()`](#c.PyPreConfig_InitPythonConfig "PyPreConfig_InitPythonConfig")), if Python is initialized with command line arguments, the command line arguments must also be passed to preinitialize Python, since they have an effect on the pre-configuration like encodings. For example, the [`-X utf8`](../using/cmdline#id5) command line option enables the UTF-8 Mode. `PyMem_SetAllocator()` can be called after [`Py_PreInitialize()`](#c.Py_PreInitialize "Py_PreInitialize") and before [`Py_InitializeFromConfig()`](#c.Py_InitializeFromConfig "Py_InitializeFromConfig") to install a custom memory allocator. It can be called before [`Py_PreInitialize()`](#c.Py_PreInitialize "Py_PreInitialize") if [`PyPreConfig.allocator`](#c.PyPreConfig.allocator "PyPreConfig.allocator") is set to `PYMEM_ALLOCATOR_NOT_SET`. Python memory allocation functions like [`PyMem_RawMalloc()`](memory#c.PyMem_RawMalloc "PyMem_RawMalloc") must not be used before Python preinitialization, whereas calling directly `malloc()` and `free()` is always safe. [`Py_DecodeLocale()`](sys#c.Py_DecodeLocale "Py_DecodeLocale") must not be called before the preinitialization. Example using the preinitialization to enable the UTF-8 Mode: ``` PyStatus status; PyPreConfig preconfig; PyPreConfig_InitPythonConfig(&preconfig); preconfig.utf8_mode = 1; status = Py_PreInitialize(&preconfig); if (PyStatus_Exception(status)) { Py_ExitStatusException(status); } /* at this point, Python will speak UTF-8 */ Py_Initialize(); /* ... use Python API here ... */ Py_Finalize(); ``` PyConfig -------- `PyConfig` Structure containing most parameters to configure Python. Structure methods: `void PyConfig_InitPythonConfig(PyConfig *config)` Initialize configuration with [Python Configuration](#init-python-config). `void PyConfig_InitIsolatedConfig(PyConfig *config)` Initialize configuration with [Isolated Configuration](#init-isolated-conf). `PyStatus PyConfig_SetString(PyConfig *config, wchar_t * const *config_str, const wchar_t *str)` Copy the wide character string *str* into `*config_str`. Preinitialize Python if needed. `PyStatus PyConfig_SetBytesString(PyConfig *config, wchar_t * const *config_str, const char *str)` Decode *str* using `Py_DecodeLocale()` and set the result into `*config_str`. Preinitialize Python if needed. `PyStatus PyConfig_SetArgv(PyConfig *config, int argc, wchar_t * const *argv)` Set command line arguments from wide character strings. Preinitialize Python if needed. `PyStatus PyConfig_SetBytesArgv(PyConfig *config, int argc, char * const *argv)` Set command line arguments: decode bytes using [`Py_DecodeLocale()`](sys#c.Py_DecodeLocale "Py_DecodeLocale"). Preinitialize Python if needed. `PyStatus PyConfig_SetWideStringList(PyConfig *config, PyWideStringList *list, Py_ssize_t length, wchar_t **items)` Set the list of wide strings *list* to *length* and *items*. Preinitialize Python if needed. `PyStatus PyConfig_Read(PyConfig *config)` Read all Python configuration. Fields which are already initialized are left unchanged. Preinitialize Python if needed. `void PyConfig_Clear(PyConfig *config)` Release configuration memory. Most `PyConfig` methods preinitialize Python if needed. In that case, the Python preinitialization configuration in based on the [`PyConfig`](#c.PyConfig "PyConfig"). If configuration fields which are in common with [`PyPreConfig`](#c.PyPreConfig "PyPreConfig") are tuned, they must be set before calling a [`PyConfig`](#c.PyConfig "PyConfig") method: * [`dev_mode`](#c.PyConfig.dev_mode "PyConfig.dev_mode") * [`isolated`](#c.PyConfig.isolated "PyConfig.isolated") * [`parse_argv`](#c.PyConfig.parse_argv "PyConfig.parse_argv") * [`use_environment`](#c.PyConfig.use_environment "PyConfig.use_environment") Moreover, if [`PyConfig_SetArgv()`](#c.PyConfig_SetArgv "PyConfig_SetArgv") or [`PyConfig_SetBytesArgv()`](#c.PyConfig_SetBytesArgv "PyConfig_SetBytesArgv") is used, this method must be called first, before other methods, since the preinitialization configuration depends on command line arguments (if `parse_argv` is non-zero). The caller of these methods is responsible to handle exceptions (error or exit) using `PyStatus_Exception()` and `Py_ExitStatusException()`. Structure fields: `PyWideStringList argv` Command line arguments, [`sys.argv`](../library/sys#sys.argv "sys.argv"). See [`parse_argv`](#c.PyConfig.parse_argv "PyConfig.parse_argv") to parse [`argv`](#c.PyConfig.argv "PyConfig.argv") the same way the regular Python parses Python command line arguments. If [`argv`](#c.PyConfig.argv "PyConfig.argv") is empty, an empty string is added to ensure that [`sys.argv`](../library/sys#sys.argv "sys.argv") always exists and is never empty. `wchar_t* base_exec_prefix` [`sys.base_exec_prefix`](../library/sys#sys.base_exec_prefix "sys.base_exec_prefix"). `wchar_t* base_executable` `sys._base_executable`: `__PYVENV_LAUNCHER__` environment variable value, or copy of [`PyConfig.executable`](#c.PyConfig.executable "PyConfig.executable"). `wchar_t* base_prefix` [`sys.base_prefix`](../library/sys#sys.base_prefix "sys.base_prefix"). `wchar_t* platlibdir` [`sys.platlibdir`](../library/sys#sys.platlibdir "sys.platlibdir"): platform library directory name, set at configure time by `--with-platlibdir`, overrideable by the `PYTHONPLATLIBDIR` environment variable. New in version 3.9. `int buffered_stdio` If equals to 0, enable unbuffered mode, making the stdout and stderr streams unbuffered. stdin is always opened in buffered mode. `int bytes_warning` If equals to 1, issue a warning when comparing [`bytes`](../library/stdtypes#bytes "bytes") or [`bytearray`](../library/stdtypes#bytearray "bytearray") with [`str`](../library/stdtypes#str "str"), or comparing [`bytes`](../library/stdtypes#bytes "bytes") with [`int`](../library/functions#int "int"). If equal or greater to 2, raise a [`BytesWarning`](../library/exceptions#BytesWarning "BytesWarning") exception. `wchar_t* check_hash_pycs_mode` Control the validation behavior of hash-based `.pyc` files (see [**PEP 552**](https://www.python.org/dev/peps/pep-0552)): [`--check-hash-based-pycs`](../using/cmdline#cmdoption-check-hash-based-pycs) command line option value. Valid values: `always`, `never` and `default`. The default value is: `default`. `int configure_c_stdio` If non-zero, configure C standard streams (`stdio`, `stdout`, `stdout`). For example, set their mode to `O_BINARY` on Windows. `int dev_mode` If non-zero, enable the [Python Development Mode](../library/devmode#devmode). `int dump_refs` If non-zero, dump all objects which are still alive at exit. `Py_TRACE_REFS` macro must be defined in build. `wchar_t* exec_prefix` [`sys.exec_prefix`](../library/sys#sys.exec_prefix "sys.exec_prefix"). `wchar_t* executable` [`sys.executable`](../library/sys#sys.executable "sys.executable"). `int faulthandler` If non-zero, call [`faulthandler.enable()`](../library/faulthandler#faulthandler.enable "faulthandler.enable") at startup. `wchar_t* filesystem_encoding` Filesystem encoding, [`sys.getfilesystemencoding()`](../library/sys#sys.getfilesystemencoding "sys.getfilesystemencoding"). `wchar_t* filesystem_errors` Filesystem encoding errors, [`sys.getfilesystemencodeerrors()`](../library/sys#sys.getfilesystemencodeerrors "sys.getfilesystemencodeerrors"). `unsigned long hash_seed` `int use_hash_seed` Randomized hash function seed. If [`use_hash_seed`](#c.PyConfig.use_hash_seed "PyConfig.use_hash_seed") is zero, a seed is chosen randomly at Pythonstartup, and [`hash_seed`](#c.PyConfig.hash_seed "PyConfig.hash_seed") is ignored. `wchar_t* home` Python home directory. Initialized from [`PYTHONHOME`](../using/cmdline#envvar-PYTHONHOME) environment variable value by default. `int import_time` If non-zero, profile import time. `int inspect` Enter interactive mode after executing a script or a command. `int install_signal_handlers` Install signal handlers? `int interactive` Interactive mode. `int isolated` If greater than 0, enable isolated mode: * [`sys.path`](../library/sys#sys.path "sys.path") contains neither the script’s directory (computed from `argv[0]` or the current directory) nor the user’s site-packages directory. * Python REPL doesn’t import [`readline`](../library/readline#module-readline "readline: GNU readline support for Python. (Unix)") nor enable default readline configuration on interactive prompts. * Set [`use_environment`](#c.PyConfig.use_environment "PyConfig.use_environment") and [`user_site_directory`](#c.PyConfig.user_site_directory "PyConfig.user_site_directory") to 0. `int legacy_windows_stdio` If non-zero, use [`io.FileIO`](../library/io#io.FileIO "io.FileIO") instead of `io.WindowsConsoleIO` for [`sys.stdin`](../library/sys#sys.stdin "sys.stdin"), [`sys.stdout`](../library/sys#sys.stdout "sys.stdout") and [`sys.stderr`](../library/sys#sys.stderr "sys.stderr"). Only available on Windows. `#ifdef MS_WINDOWS` macro can be used for Windows specific code. `int malloc_stats` If non-zero, dump statistics on [Python pymalloc memory allocator](memory#pymalloc) at exit. The option is ignored if Python is built using `--without-pymalloc`. `wchar_t* pythonpath_env` Module search paths as a string separated by `DELIM` (`os.path.pathsep`). Initialized from [`PYTHONPATH`](../using/cmdline#envvar-PYTHONPATH) environment variable value by default. `PyWideStringList module_search_paths` `int module_search_paths_set` [`sys.path`](../library/sys#sys.path "sys.path"). If [`module_search_paths_set`](#c.PyConfig.module_search_paths_set "PyConfig.module_search_paths_set") is equal to 0, the [`module_search_paths`](#c.PyConfig.module_search_paths "PyConfig.module_search_paths") is overridden by the function calculating the [Path Configuration](#init-path-config). `int optimization_level` Compilation optimization level: * 0: Peephole optimizer (and `__debug__` is set to `True`) * 1: Remove assertions, set `__debug__` to `False` * 2: Strip docstrings `int parse_argv` If non-zero, parse [`argv`](#c.PyConfig.argv "PyConfig.argv") the same way the regular Python command line arguments, and strip Python arguments from [`argv`](#c.PyConfig.argv "PyConfig.argv"): see [Command Line Arguments](../using/cmdline#using-on-cmdline). `int parser_debug` If non-zero, turn on parser debugging output (for expert only, depending on compilation options). `int pathconfig_warnings` If equal to 0, suppress warnings when calculating the [Path Configuration](#init-path-config) (Unix only, Windows does not log any warning). Otherwise, warnings are written into `stderr`. `wchar_t* prefix` [`sys.prefix`](../library/sys#sys.prefix "sys.prefix"). `wchar_t* program_name` Program name. Used to initialize [`executable`](#c.PyConfig.executable "PyConfig.executable"), and in early error messages. `wchar_t* pycache_prefix` [`sys.pycache_prefix`](../library/sys#sys.pycache_prefix "sys.pycache_prefix"): `.pyc` cache prefix. If `NULL`, [`sys.pycache_prefix`](../library/sys#sys.pycache_prefix "sys.pycache_prefix") is set to `None`. `int quiet` Quiet mode. For example, don’t display the copyright and version messages in interactive mode. `wchar_t* run_command` `python3 -c COMMAND` argument. Used by [`Py_RunMain()`](#c.Py_RunMain "Py_RunMain"). `wchar_t* run_filename` `python3 FILENAME` argument. Used by [`Py_RunMain()`](#c.Py_RunMain "Py_RunMain"). `wchar_t* run_module` `python3 -m MODULE` argument. Used by [`Py_RunMain()`](#c.Py_RunMain "Py_RunMain"). `int show_ref_count` Show total reference count at exit? Set to 1 by [`-X showrefcount`](../using/cmdline#id5) command line option. Need a debug build of Python (`Py_REF_DEBUG` macro must be defined). `int site_import` Import the [`site`](../library/site#module-site "site: Module responsible for site-specific configuration.") module at startup? `int skip_source_first_line` Skip the first line of the source? `wchar_t* stdio_encoding` `wchar_t* stdio_errors` Encoding and encoding errors of [`sys.stdin`](../library/sys#sys.stdin "sys.stdin"), [`sys.stdout`](../library/sys#sys.stdout "sys.stdout") and [`sys.stderr`](../library/sys#sys.stderr "sys.stderr"). `int tracemalloc` If non-zero, call [`tracemalloc.start()`](../library/tracemalloc#tracemalloc.start "tracemalloc.start") at startup. `int use_environment` If greater than 0, use [environment variables](../using/cmdline#using-on-envvars). `int user_site_directory` If non-zero, add user site directory to [`sys.path`](../library/sys#sys.path "sys.path"). `int verbose` If non-zero, enable verbose mode. `PyWideStringList warnoptions` [`sys.warnoptions`](../library/sys#sys.warnoptions "sys.warnoptions"): options of the [`warnings`](../library/warnings#module-warnings "warnings: Issue warning messages and control their disposition.") module to build warnings filters: lowest to highest priority. The [`warnings`](../library/warnings#module-warnings "warnings: Issue warning messages and control their disposition.") module adds [`sys.warnoptions`](../library/sys#sys.warnoptions "sys.warnoptions") in the reverse order: the last [`PyConfig.warnoptions`](#c.PyConfig.warnoptions "PyConfig.warnoptions") item becomes the first item of `warnings.filters` which is checked first (highest priority). `int write_bytecode` If non-zero, write `.pyc` files. [`sys.dont_write_bytecode`](../library/sys#sys.dont_write_bytecode "sys.dont_write_bytecode") is initialized to the inverted value of [`write_bytecode`](#c.PyConfig.write_bytecode "PyConfig.write_bytecode"). `PyWideStringList xoptions` [`sys._xoptions`](../library/sys#sys._xoptions "sys._xoptions"). `int _use_peg_parser` Enable PEG parser? Default: 1. Set to 0 by [`-X oldparser`](../using/cmdline#id5) and [`PYTHONOLDPARSER`](../using/cmdline#envvar-PYTHONOLDPARSER). See also [**PEP 617**](https://www.python.org/dev/peps/pep-0617). Deprecated since version 3.9, will be removed in version 3.10. If `parse_argv` is non-zero, `argv` arguments are parsed the same way the regular Python parses command line arguments, and Python arguments are stripped from `argv`: see [Command Line Arguments](../using/cmdline#using-on-cmdline). The `xoptions` options are parsed to set other options: see [`-X`](../using/cmdline#id5) option. Changed in version 3.9: The `show_alloc_count` field has been removed. Initialization with PyConfig ---------------------------- Function to initialize Python: `PyStatus Py_InitializeFromConfig(const PyConfig *config)` Initialize Python from *config* configuration. The caller is responsible to handle exceptions (error or exit) using [`PyStatus_Exception()`](#c.PyStatus_Exception "PyStatus_Exception") and [`Py_ExitStatusException()`](#c.Py_ExitStatusException "Py_ExitStatusException"). If [`PyImport_FrozenModules()`](import#c.PyImport_FrozenModules "PyImport_FrozenModules"), [`PyImport_AppendInittab()`](import#c.PyImport_AppendInittab "PyImport_AppendInittab") or [`PyImport_ExtendInittab()`](import#c.PyImport_ExtendInittab "PyImport_ExtendInittab") are used, they must be set or called after Python preinitialization and before the Python initialization. If Python is initialized multiple times, [`PyImport_AppendInittab()`](import#c.PyImport_AppendInittab "PyImport_AppendInittab") or [`PyImport_ExtendInittab()`](import#c.PyImport_ExtendInittab "PyImport_ExtendInittab") must be called before each Python initialization. Example setting the program name: ``` void init_python(void) { PyStatus status; PyConfig config; PyConfig_InitPythonConfig(&config); /* Set the program name. Implicitly preinitialize Python. */ status = PyConfig_SetString(&config, &config.program_name, L"/path/to/my_program"); if (PyStatus_Exception(status)) { goto fail; } status = Py_InitializeFromConfig(&config); if (PyStatus_Exception(status)) { goto fail; } PyConfig_Clear(&config); return; fail: PyConfig_Clear(&config); Py_ExitStatusException(status); } ``` More complete example modifying the default configuration, read the configuration, and then override some parameters: ``` PyStatus init_python(const char *program_name) { PyStatus status; PyConfig config; PyConfig_InitPythonConfig(&config); /* Set the program name before reading the configuration (decode byte string from the locale encoding). Implicitly preinitialize Python. */ status = PyConfig_SetBytesString(&config, &config.program_name, program_name); if (PyStatus_Exception(status)) { goto done; } /* Read all configuration at once */ status = PyConfig_Read(&config); if (PyStatus_Exception(status)) { goto done; } /* Append our custom search path to sys.path */ status = PyWideStringList_Append(&config.module_search_paths, L"/path/to/more/modules"); if (PyStatus_Exception(status)) { goto done; } /* Override executable computed by PyConfig_Read() */ status = PyConfig_SetString(&config, &config.executable, L"/path/to/my_executable"); if (PyStatus_Exception(status)) { goto done; } status = Py_InitializeFromConfig(&config); done: PyConfig_Clear(&config); return status; } ``` Isolated Configuration ---------------------- [`PyPreConfig_InitIsolatedConfig()`](#c.PyPreConfig_InitIsolatedConfig "PyPreConfig_InitIsolatedConfig") and [`PyConfig_InitIsolatedConfig()`](#c.PyConfig_InitIsolatedConfig "PyConfig_InitIsolatedConfig") functions create a configuration to isolate Python from the system. For example, to embed Python into an application. This configuration ignores global configuration variables, environment variables, command line arguments ([`PyConfig.argv`](#c.PyConfig.argv "PyConfig.argv") is not parsed) and user site directory. The C standard streams (ex: `stdout`) and the LC\_CTYPE locale are left unchanged. Signal handlers are not installed. Configuration files are still used with this configuration. Set the [Path Configuration](#init-path-config) (“output fields”) to ignore these configuration files and avoid the function computing the default path configuration. Python Configuration -------------------- [`PyPreConfig_InitPythonConfig()`](#c.PyPreConfig_InitPythonConfig "PyPreConfig_InitPythonConfig") and [`PyConfig_InitPythonConfig()`](#c.PyConfig_InitPythonConfig "PyConfig_InitPythonConfig") functions create a configuration to build a customized Python which behaves as the regular Python. Environments variables and command line arguments are used to configure Python, whereas global configuration variables are ignored. This function enables C locale coercion ([**PEP 538**](https://www.python.org/dev/peps/pep-0538)) and UTF-8 Mode ([**PEP 540**](https://www.python.org/dev/peps/pep-0540)) depending on the LC\_CTYPE locale, [`PYTHONUTF8`](../using/cmdline#envvar-PYTHONUTF8) and [`PYTHONCOERCECLOCALE`](../using/cmdline#envvar-PYTHONCOERCECLOCALE) environment variables. Example of customized Python always running in isolated mode: ``` int main(int argc, char **argv) { PyStatus status; PyConfig config; PyConfig_InitPythonConfig(&config); config.isolated = 1; /* Decode command line arguments. Implicitly preinitialize Python (in isolated mode). */ status = PyConfig_SetBytesArgv(&config, argc, argv); if (PyStatus_Exception(status)) { goto fail; } status = Py_InitializeFromConfig(&config); if (PyStatus_Exception(status)) { goto fail; } PyConfig_Clear(&config); return Py_RunMain(); fail: PyConfig_Clear(&config); if (PyStatus_IsExit(status)) { return status.exitcode; } /* Display the error message and exit the process with non-zero exit code */ Py_ExitStatusException(status); } ``` Path Configuration ------------------ [`PyConfig`](#c.PyConfig "PyConfig") contains multiple fields for the path configuration: * Path configuration inputs: + [`PyConfig.home`](#c.PyConfig.home "PyConfig.home") + [`PyConfig.platlibdir`](#c.PyConfig.platlibdir "PyConfig.platlibdir") + [`PyConfig.pathconfig_warnings`](#c.PyConfig.pathconfig_warnings "PyConfig.pathconfig_warnings") + [`PyConfig.program_name`](#c.PyConfig.program_name "PyConfig.program_name") + [`PyConfig.pythonpath_env`](#c.PyConfig.pythonpath_env "PyConfig.pythonpath_env") + current working directory: to get absolute paths + `PATH` environment variable to get the program full path (from [`PyConfig.program_name`](#c.PyConfig.program_name "PyConfig.program_name")) + `__PYVENV_LAUNCHER__` environment variable + (Windows only) Application paths in the registry under “SoftwarePythonPythonCoreX.YPythonPath” of HKEY\_CURRENT\_USER and HKEY\_LOCAL\_MACHINE (where X.Y is the Python version). * Path configuration output fields: + [`PyConfig.base_exec_prefix`](#c.PyConfig.base_exec_prefix "PyConfig.base_exec_prefix") + [`PyConfig.base_executable`](#c.PyConfig.base_executable "PyConfig.base_executable") + [`PyConfig.base_prefix`](#c.PyConfig.base_prefix "PyConfig.base_prefix") + [`PyConfig.exec_prefix`](#c.PyConfig.exec_prefix "PyConfig.exec_prefix") + [`PyConfig.executable`](#c.PyConfig.executable "PyConfig.executable") + [`PyConfig.module_search_paths_set`](#c.PyConfig.module_search_paths_set "PyConfig.module_search_paths_set"), [`PyConfig.module_search_paths`](#c.PyConfig.module_search_paths "PyConfig.module_search_paths") + [`PyConfig.prefix`](#c.PyConfig.prefix "PyConfig.prefix") If at least one “output field” is not set, Python calculates the path configuration to fill unset fields. If [`module_search_paths_set`](#c.PyConfig.module_search_paths_set "PyConfig.module_search_paths_set") is equal to 0, [`module_search_paths`](#c.PyConfig.module_search_paths "PyConfig.module_search_paths") is overridden and [`module_search_paths_set`](#c.PyConfig.module_search_paths_set "PyConfig.module_search_paths_set") is set to 1. It is possible to completely ignore the function calculating the default path configuration by setting explicitly all path configuration output fields listed above. A string is considered as set even if it is non-empty. `module_search_paths` is considered as set if `module_search_paths_set` is set to 1. In this case, path configuration input fields are ignored as well. Set [`pathconfig_warnings`](#c.PyConfig.pathconfig_warnings "PyConfig.pathconfig_warnings") to 0 to suppress warnings when calculating the path configuration (Unix only, Windows does not log any warning). If [`base_prefix`](#c.PyConfig.base_prefix "PyConfig.base_prefix") or [`base_exec_prefix`](#c.PyConfig.base_exec_prefix "PyConfig.base_exec_prefix") fields are not set, they inherit their value from [`prefix`](#c.PyConfig.prefix "PyConfig.prefix") and [`exec_prefix`](#c.PyConfig.exec_prefix "PyConfig.exec_prefix") respectively. [`Py_RunMain()`](#c.Py_RunMain "Py_RunMain") and [`Py_Main()`](veryhigh#c.Py_Main "Py_Main") modify [`sys.path`](../library/sys#sys.path "sys.path"): * If [`run_filename`](#c.PyConfig.run_filename "PyConfig.run_filename") is set and is a directory which contains a `__main__.py` script, prepend [`run_filename`](#c.PyConfig.run_filename "PyConfig.run_filename") to [`sys.path`](../library/sys#sys.path "sys.path"). * If [`isolated`](#c.PyConfig.isolated "PyConfig.isolated") is zero: + If [`run_module`](#c.PyConfig.run_module "PyConfig.run_module") is set, prepend the current directory to [`sys.path`](../library/sys#sys.path "sys.path"). Do nothing if the current directory cannot be read. + If [`run_filename`](#c.PyConfig.run_filename "PyConfig.run_filename") is set, prepend the directory of the filename to [`sys.path`](../library/sys#sys.path "sys.path"). + Otherwise, prepend an empty string to [`sys.path`](../library/sys#sys.path "sys.path"). If [`site_import`](#c.PyConfig.site_import "PyConfig.site_import") is non-zero, [`sys.path`](../library/sys#sys.path "sys.path") can be modified by the [`site`](../library/site#module-site "site: Module responsible for site-specific configuration.") module. If [`user_site_directory`](#c.PyConfig.user_site_directory "PyConfig.user_site_directory") is non-zero and the user’s site-package directory exists, the [`site`](../library/site#module-site "site: Module responsible for site-specific configuration.") module appends the user’s site-package directory to [`sys.path`](../library/sys#sys.path "sys.path"). The following configuration files are used by the path configuration: * `pyvenv.cfg` * `python._pth` (Windows only) * `pybuilddir.txt` (Unix only) The `__PYVENV_LAUNCHER__` environment variable is used to set [`PyConfig.base_executable`](#c.PyConfig.base_executable "PyConfig.base_executable") Py\_RunMain() ------------- `int Py_RunMain(void)` Execute the command ([`PyConfig.run_command`](#c.PyConfig.run_command "PyConfig.run_command")), the script ([`PyConfig.run_filename`](#c.PyConfig.run_filename "PyConfig.run_filename")) or the module ([`PyConfig.run_module`](#c.PyConfig.run_module "PyConfig.run_module")) specified on the command line or in the configuration. By default and when if [`-i`](../using/cmdline#cmdoption-i) option is used, run the REPL. Finally, finalizes Python and returns an exit status that can be passed to the `exit()` function. See [Python Configuration](#init-python-config) for an example of customized Python always running in isolated mode using [`Py_RunMain()`](#c.Py_RunMain "Py_RunMain"). Py\_GetArgcArgv() ----------------- `void Py_GetArgcArgv(int *argc, wchar_t ***argv)` Get the original command line arguments, before Python modified them. Multi-Phase Initialization Private Provisional API -------------------------------------------------- This section is a private provisional API introducing multi-phase initialization, the core feature of [**PEP 432**](https://www.python.org/dev/peps/pep-0432): * “Core” initialization phase, “bare minimum Python”: + Builtin types; + Builtin exceptions; + Builtin and frozen modules; + The [`sys`](../library/sys#module-sys "sys: Access system-specific parameters and functions.") module is only partially initialized (ex: [`sys.path`](../library/sys#sys.path "sys.path") doesn’t exist yet). * “Main” initialization phase, Python is fully initialized: + Install and configure [`importlib`](../library/importlib#module-importlib "importlib: The implementation of the import machinery."); + Apply the [Path Configuration](#init-path-config); + Install signal handlers; + Finish [`sys`](../library/sys#module-sys "sys: Access system-specific parameters and functions.") module initialization (ex: create [`sys.stdout`](../library/sys#sys.stdout "sys.stdout") and [`sys.path`](../library/sys#sys.path "sys.path")); + Enable optional features like [`faulthandler`](../library/faulthandler#module-faulthandler "faulthandler: Dump the Python traceback.") and [`tracemalloc`](../library/tracemalloc#module-tracemalloc "tracemalloc: Trace memory allocations."); + Import the [`site`](../library/site#module-site "site: Module responsible for site-specific configuration.") module; + etc. Private provisional API: * `PyConfig._init_main`: if set to 0, [`Py_InitializeFromConfig()`](#c.Py_InitializeFromConfig "Py_InitializeFromConfig") stops at the “Core” initialization phase. * `PyConfig._isolated_interpreter`: if non-zero, disallow threads, subprocesses and fork. `PyStatus _Py_InitializeMain(void)` Move to the “Main” initialization phase, finish the Python initialization. No module is imported during the “Core” phase and the `importlib` module is not configured: the [Path Configuration](#init-path-config) is only applied during the “Main” phase. It may allow to customize Python in Python to override or tune the [Path Configuration](#init-path-config), maybe install a custom [`sys.meta_path`](../library/sys#sys.meta_path "sys.meta_path") importer or an import hook, etc. It may become possible to calculatin the [Path Configuration](#init-path-config) in Python, after the Core phase and before the Main phase, which is one of the [**PEP 432**](https://www.python.org/dev/peps/pep-0432) motivation. The “Core” phase is not properly defined: what should be and what should not be available at this phase is not specified yet. The API is marked as private and provisional: the API can be modified or even be removed anytime until a proper public API is designed. Example running Python code between “Core” and “Main” initialization phases: ``` void init_python(void) { PyStatus status; PyConfig config; PyConfig_InitPythonConfig(&config); config._init_main = 0; /* ... customize 'config' configuration ... */ status = Py_InitializeFromConfig(&config); PyConfig_Clear(&config); if (PyStatus_Exception(status)) { Py_ExitStatusException(status); } /* Use sys.stderr because sys.stdout is only created by _Py_InitializeMain() */ int res = PyRun_SimpleString( "import sys; " "print('Run Python code before _Py_InitializeMain', " "file=sys.stderr)"); if (res < 0) { exit(1); } /* ... put more configuration code here ... */ status = _Py_InitializeMain(); if (PyStatus_Exception(status)) { Py_ExitStatusException(status); } } ```
programming_docs
python Floating Point Objects Floating Point Objects ====================== `PyFloatObject` This subtype of [`PyObject`](structures#c.PyObject "PyObject") represents a Python floating point object. `PyTypeObject PyFloat_Type` This instance of [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject") represents the Python floating point type. This is the same object as [`float`](../library/functions#float "float") in the Python layer. `int PyFloat_Check(PyObject *p)` Return true if its argument is a [`PyFloatObject`](#c.PyFloatObject "PyFloatObject") or a subtype of [`PyFloatObject`](#c.PyFloatObject "PyFloatObject"). This function always succeeds. `int PyFloat_CheckExact(PyObject *p)` Return true if its argument is a [`PyFloatObject`](#c.PyFloatObject "PyFloatObject"), but not a subtype of [`PyFloatObject`](#c.PyFloatObject "PyFloatObject"). This function always succeeds. `PyObject* PyFloat_FromString(PyObject *str)` *Return value: New reference.*Create a [`PyFloatObject`](#c.PyFloatObject "PyFloatObject") object based on the string value in *str*, or `NULL` on failure. `PyObject* PyFloat_FromDouble(double v)` *Return value: New reference.*Create a [`PyFloatObject`](#c.PyFloatObject "PyFloatObject") object from *v*, or `NULL` on failure. `double PyFloat_AsDouble(PyObject *pyfloat)` Return a C `double` representation of the contents of *pyfloat*. If *pyfloat* is not a Python floating point object but has a [`__float__()`](../reference/datamodel#object.__float__ "object.__float__") method, this method will first be called to convert *pyfloat* into a float. If `__float__()` is not defined then it falls back to [`__index__()`](../reference/datamodel#object.__index__ "object.__index__"). This method returns `-1.0` upon failure, so one should call [`PyErr_Occurred()`](exceptions#c.PyErr_Occurred "PyErr_Occurred") to check for errors. Changed in version 3.8: Use [`__index__()`](../reference/datamodel#object.__index__ "object.__index__") if available. `double PyFloat_AS_DOUBLE(PyObject *pyfloat)` Return a C `double` representation of the contents of *pyfloat*, but without error checking. `PyObject* PyFloat_GetInfo(void)` *Return value: New reference.*Return a structseq instance which contains information about the precision, minimum and maximum values of a float. It’s a thin wrapper around the header file `float.h`. `double PyFloat_GetMax()` Return the maximum representable finite float *DBL\_MAX* as C `double`. `double PyFloat_GetMin()` Return the minimum normalized positive float *DBL\_MIN* as C `double`. python Integer Objects Integer Objects =============== All integers are implemented as “long” integer objects of arbitrary size. On error, most `PyLong_As*` APIs return `(return type)-1` which cannot be distinguished from a number. Use [`PyErr_Occurred()`](exceptions#c.PyErr_Occurred "PyErr_Occurred") to disambiguate. `PyLongObject` This subtype of [`PyObject`](structures#c.PyObject "PyObject") represents a Python integer object. `PyTypeObject PyLong_Type` This instance of [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject") represents the Python integer type. This is the same object as [`int`](../library/functions#int "int") in the Python layer. `int PyLong_Check(PyObject *p)` Return true if its argument is a [`PyLongObject`](#c.PyLongObject "PyLongObject") or a subtype of [`PyLongObject`](#c.PyLongObject "PyLongObject"). This function always succeeds. `int PyLong_CheckExact(PyObject *p)` Return true if its argument is a [`PyLongObject`](#c.PyLongObject "PyLongObject"), but not a subtype of [`PyLongObject`](#c.PyLongObject "PyLongObject"). This function always succeeds. `PyObject* PyLong_FromLong(long v)` *Return value: New reference.*Return a new [`PyLongObject`](#c.PyLongObject "PyLongObject") object from *v*, or `NULL` on failure. The current implementation keeps an array of integer objects for all integers between `-5` and `256`. When you create an int in that range you actually just get back a reference to the existing object. `PyObject* PyLong_FromUnsignedLong(unsigned long v)` *Return value: New reference.*Return a new [`PyLongObject`](#c.PyLongObject "PyLongObject") object from a C `unsigned long`, or `NULL` on failure. `PyObject* PyLong_FromSsize_t(Py_ssize_t v)` *Return value: New reference.*Return a new [`PyLongObject`](#c.PyLongObject "PyLongObject") object from a C [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t"), or `NULL` on failure. `PyObject* PyLong_FromSize_t(size_t v)` *Return value: New reference.*Return a new [`PyLongObject`](#c.PyLongObject "PyLongObject") object from a C `size_t`, or `NULL` on failure. `PyObject* PyLong_FromLongLong(long long v)` *Return value: New reference.*Return a new [`PyLongObject`](#c.PyLongObject "PyLongObject") object from a C `long long`, or `NULL` on failure. `PyObject* PyLong_FromUnsignedLongLong(unsigned long long v)` *Return value: New reference.*Return a new [`PyLongObject`](#c.PyLongObject "PyLongObject") object from a C `unsigned long long`, or `NULL` on failure. `PyObject* PyLong_FromDouble(double v)` *Return value: New reference.*Return a new [`PyLongObject`](#c.PyLongObject "PyLongObject") object from the integer part of *v*, or `NULL` on failure. `PyObject* PyLong_FromString(const char *str, char **pend, int base)` *Return value: New reference.*Return a new [`PyLongObject`](#c.PyLongObject "PyLongObject") based on the string value in *str*, which is interpreted according to the radix in *base*. If *pend* is non-`NULL`, *\*pend* will point to the first character in *str* which follows the representation of the number. If *base* is `0`, *str* is interpreted using the [Integer literals](../reference/lexical_analysis#integers) definition; in this case, leading zeros in a non-zero decimal number raises a [`ValueError`](../library/exceptions#ValueError "ValueError"). If *base* is not `0`, it must be between `2` and `36`, inclusive. Leading spaces and single underscores after a base specifier and between digits are ignored. If there are no digits, [`ValueError`](../library/exceptions#ValueError "ValueError") will be raised. `PyObject* PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)` *Return value: New reference.*Convert a sequence of Unicode digits to a Python integer value. Deprecated since version 3.3, will be removed in version 3.10: Part of the old-style [`Py_UNICODE`](unicode#c.Py_UNICODE "Py_UNICODE") API; please migrate to using [`PyLong_FromUnicodeObject()`](#c.PyLong_FromUnicodeObject "PyLong_FromUnicodeObject"). `PyObject* PyLong_FromUnicodeObject(PyObject *u, int base)` *Return value: New reference.*Convert a sequence of Unicode digits in the string *u* to a Python integer value. New in version 3.3. `PyObject* PyLong_FromVoidPtr(void *p)` *Return value: New reference.*Create a Python integer from the pointer *p*. The pointer value can be retrieved from the resulting value using [`PyLong_AsVoidPtr()`](#c.PyLong_AsVoidPtr "PyLong_AsVoidPtr"). `long PyLong_AsLong(PyObject *obj)` Return a C `long` representation of *obj*. If *obj* is not an instance of [`PyLongObject`](#c.PyLongObject "PyLongObject"), first call its [`__index__()`](../reference/datamodel#object.__index__ "object.__index__") or [`__int__()`](../reference/datamodel#object.__int__ "object.__int__") method (if present) to convert it to a [`PyLongObject`](#c.PyLongObject "PyLongObject"). Raise [`OverflowError`](../library/exceptions#OverflowError "OverflowError") if the value of *obj* is out of range for a `long`. Returns `-1` on error. Use [`PyErr_Occurred()`](exceptions#c.PyErr_Occurred "PyErr_Occurred") to disambiguate. Changed in version 3.8: Use [`__index__()`](../reference/datamodel#object.__index__ "object.__index__") if available. Deprecated since version 3.8: Using [`__int__()`](../reference/datamodel#object.__int__ "object.__int__") is deprecated. `long PyLong_AsLongAndOverflow(PyObject *obj, int *overflow)` Return a C `long` representation of *obj*. If *obj* is not an instance of [`PyLongObject`](#c.PyLongObject "PyLongObject"), first call its [`__index__()`](../reference/datamodel#object.__index__ "object.__index__") or [`__int__()`](../reference/datamodel#object.__int__ "object.__int__") method (if present) to convert it to a [`PyLongObject`](#c.PyLongObject "PyLongObject"). If the value of *obj* is greater than `LONG_MAX` or less than `LONG_MIN`, set *\*overflow* to `1` or `-1`, respectively, and return `-1`; otherwise, set *\*overflow* to `0`. If any other exception occurs set *\*overflow* to `0` and return `-1` as usual. Returns `-1` on error. Use [`PyErr_Occurred()`](exceptions#c.PyErr_Occurred "PyErr_Occurred") to disambiguate. Changed in version 3.8: Use [`__index__()`](../reference/datamodel#object.__index__ "object.__index__") if available. Deprecated since version 3.8: Using [`__int__()`](../reference/datamodel#object.__int__ "object.__int__") is deprecated. `long long PyLong_AsLongLong(PyObject *obj)` Return a C `long long` representation of *obj*. If *obj* is not an instance of [`PyLongObject`](#c.PyLongObject "PyLongObject"), first call its [`__index__()`](../reference/datamodel#object.__index__ "object.__index__") or [`__int__()`](../reference/datamodel#object.__int__ "object.__int__") method (if present) to convert it to a [`PyLongObject`](#c.PyLongObject "PyLongObject"). Raise [`OverflowError`](../library/exceptions#OverflowError "OverflowError") if the value of *obj* is out of range for a `long long`. Returns `-1` on error. Use [`PyErr_Occurred()`](exceptions#c.PyErr_Occurred "PyErr_Occurred") to disambiguate. Changed in version 3.8: Use [`__index__()`](../reference/datamodel#object.__index__ "object.__index__") if available. Deprecated since version 3.8: Using [`__int__()`](../reference/datamodel#object.__int__ "object.__int__") is deprecated. `long long PyLong_AsLongLongAndOverflow(PyObject *obj, int *overflow)` Return a C `long long` representation of *obj*. If *obj* is not an instance of [`PyLongObject`](#c.PyLongObject "PyLongObject"), first call its [`__index__()`](../reference/datamodel#object.__index__ "object.__index__") or [`__int__()`](../reference/datamodel#object.__int__ "object.__int__") method (if present) to convert it to a [`PyLongObject`](#c.PyLongObject "PyLongObject"). If the value of *obj* is greater than `LLONG_MAX` or less than `LLONG_MIN`, set *\*overflow* to `1` or `-1`, respectively, and return `-1`; otherwise, set *\*overflow* to `0`. If any other exception occurs set *\*overflow* to `0` and return `-1` as usual. Returns `-1` on error. Use [`PyErr_Occurred()`](exceptions#c.PyErr_Occurred "PyErr_Occurred") to disambiguate. New in version 3.2. Changed in version 3.8: Use [`__index__()`](../reference/datamodel#object.__index__ "object.__index__") if available. Deprecated since version 3.8: Using [`__int__()`](../reference/datamodel#object.__int__ "object.__int__") is deprecated. `Py_ssize_t PyLong_AsSsize_t(PyObject *pylong)` Return a C [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t") representation of *pylong*. *pylong* must be an instance of [`PyLongObject`](#c.PyLongObject "PyLongObject"). Raise [`OverflowError`](../library/exceptions#OverflowError "OverflowError") if the value of *pylong* is out of range for a [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t"). Returns `-1` on error. Use [`PyErr_Occurred()`](exceptions#c.PyErr_Occurred "PyErr_Occurred") to disambiguate. `unsigned long PyLong_AsUnsignedLong(PyObject *pylong)` Return a C `unsigned long` representation of *pylong*. *pylong* must be an instance of [`PyLongObject`](#c.PyLongObject "PyLongObject"). Raise [`OverflowError`](../library/exceptions#OverflowError "OverflowError") if the value of *pylong* is out of range for a `unsigned long`. Returns `(unsigned long)-1` on error. Use [`PyErr_Occurred()`](exceptions#c.PyErr_Occurred "PyErr_Occurred") to disambiguate. `size_t PyLong_AsSize_t(PyObject *pylong)` Return a C `size_t` representation of *pylong*. *pylong* must be an instance of [`PyLongObject`](#c.PyLongObject "PyLongObject"). Raise [`OverflowError`](../library/exceptions#OverflowError "OverflowError") if the value of *pylong* is out of range for a `size_t`. Returns `(size_t)-1` on error. Use [`PyErr_Occurred()`](exceptions#c.PyErr_Occurred "PyErr_Occurred") to disambiguate. `unsigned long long PyLong_AsUnsignedLongLong(PyObject *pylong)` Return a C `unsigned long long` representation of *pylong*. *pylong* must be an instance of [`PyLongObject`](#c.PyLongObject "PyLongObject"). Raise [`OverflowError`](../library/exceptions#OverflowError "OverflowError") if the value of *pylong* is out of range for an `unsigned long long`. Returns `(unsigned long long)-1` on error. Use [`PyErr_Occurred()`](exceptions#c.PyErr_Occurred "PyErr_Occurred") to disambiguate. Changed in version 3.1: A negative *pylong* now raises [`OverflowError`](../library/exceptions#OverflowError "OverflowError"), not [`TypeError`](../library/exceptions#TypeError "TypeError"). `unsigned long PyLong_AsUnsignedLongMask(PyObject *obj)` Return a C `unsigned long` representation of *obj*. If *obj* is not an instance of [`PyLongObject`](#c.PyLongObject "PyLongObject"), first call its [`__index__()`](../reference/datamodel#object.__index__ "object.__index__") or [`__int__()`](../reference/datamodel#object.__int__ "object.__int__") method (if present) to convert it to a [`PyLongObject`](#c.PyLongObject "PyLongObject"). If the value of *obj* is out of range for an `unsigned long`, return the reduction of that value modulo `ULONG_MAX + 1`. Returns `(unsigned long)-1` on error. Use [`PyErr_Occurred()`](exceptions#c.PyErr_Occurred "PyErr_Occurred") to disambiguate. Changed in version 3.8: Use [`__index__()`](../reference/datamodel#object.__index__ "object.__index__") if available. Deprecated since version 3.8: Using [`__int__()`](../reference/datamodel#object.__int__ "object.__int__") is deprecated. `unsigned long long PyLong_AsUnsignedLongLongMask(PyObject *obj)` Return a C `unsigned long long` representation of *obj*. If *obj* is not an instance of [`PyLongObject`](#c.PyLongObject "PyLongObject"), first call its [`__index__()`](../reference/datamodel#object.__index__ "object.__index__") or [`__int__()`](../reference/datamodel#object.__int__ "object.__int__") method (if present) to convert it to a [`PyLongObject`](#c.PyLongObject "PyLongObject"). If the value of *obj* is out of range for an `unsigned long long`, return the reduction of that value modulo `ULLONG_MAX + 1`. Returns `(unsigned long long)-1` on error. Use [`PyErr_Occurred()`](exceptions#c.PyErr_Occurred "PyErr_Occurred") to disambiguate. Changed in version 3.8: Use [`__index__()`](../reference/datamodel#object.__index__ "object.__index__") if available. Deprecated since version 3.8: Using [`__int__()`](../reference/datamodel#object.__int__ "object.__int__") is deprecated. `double PyLong_AsDouble(PyObject *pylong)` Return a C `double` representation of *pylong*. *pylong* must be an instance of [`PyLongObject`](#c.PyLongObject "PyLongObject"). Raise [`OverflowError`](../library/exceptions#OverflowError "OverflowError") if the value of *pylong* is out of range for a `double`. Returns `-1.0` on error. Use [`PyErr_Occurred()`](exceptions#c.PyErr_Occurred "PyErr_Occurred") to disambiguate. `void* PyLong_AsVoidPtr(PyObject *pylong)` Convert a Python integer *pylong* to a C `void` pointer. If *pylong* cannot be converted, an [`OverflowError`](../library/exceptions#OverflowError "OverflowError") will be raised. This is only assured to produce a usable `void` pointer for values created with [`PyLong_FromVoidPtr()`](#c.PyLong_FromVoidPtr "PyLong_FromVoidPtr"). Returns `NULL` on error. Use [`PyErr_Occurred()`](exceptions#c.PyErr_Occurred "PyErr_Occurred") to disambiguate. python Capsules Capsules ======== Refer to [Providing a C API for an Extension Module](../extending/extending#using-capsules) for more information on using these objects. New in version 3.1. `PyCapsule` This subtype of [`PyObject`](structures#c.PyObject "PyObject") represents an opaque value, useful for C extension modules who need to pass an opaque value (as a `void*` pointer) through Python code to other C code. It is often used to make a C function pointer defined in one module available to other modules, so the regular import mechanism can be used to access C APIs defined in dynamically loaded modules. `PyCapsule_Destructor` The type of a destructor callback for a capsule. Defined as: ``` typedef void (*PyCapsule_Destructor)(PyObject *); ``` See [`PyCapsule_New()`](#c.PyCapsule_New "PyCapsule_New") for the semantics of PyCapsule\_Destructor callbacks. `int PyCapsule_CheckExact(PyObject *p)` Return true if its argument is a [`PyCapsule`](#c.PyCapsule "PyCapsule"). This function always succeeds. `PyObject* PyCapsule_New(void *pointer, const char *name, PyCapsule_Destructor destructor)` *Return value: New reference.*Create a [`PyCapsule`](#c.PyCapsule "PyCapsule") encapsulating the *pointer*. The *pointer* argument may not be `NULL`. On failure, set an exception and return `NULL`. The *name* string may either be `NULL` or a pointer to a valid C string. If non-`NULL`, this string must outlive the capsule. (Though it is permitted to free it inside the *destructor*.) If the *destructor* argument is not `NULL`, it will be called with the capsule as its argument when it is destroyed. If this capsule will be stored as an attribute of a module, the *name* should be specified as `modulename.attributename`. This will enable other modules to import the capsule using [`PyCapsule_Import()`](#c.PyCapsule_Import "PyCapsule_Import"). `void* PyCapsule_GetPointer(PyObject *capsule, const char *name)` Retrieve the *pointer* stored in the capsule. On failure, set an exception and return `NULL`. The *name* parameter must compare exactly to the name stored in the capsule. If the name stored in the capsule is `NULL`, the *name* passed in must also be `NULL`. Python uses the C function `strcmp()` to compare capsule names. `PyCapsule_Destructor PyCapsule_GetDestructor(PyObject *capsule)` Return the current destructor stored in the capsule. On failure, set an exception and return `NULL`. It is legal for a capsule to have a `NULL` destructor. This makes a `NULL` return code somewhat ambiguous; use [`PyCapsule_IsValid()`](#c.PyCapsule_IsValid "PyCapsule_IsValid") or [`PyErr_Occurred()`](exceptions#c.PyErr_Occurred "PyErr_Occurred") to disambiguate. `void* PyCapsule_GetContext(PyObject *capsule)` Return the current context stored in the capsule. On failure, set an exception and return `NULL`. It is legal for a capsule to have a `NULL` context. This makes a `NULL` return code somewhat ambiguous; use [`PyCapsule_IsValid()`](#c.PyCapsule_IsValid "PyCapsule_IsValid") or [`PyErr_Occurred()`](exceptions#c.PyErr_Occurred "PyErr_Occurred") to disambiguate. `const char* PyCapsule_GetName(PyObject *capsule)` Return the current name stored in the capsule. On failure, set an exception and return `NULL`. It is legal for a capsule to have a `NULL` name. This makes a `NULL` return code somewhat ambiguous; use [`PyCapsule_IsValid()`](#c.PyCapsule_IsValid "PyCapsule_IsValid") or [`PyErr_Occurred()`](exceptions#c.PyErr_Occurred "PyErr_Occurred") to disambiguate. `void* PyCapsule_Import(const char *name, int no_block)` Import a pointer to a C object from a capsule attribute in a module. The *name* parameter should specify the full name to the attribute, as in `module.attribute`. The *name* stored in the capsule must match this string exactly. If *no\_block* is true, import the module without blocking (using [`PyImport_ImportModuleNoBlock()`](import#c.PyImport_ImportModuleNoBlock "PyImport_ImportModuleNoBlock")). If *no\_block* is false, import the module conventionally (using [`PyImport_ImportModule()`](import#c.PyImport_ImportModule "PyImport_ImportModule")). Return the capsule’s internal *pointer* on success. On failure, set an exception and return `NULL`. `int PyCapsule_IsValid(PyObject *capsule, const char *name)` Determines whether or not *capsule* is a valid capsule. A valid capsule is non-`NULL`, passes [`PyCapsule_CheckExact()`](#c.PyCapsule_CheckExact "PyCapsule_CheckExact"), has a non-`NULL` pointer stored in it, and its internal name matches the *name* parameter. (See [`PyCapsule_GetPointer()`](#c.PyCapsule_GetPointer "PyCapsule_GetPointer") for information on how capsule names are compared.) In other words, if [`PyCapsule_IsValid()`](#c.PyCapsule_IsValid "PyCapsule_IsValid") returns a true value, calls to any of the accessors (any function starting with `PyCapsule_Get()`) are guaranteed to succeed. Return a nonzero value if the object is valid and matches the name passed in. Return `0` otherwise. This function will not fail. `int PyCapsule_SetContext(PyObject *capsule, void *context)` Set the context pointer inside *capsule* to *context*. Return `0` on success. Return nonzero and set an exception on failure. `int PyCapsule_SetDestructor(PyObject *capsule, PyCapsule_Destructor destructor)` Set the destructor inside *capsule* to *destructor*. Return `0` on success. Return nonzero and set an exception on failure. `int PyCapsule_SetName(PyObject *capsule, const char *name)` Set the name inside *capsule* to *name*. If non-`NULL`, the name must outlive the capsule. If the previous *name* stored in the capsule was not `NULL`, no attempt is made to free it. Return `0` on success. Return nonzero and set an exception on failure. `int PyCapsule_SetPointer(PyObject *capsule, void *pointer)` Set the void pointer inside *capsule* to *pointer*. The pointer may not be `NULL`. Return `0` on success. Return nonzero and set an exception on failure.
programming_docs
python Mapping Protocol Mapping Protocol ================ See also [`PyObject_GetItem()`](object#c.PyObject_GetItem "PyObject_GetItem"), [`PyObject_SetItem()`](object#c.PyObject_SetItem "PyObject_SetItem") and [`PyObject_DelItem()`](object#c.PyObject_DelItem "PyObject_DelItem"). `int PyMapping_Check(PyObject *o)` Return `1` if the object provides the mapping protocol or supports slicing, and `0` otherwise. Note that it returns `1` for Python classes with a [`__getitem__()`](../reference/datamodel#object.__getitem__ "object.__getitem__") method, since in general it is impossible to determine what type of keys the class supports. This function always succeeds. `Py_ssize_t PyMapping_Size(PyObject *o)` `Py_ssize_t PyMapping_Length(PyObject *o)` Returns the number of keys in object *o* on success, and `-1` on failure. This is equivalent to the Python expression `len(o)`. `PyObject* PyMapping_GetItemString(PyObject *o, const char *key)` *Return value: New reference.*Return element of *o* corresponding to the string *key* or `NULL` on failure. This is the equivalent of the Python expression `o[key]`. See also [`PyObject_GetItem()`](object#c.PyObject_GetItem "PyObject_GetItem"). `int PyMapping_SetItemString(PyObject *o, const char *key, PyObject *v)` Map the string *key* to the value *v* in object *o*. Returns `-1` on failure. This is the equivalent of the Python statement `o[key] = v`. See also [`PyObject_SetItem()`](object#c.PyObject_SetItem "PyObject_SetItem"). This function *does not* steal a reference to *v*. `int PyMapping_DelItem(PyObject *o, PyObject *key)` Remove the mapping for the object *key* from the object *o*. Return `-1` on failure. This is equivalent to the Python statement `del o[key]`. This is an alias of [`PyObject_DelItem()`](object#c.PyObject_DelItem "PyObject_DelItem"). `int PyMapping_DelItemString(PyObject *o, const char *key)` Remove the mapping for the string *key* from the object *o*. Return `-1` on failure. This is equivalent to the Python statement `del o[key]`. `int PyMapping_HasKey(PyObject *o, PyObject *key)` Return `1` if the mapping object has the key *key* and `0` otherwise. This is equivalent to the Python expression `key in o`. This function always succeeds. Note that exceptions which occur while calling the [`__getitem__()`](../reference/datamodel#object.__getitem__ "object.__getitem__") method will get suppressed. To get error reporting use [`PyObject_GetItem()`](object#c.PyObject_GetItem "PyObject_GetItem") instead. `int PyMapping_HasKeyString(PyObject *o, const char *key)` Return `1` if the mapping object has the key *key* and `0` otherwise. This is equivalent to the Python expression `key in o`. This function always succeeds. Note that exceptions which occur while calling the [`__getitem__()`](../reference/datamodel#object.__getitem__ "object.__getitem__") method and creating a temporary string object will get suppressed. To get error reporting use [`PyMapping_GetItemString()`](#c.PyMapping_GetItemString "PyMapping_GetItemString") instead. `PyObject* PyMapping_Keys(PyObject *o)` *Return value: New reference.*On success, return a list of the keys in object *o*. On failure, return `NULL`. Changed in version 3.7: Previously, the function returned a list or a tuple. `PyObject* PyMapping_Values(PyObject *o)` *Return value: New reference.*On success, return a list of the values in object *o*. On failure, return `NULL`. Changed in version 3.7: Previously, the function returned a list or a tuple. `PyObject* PyMapping_Items(PyObject *o)` *Return value: New reference.*On success, return a list of the items in object *o*, where each item is a tuple containing a key-value pair. On failure, return `NULL`. Changed in version 3.7: Previously, the function returned a list or a tuple. python Object Protocol Object Protocol =============== `PyObject* Py_NotImplemented` The `NotImplemented` singleton, used to signal that an operation is not implemented for the given type combination. `Py_RETURN_NOTIMPLEMENTED` Properly handle returning [`Py_NotImplemented`](#c.Py_NotImplemented "Py_NotImplemented") from within a C function (that is, increment the reference count of NotImplemented and return it). `int PyObject_Print(PyObject *o, FILE *fp, int flags)` Print an object *o*, on file *fp*. Returns `-1` on error. The flags argument is used to enable certain printing options. The only option currently supported is `Py_PRINT_RAW`; if given, the [`str()`](../library/stdtypes#str "str") of the object is written instead of the [`repr()`](../library/functions#repr "repr"). `int PyObject_HasAttr(PyObject *o, PyObject *attr_name)` Returns `1` if *o* has the attribute *attr\_name*, and `0` otherwise. This is equivalent to the Python expression `hasattr(o, attr_name)`. This function always succeeds. Note that exceptions which occur while calling [`__getattr__()`](../reference/datamodel#object.__getattr__ "object.__getattr__") and [`__getattribute__()`](../reference/datamodel#object.__getattribute__ "object.__getattribute__") methods will get suppressed. To get error reporting use [`PyObject_GetAttr()`](#c.PyObject_GetAttr "PyObject_GetAttr") instead. `int PyObject_HasAttrString(PyObject *o, const char *attr_name)` Returns `1` if *o* has the attribute *attr\_name*, and `0` otherwise. This is equivalent to the Python expression `hasattr(o, attr_name)`. This function always succeeds. Note that exceptions which occur while calling [`__getattr__()`](../reference/datamodel#object.__getattr__ "object.__getattr__") and [`__getattribute__()`](../reference/datamodel#object.__getattribute__ "object.__getattribute__") methods and creating a temporary string object will get suppressed. To get error reporting use [`PyObject_GetAttrString()`](#c.PyObject_GetAttrString "PyObject_GetAttrString") instead. `PyObject* PyObject_GetAttr(PyObject *o, PyObject *attr_name)` *Return value: New reference.*Retrieve an attribute named *attr\_name* from object *o*. Returns the attribute value on success, or `NULL` on failure. This is the equivalent of the Python expression `o.attr_name`. `PyObject* PyObject_GetAttrString(PyObject *o, const char *attr_name)` *Return value: New reference.*Retrieve an attribute named *attr\_name* from object *o*. Returns the attribute value on success, or `NULL` on failure. This is the equivalent of the Python expression `o.attr_name`. `PyObject* PyObject_GenericGetAttr(PyObject *o, PyObject *name)` *Return value: New reference.*Generic attribute getter function that is meant to be put into a type object’s `tp_getattro` slot. It looks for a descriptor in the dictionary of classes in the object’s MRO as well as an attribute in the object’s [`__dict__`](../library/stdtypes#object.__dict__ "object.__dict__") (if present). As outlined in [Implementing Descriptors](../reference/datamodel#descriptors), data descriptors take preference over instance attributes, while non-data descriptors don’t. Otherwise, an [`AttributeError`](../library/exceptions#AttributeError "AttributeError") is raised. `int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v)` Set the value of the attribute named *attr\_name*, for object *o*, to the value *v*. Raise an exception and return `-1` on failure; return `0` on success. This is the equivalent of the Python statement `o.attr_name = v`. If *v* is `NULL`, the attribute is deleted. This behaviour is deprecated in favour of using [`PyObject_DelAttr()`](#c.PyObject_DelAttr "PyObject_DelAttr"), but there are currently no plans to remove it. `int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v)` Set the value of the attribute named *attr\_name*, for object *o*, to the value *v*. Raise an exception and return `-1` on failure; return `0` on success. This is the equivalent of the Python statement `o.attr_name = v`. If *v* is `NULL`, the attribute is deleted, but this feature is deprecated in favour of using [`PyObject_DelAttrString()`](#c.PyObject_DelAttrString "PyObject_DelAttrString"). `int PyObject_GenericSetAttr(PyObject *o, PyObject *name, PyObject *value)` Generic attribute setter and deleter function that is meant to be put into a type object’s [`tp_setattro`](typeobj#c.PyTypeObject.tp_setattro "PyTypeObject.tp_setattro") slot. It looks for a data descriptor in the dictionary of classes in the object’s MRO, and if found it takes preference over setting or deleting the attribute in the instance dictionary. Otherwise, the attribute is set or deleted in the object’s [`__dict__`](../library/stdtypes#object.__dict__ "object.__dict__") (if present). On success, `0` is returned, otherwise an [`AttributeError`](../library/exceptions#AttributeError "AttributeError") is raised and `-1` is returned. `int PyObject_DelAttr(PyObject *o, PyObject *attr_name)` Delete attribute named *attr\_name*, for object *o*. Returns `-1` on failure. This is the equivalent of the Python statement `del o.attr_name`. `int PyObject_DelAttrString(PyObject *o, const char *attr_name)` Delete attribute named *attr\_name*, for object *o*. Returns `-1` on failure. This is the equivalent of the Python statement `del o.attr_name`. `PyObject* PyObject_GenericGetDict(PyObject *o, void *context)` *Return value: New reference.*A generic implementation for the getter of a `__dict__` descriptor. It creates the dictionary if necessary. New in version 3.3. `int PyObject_GenericSetDict(PyObject *o, PyObject *value, void *context)` A generic implementation for the setter of a `__dict__` descriptor. This implementation does not allow the dictionary to be deleted. New in version 3.3. `PyObject* PyObject_RichCompare(PyObject *o1, PyObject *o2, int opid)` *Return value: New reference.*Compare the values of *o1* and *o2* using the operation specified by *opid*, which must be one of `Py_LT`, `Py_LE`, `Py_EQ`, `Py_NE`, `Py_GT`, or `Py_GE`, corresponding to `<`, `<=`, `==`, `!=`, `>`, or `>=` respectively. This is the equivalent of the Python expression `o1 op o2`, where `op` is the operator corresponding to *opid*. Returns the value of the comparison on success, or `NULL` on failure. `int PyObject_RichCompareBool(PyObject *o1, PyObject *o2, int opid)` Compare the values of *o1* and *o2* using the operation specified by *opid*, which must be one of `Py_LT`, `Py_LE`, `Py_EQ`, `Py_NE`, `Py_GT`, or `Py_GE`, corresponding to `<`, `<=`, `==`, `!=`, `>`, or `>=` respectively. Returns `-1` on error, `0` if the result is false, `1` otherwise. This is the equivalent of the Python expression `o1 op o2`, where `op` is the operator corresponding to *opid*. Note If *o1* and *o2* are the same object, [`PyObject_RichCompareBool()`](#c.PyObject_RichCompareBool "PyObject_RichCompareBool") will always return `1` for `Py_EQ` and `0` for `Py_NE`. `PyObject* PyObject_Repr(PyObject *o)` *Return value: New reference.*Compute a string representation of object *o*. Returns the string representation on success, `NULL` on failure. This is the equivalent of the Python expression `repr(o)`. Called by the [`repr()`](../library/functions#repr "repr") built-in function. Changed in version 3.4: This function now includes a debug assertion to help ensure that it does not silently discard an active exception. `PyObject* PyObject_ASCII(PyObject *o)` *Return value: New reference.*As [`PyObject_Repr()`](#c.PyObject_Repr "PyObject_Repr"), compute a string representation of object *o*, but escape the non-ASCII characters in the string returned by [`PyObject_Repr()`](#c.PyObject_Repr "PyObject_Repr") with `\x`, `\u` or `\U` escapes. This generates a string similar to that returned by [`PyObject_Repr()`](#c.PyObject_Repr "PyObject_Repr") in Python 2. Called by the [`ascii()`](../library/functions#ascii "ascii") built-in function. `PyObject* PyObject_Str(PyObject *o)` *Return value: New reference.*Compute a string representation of object *o*. Returns the string representation on success, `NULL` on failure. This is the equivalent of the Python expression `str(o)`. Called by the [`str()`](../library/stdtypes#str "str") built-in function and, therefore, by the [`print()`](../library/functions#print "print") function. Changed in version 3.4: This function now includes a debug assertion to help ensure that it does not silently discard an active exception. `PyObject* PyObject_Bytes(PyObject *o)` *Return value: New reference.*Compute a bytes representation of object *o*. `NULL` is returned on failure and a bytes object on success. This is equivalent to the Python expression `bytes(o)`, when *o* is not an integer. Unlike `bytes(o)`, a TypeError is raised when *o* is an integer instead of a zero-initialized bytes object. `int PyObject_IsSubclass(PyObject *derived, PyObject *cls)` Return `1` if the class *derived* is identical to or derived from the class *cls*, otherwise return `0`. In case of an error, return `-1`. If *cls* is a tuple, the check will be done against every entry in *cls*. The result will be `1` when at least one of the checks returns `1`, otherwise it will be `0`. If *cls* has a [`__subclasscheck__()`](../reference/datamodel#class.__subclasscheck__ "class.__subclasscheck__") method, it will be called to determine the subclass status as described in [**PEP 3119**](https://www.python.org/dev/peps/pep-3119). Otherwise, *derived* is a subclass of *cls* if it is a direct or indirect subclass, i.e. contained in `cls.__mro__`. Normally only class objects, i.e. instances of [`type`](../library/functions#type "type") or a derived class, are considered classes. However, objects can override this by having a `__bases__` attribute (which must be a tuple of base classes). `int PyObject_IsInstance(PyObject *inst, PyObject *cls)` Return `1` if *inst* is an instance of the class *cls* or a subclass of *cls*, or `0` if not. On error, returns `-1` and sets an exception. If *cls* is a tuple, the check will be done against every entry in *cls*. The result will be `1` when at least one of the checks returns `1`, otherwise it will be `0`. If *cls* has a [`__instancecheck__()`](../reference/datamodel#class.__instancecheck__ "class.__instancecheck__") method, it will be called to determine the subclass status as described in [**PEP 3119**](https://www.python.org/dev/peps/pep-3119). Otherwise, *inst* is an instance of *cls* if its class is a subclass of *cls*. An instance *inst* can override what is considered its class by having a `__class__` attribute. An object *cls* can override if it is considered a class, and what its base classes are, by having a `__bases__` attribute (which must be a tuple of base classes). `Py_hash_t PyObject_Hash(PyObject *o)` Compute and return the hash value of an object *o*. On failure, return `-1`. This is the equivalent of the Python expression `hash(o)`. Changed in version 3.2: The return type is now Py\_hash\_t. This is a signed integer the same size as [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t"). `Py_hash_t PyObject_HashNotImplemented(PyObject *o)` Set a [`TypeError`](../library/exceptions#TypeError "TypeError") indicating that `type(o)` is not hashable and return `-1`. This function receives special treatment when stored in a `tp_hash` slot, allowing a type to explicitly indicate to the interpreter that it is not hashable. `int PyObject_IsTrue(PyObject *o)` Returns `1` if the object *o* is considered to be true, and `0` otherwise. This is equivalent to the Python expression `not not o`. On failure, return `-1`. `int PyObject_Not(PyObject *o)` Returns `0` if the object *o* is considered to be true, and `1` otherwise. This is equivalent to the Python expression `not o`. On failure, return `-1`. `PyObject* PyObject_Type(PyObject *o)` *Return value: New reference.*When *o* is non-`NULL`, returns a type object corresponding to the object type of object *o*. On failure, raises [`SystemError`](../library/exceptions#SystemError "SystemError") and returns `NULL`. This is equivalent to the Python expression `type(o)`. This function increments the reference count of the return value. There’s really no reason to use this function instead of the [`Py_TYPE()`](structures#c.Py_TYPE "Py_TYPE") function, which returns a pointer of type [`PyTypeObject*`](type#c.PyTypeObject "PyTypeObject"), except when the incremented reference count is needed. `int PyObject_TypeCheck(PyObject *o, PyTypeObject *type)` Return true if the object *o* is of type *type* or a subtype of *type*. Both parameters must be non-`NULL`. `Py_ssize_t PyObject_Size(PyObject *o)` `Py_ssize_t PyObject_Length(PyObject *o)` Return the length of object *o*. If the object *o* provides either the sequence and mapping protocols, the sequence length is returned. On error, `-1` is returned. This is the equivalent to the Python expression `len(o)`. `Py_ssize_t PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)` Return an estimated length for the object *o*. First try to return its actual length, then an estimate using [`__length_hint__()`](../reference/datamodel#object.__length_hint__ "object.__length_hint__"), and finally return the default value. On error return `-1`. This is the equivalent to the Python expression `operator.length_hint(o, defaultvalue)`. New in version 3.4. `PyObject* PyObject_GetItem(PyObject *o, PyObject *key)` *Return value: New reference.*Return element of *o* corresponding to the object *key* or `NULL` on failure. This is the equivalent of the Python expression `o[key]`. `int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v)` Map the object *key* to the value *v*. Raise an exception and return `-1` on failure; return `0` on success. This is the equivalent of the Python statement `o[key] = v`. This function *does not* steal a reference to *v*. `int PyObject_DelItem(PyObject *o, PyObject *key)` Remove the mapping for the object *key* from the object *o*. Return `-1` on failure. This is equivalent to the Python statement `del o[key]`. `PyObject* PyObject_Dir(PyObject *o)` *Return value: New reference.*This is equivalent to the Python expression `dir(o)`, returning a (possibly empty) list of strings appropriate for the object argument, or `NULL` if there was an error. If the argument is `NULL`, this is like the Python `dir()`, returning the names of the current locals; in this case, if no execution frame is active then `NULL` is returned but [`PyErr_Occurred()`](exceptions#c.PyErr_Occurred "PyErr_Occurred") will return false. `PyObject* PyObject_GetIter(PyObject *o)` *Return value: New reference.*This is equivalent to the Python expression `iter(o)`. It returns a new iterator for the object argument, or the object itself if the object is already an iterator. Raises [`TypeError`](../library/exceptions#TypeError "TypeError") and returns `NULL` if the object cannot be iterated. python Introduction Introduction ============ The Application Programmer’s Interface to Python gives C and C++ programmers access to the Python interpreter at a variety of levels. The API is equally usable from C++, but for brevity it is generally referred to as the Python/C API. There are two fundamentally different reasons for using the Python/C API. The first reason is to write *extension modules* for specific purposes; these are C modules that extend the Python interpreter. This is probably the most common use. The second reason is to use Python as a component in a larger application; this technique is generally referred to as *embedding* Python in an application. Writing an extension module is a relatively well-understood process, where a “cookbook” approach works well. There are several tools that automate the process to some extent. While people have embedded Python in other applications since its early existence, the process of embedding Python is less straightforward than writing an extension. Many API functions are useful independent of whether you’re embedding or extending Python; moreover, most applications that embed Python will need to provide a custom extension as well, so it’s probably a good idea to become familiar with writing an extension before attempting to embed Python in a real application. Coding standards ---------------- If you’re writing C code for inclusion in CPython, you **must** follow the guidelines and standards defined in [**PEP 7**](https://www.python.org/dev/peps/pep-0007). These guidelines apply regardless of the version of Python you are contributing to. Following these conventions is not necessary for your own third party extension modules, unless you eventually expect to contribute them to Python. Include Files ------------- All function, type and macro definitions needed to use the Python/C API are included in your code by the following line: ``` #define PY_SSIZE_T_CLEAN #include <Python.h> ``` This implies inclusion of the following standard headers: `<stdio.h>`, `<string.h>`, `<errno.h>`, `<limits.h>`, `<assert.h>` and `<stdlib.h>` (if available). Note Since Python may define some pre-processor definitions which affect the standard headers on some systems, you *must* include `Python.h` before any standard headers are included. It is recommended to always define `PY_SSIZE_T_CLEAN` before including `Python.h`. See [Parsing arguments and building values](arg#arg-parsing) for a description of this macro. All user visible names defined by Python.h (except those defined by the included standard headers) have one of the prefixes `Py` or `_Py`. Names beginning with `_Py` are for internal use by the Python implementation and should not be used by extension writers. Structure member names do not have a reserved prefix. Note User code should never define names that begin with `Py` or `_Py`. This confuses the reader, and jeopardizes the portability of the user code to future Python versions, which may define additional names beginning with one of these prefixes. The header files are typically installed with Python. On Unix, these are located in the directories `*prefix*/include/pythonversion/` and `*exec\_prefix*/include/pythonversion/`, where `prefix` and `exec_prefix` are defined by the corresponding parameters to Python’s **configure** script and *version* is `'%d.%d' % sys.version_info[:2]`. On Windows, the headers are installed in `*prefix*/include`, where `prefix` is the installation directory specified to the installer. To include the headers, place both directories (if different) on your compiler’s search path for includes. Do *not* place the parent directories on the search path and then use `#include <pythonX.Y/Python.h>`; this will break on multi-platform builds since the platform independent headers under `prefix` include the platform specific headers from `exec_prefix`. C++ users should note that although the API is defined entirely using C, the header files properly declare the entry points to be `extern "C"`. As a result, there is no need to do anything special to use the API from C++. Useful macros ------------- Several useful macros are defined in the Python header files. Many are defined closer to where they are useful (e.g. [`Py_RETURN_NONE`](none#c.Py_RETURN_NONE "Py_RETURN_NONE")). Others of a more general utility are defined here. This is not necessarily a complete listing. `Py_UNREACHABLE()` Use this when you have a code path that cannot be reached by design. For example, in the `default:` clause in a `switch` statement for which all possible values are covered in `case` statements. Use this in places where you might be tempted to put an `assert(0)` or `abort()` call. In release mode, the macro helps the compiler to optimize the code, and avoids a warning about unreachable code. For example, the macro is implemented with `__builtin_unreachable()` on GCC in release mode. A use for `Py_UNREACHABLE()` is following a call a function that never returns but that is not declared `_Py_NO_RETURN`. If a code path is very unlikely code but can be reached under exceptional case, this macro must not be used. For example, under low memory condition or if a system call returns a value out of the expected range. In this case, it’s better to report the error to the caller. If the error cannot be reported to caller, [`Py_FatalError()`](sys#c.Py_FatalError "Py_FatalError") can be used. New in version 3.7. `Py_ABS(x)` Return the absolute value of `x`. New in version 3.3. `Py_MIN(x, y)` Return the minimum value between `x` and `y`. New in version 3.3. `Py_MAX(x, y)` Return the maximum value between `x` and `y`. New in version 3.3. `Py_STRINGIFY(x)` Convert `x` to a C string. E.g. `Py_STRINGIFY(123)` returns `"123"`. New in version 3.4. `Py_MEMBER_SIZE(type, member)` Return the size of a structure (`type`) `member` in bytes. New in version 3.6. `Py_CHARMASK(c)` Argument must be a character or an integer in the range [-128, 127] or [0, 255]. This macro returns `c` cast to an `unsigned char`. `Py_GETENV(s)` Like `getenv(s)`, but returns `NULL` if [`-E`](../using/cmdline#cmdoption-e) was passed on the command line (i.e. if `Py_IgnoreEnvironmentFlag` is set). `Py_UNUSED(arg)` Use this for unused arguments in a function definition to silence compiler warnings. Example: `int func(int a, int Py_UNUSED(b)) { return a; }`. New in version 3.4. `Py_DEPRECATED(version)` Use this for deprecated declarations. The macro must be placed before the symbol name. Example: ``` Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void); ``` Changed in version 3.8: MSVC support was added. `PyDoc_STRVAR(name, str)` Creates a variable with name `name` that can be used in docstrings. If Python is built without docstrings, the value will be empty. Use [`PyDoc_STRVAR`](#c.PyDoc_STRVAR "PyDoc_STRVAR") for docstrings to support building Python without docstrings, as specified in [**PEP 7**](https://www.python.org/dev/peps/pep-0007). Example: ``` PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element."); static PyMethodDef deque_methods[] = { // ... {"pop", (PyCFunction)deque_pop, METH_NOARGS, pop_doc}, // ... } ``` `PyDoc_STR(str)` Creates a docstring for the given input string or an empty string if docstrings are disabled. Use [`PyDoc_STR`](#c.PyDoc_STR "PyDoc_STR") in specifying docstrings to support building Python without docstrings, as specified in [**PEP 7**](https://www.python.org/dev/peps/pep-0007). Example: ``` static PyMethodDef pysqlite_row_methods[] = { {"keys", (PyCFunction)pysqlite_row_keys, METH_NOARGS, PyDoc_STR("Returns the keys of the row.")}, {NULL, NULL} }; ``` Objects, Types and Reference Counts ----------------------------------- Most Python/C API functions have one or more arguments as well as a return value of type [`PyObject*`](structures#c.PyObject "PyObject"). This type is a pointer to an opaque data type representing an arbitrary Python object. Since all Python object types are treated the same way by the Python language in most situations (e.g., assignments, scope rules, and argument passing), it is only fitting that they should be represented by a single C type. Almost all Python objects live on the heap: you never declare an automatic or static variable of type [`PyObject`](structures#c.PyObject "PyObject"), only pointer variables of type [`PyObject*`](structures#c.PyObject "PyObject") can be declared. The sole exception are the type objects; since these must never be deallocated, they are typically static [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject") objects. All Python objects (even Python integers) have a *type* and a *reference count*. An object’s type determines what kind of object it is (e.g., an integer, a list, or a user-defined function; there are many more as explained in [The standard type hierarchy](../reference/datamodel#types)). For each of the well-known types there is a macro to check whether an object is of that type; for instance, `PyList_Check(a)` is true if (and only if) the object pointed to by *a* is a Python list. ### Reference Counts The reference count is important because today’s computers have a finite (and often severely limited) memory size; it counts how many different places there are that have a reference to an object. Such a place could be another object, or a global (or static) C variable, or a local variable in some C function. When an object’s reference count becomes zero, the object is deallocated. If it contains references to other objects, their reference count is decremented. Those other objects may be deallocated in turn, if this decrement makes their reference count become zero, and so on. (There’s an obvious problem with objects that reference each other here; for now, the solution is “don’t do that.”) Reference counts are always manipulated explicitly. The normal way is to use the macro [`Py_INCREF()`](refcounting#c.Py_INCREF "Py_INCREF") to increment an object’s reference count by one, and [`Py_DECREF()`](refcounting#c.Py_DECREF "Py_DECREF") to decrement it by one. The [`Py_DECREF()`](refcounting#c.Py_DECREF "Py_DECREF") macro is considerably more complex than the incref one, since it must check whether the reference count becomes zero and then cause the object’s deallocator to be called. The deallocator is a function pointer contained in the object’s type structure. The type-specific deallocator takes care of decrementing the reference counts for other objects contained in the object if this is a compound object type, such as a list, as well as performing any additional finalization that’s needed. There’s no chance that the reference count can overflow; at least as many bits are used to hold the reference count as there are distinct memory locations in virtual memory (assuming `sizeof(Py_ssize_t) >= sizeof(void*)`). Thus, the reference count increment is a simple operation. It is not necessary to increment an object’s reference count for every local variable that contains a pointer to an object. In theory, the object’s reference count goes up by one when the variable is made to point to it and it goes down by one when the variable goes out of scope. However, these two cancel each other out, so at the end the reference count hasn’t changed. The only real reason to use the reference count is to prevent the object from being deallocated as long as our variable is pointing to it. If we know that there is at least one other reference to the object that lives at least as long as our variable, there is no need to increment the reference count temporarily. An important situation where this arises is in objects that are passed as arguments to C functions in an extension module that are called from Python; the call mechanism guarantees to hold a reference to every argument for the duration of the call. However, a common pitfall is to extract an object from a list and hold on to it for a while without incrementing its reference count. Some other operation might conceivably remove the object from the list, decrementing its reference count and possibly deallocating it. The real danger is that innocent-looking operations may invoke arbitrary Python code which could do this; there is a code path which allows control to flow back to the user from a [`Py_DECREF()`](refcounting#c.Py_DECREF "Py_DECREF"), so almost any operation is potentially dangerous. A safe approach is to always use the generic operations (functions whose name begins with `PyObject_`, `PyNumber_`, `PySequence_` or `PyMapping_`). These operations always increment the reference count of the object they return. This leaves the caller with the responsibility to call [`Py_DECREF()`](refcounting#c.Py_DECREF "Py_DECREF") when they are done with the result; this soon becomes second nature. #### Reference Count Details The reference count behavior of functions in the Python/C API is best explained in terms of *ownership of references*. Ownership pertains to references, never to objects (objects are not owned: they are always shared). “Owning a reference” means being responsible for calling Py\_DECREF on it when the reference is no longer needed. Ownership can also be transferred, meaning that the code that receives ownership of the reference then becomes responsible for eventually decref’ing it by calling [`Py_DECREF()`](refcounting#c.Py_DECREF "Py_DECREF") or [`Py_XDECREF()`](refcounting#c.Py_XDECREF "Py_XDECREF") when it’s no longer needed—or passing on this responsibility (usually to its caller). When a function passes ownership of a reference on to its caller, the caller is said to receive a *new* reference. When no ownership is transferred, the caller is said to *borrow* the reference. Nothing needs to be done for a borrowed reference. Conversely, when a calling function passes in a reference to an object, there are two possibilities: the function *steals* a reference to the object, or it does not. *Stealing a reference* means that when you pass a reference to a function, that function assumes that it now owns that reference, and you are not responsible for it any longer. Few functions steal references; the two notable exceptions are [`PyList_SetItem()`](list#c.PyList_SetItem "PyList_SetItem") and [`PyTuple_SetItem()`](tuple#c.PyTuple_SetItem "PyTuple_SetItem"), which steal a reference to the item (but not to the tuple or list into which the item is put!). These functions were designed to steal a reference because of a common idiom for populating a tuple or list with newly created objects; for example, the code to create the tuple `(1, 2, "three")` could look like this (forgetting about error handling for the moment; a better way to code this is shown below): ``` PyObject *t; t = PyTuple_New(3); PyTuple_SetItem(t, 0, PyLong_FromLong(1L)); PyTuple_SetItem(t, 1, PyLong_FromLong(2L)); PyTuple_SetItem(t, 2, PyUnicode_FromString("three")); ``` Here, [`PyLong_FromLong()`](long#c.PyLong_FromLong "PyLong_FromLong") returns a new reference which is immediately stolen by [`PyTuple_SetItem()`](tuple#c.PyTuple_SetItem "PyTuple_SetItem"). When you want to keep using an object although the reference to it will be stolen, use [`Py_INCREF()`](refcounting#c.Py_INCREF "Py_INCREF") to grab another reference before calling the reference-stealing function. Incidentally, [`PyTuple_SetItem()`](tuple#c.PyTuple_SetItem "PyTuple_SetItem") is the *only* way to set tuple items; [`PySequence_SetItem()`](sequence#c.PySequence_SetItem "PySequence_SetItem") and [`PyObject_SetItem()`](object#c.PyObject_SetItem "PyObject_SetItem") refuse to do this since tuples are an immutable data type. You should only use [`PyTuple_SetItem()`](tuple#c.PyTuple_SetItem "PyTuple_SetItem") for tuples that you are creating yourself. Equivalent code for populating a list can be written using [`PyList_New()`](list#c.PyList_New "PyList_New") and [`PyList_SetItem()`](list#c.PyList_SetItem "PyList_SetItem"). However, in practice, you will rarely use these ways of creating and populating a tuple or list. There’s a generic function, [`Py_BuildValue()`](arg#c.Py_BuildValue "Py_BuildValue"), that can create most common objects from C values, directed by a *format string*. For example, the above two blocks of code could be replaced by the following (which also takes care of the error checking): ``` PyObject *tuple, *list; tuple = Py_BuildValue("(iis)", 1, 2, "three"); list = Py_BuildValue("[iis]", 1, 2, "three"); ``` It is much more common to use [`PyObject_SetItem()`](object#c.PyObject_SetItem "PyObject_SetItem") and friends with items whose references you are only borrowing, like arguments that were passed in to the function you are writing. In that case, their behaviour regarding reference counts is much saner, since you don’t have to increment a reference count so you can give a reference away (“have it be stolen”). For example, this function sets all items of a list (actually, any mutable sequence) to a given item: ``` int set_all(PyObject *target, PyObject *item) { Py_ssize_t i, n; n = PyObject_Length(target); if (n < 0) return -1; for (i = 0; i < n; i++) { PyObject *index = PyLong_FromSsize_t(i); if (!index) return -1; if (PyObject_SetItem(target, index, item) < 0) { Py_DECREF(index); return -1; } Py_DECREF(index); } return 0; } ``` The situation is slightly different for function return values. While passing a reference to most functions does not change your ownership responsibilities for that reference, many functions that return a reference to an object give you ownership of the reference. The reason is simple: in many cases, the returned object is created on the fly, and the reference you get is the only reference to the object. Therefore, the generic functions that return object references, like [`PyObject_GetItem()`](object#c.PyObject_GetItem "PyObject_GetItem") and [`PySequence_GetItem()`](sequence#c.PySequence_GetItem "PySequence_GetItem"), always return a new reference (the caller becomes the owner of the reference). It is important to realize that whether you own a reference returned by a function depends on which function you call only — *the plumage* (the type of the object passed as an argument to the function) *doesn’t enter into it!* Thus, if you extract an item from a list using [`PyList_GetItem()`](list#c.PyList_GetItem "PyList_GetItem"), you don’t own the reference — but if you obtain the same item from the same list using [`PySequence_GetItem()`](sequence#c.PySequence_GetItem "PySequence_GetItem") (which happens to take exactly the same arguments), you do own a reference to the returned object. Here is an example of how you could write a function that computes the sum of the items in a list of integers; once using [`PyList_GetItem()`](list#c.PyList_GetItem "PyList_GetItem"), and once using [`PySequence_GetItem()`](sequence#c.PySequence_GetItem "PySequence_GetItem"). ``` long sum_list(PyObject *list) { Py_ssize_t i, n; long total = 0, value; PyObject *item; n = PyList_Size(list); if (n < 0) return -1; /* Not a list */ for (i = 0; i < n; i++) { item = PyList_GetItem(list, i); /* Can't fail */ if (!PyLong_Check(item)) continue; /* Skip non-integers */ value = PyLong_AsLong(item); if (value == -1 && PyErr_Occurred()) /* Integer too big to fit in a C long, bail out */ return -1; total += value; } return total; } ``` ``` long sum_sequence(PyObject *sequence) { Py_ssize_t i, n; long total = 0, value; PyObject *item; n = PySequence_Length(sequence); if (n < 0) return -1; /* Has no length */ for (i = 0; i < n; i++) { item = PySequence_GetItem(sequence, i); if (item == NULL) return -1; /* Not a sequence, or other failure */ if (PyLong_Check(item)) { value = PyLong_AsLong(item); Py_DECREF(item); if (value == -1 && PyErr_Occurred()) /* Integer too big to fit in a C long, bail out */ return -1; total += value; } else { Py_DECREF(item); /* Discard reference ownership */ } } return total; } ``` ### Types There are few other data types that play a significant role in the Python/C API; most are simple C types such as `int`, `long`, `double` and `char*`. A few structure types are used to describe static tables used to list the functions exported by a module or the data attributes of a new object type, and another is used to describe the value of a complex number. These will be discussed together with the functions that use them. `Py_ssize_t` A signed integral type such that `sizeof(Py_ssize_t) == sizeof(size_t)`. C99 doesn’t define such a thing directly (size\_t is an unsigned integral type). See [**PEP 353**](https://www.python.org/dev/peps/pep-0353) for details. `PY_SSIZE_T_MAX` is the largest positive value of type [`Py_ssize_t`](#c.Py_ssize_t "Py_ssize_t"). Exceptions ---------- The Python programmer only needs to deal with exceptions if specific error handling is required; unhandled exceptions are automatically propagated to the caller, then to the caller’s caller, and so on, until they reach the top-level interpreter, where they are reported to the user accompanied by a stack traceback. For C programmers, however, error checking always has to be explicit. All functions in the Python/C API can raise exceptions, unless an explicit claim is made otherwise in a function’s documentation. In general, when a function encounters an error, it sets an exception, discards any object references that it owns, and returns an error indicator. If not documented otherwise, this indicator is either `NULL` or `-1`, depending on the function’s return type. A few functions return a Boolean true/false result, with false indicating an error. Very few functions return no explicit error indicator or have an ambiguous return value, and require explicit testing for errors with [`PyErr_Occurred()`](exceptions#c.PyErr_Occurred "PyErr_Occurred"). These exceptions are always explicitly documented. Exception state is maintained in per-thread storage (this is equivalent to using global storage in an unthreaded application). A thread can be in one of two states: an exception has occurred, or not. The function [`PyErr_Occurred()`](exceptions#c.PyErr_Occurred "PyErr_Occurred") can be used to check for this: it returns a borrowed reference to the exception type object when an exception has occurred, and `NULL` otherwise. There are a number of functions to set the exception state: [`PyErr_SetString()`](exceptions#c.PyErr_SetString "PyErr_SetString") is the most common (though not the most general) function to set the exception state, and [`PyErr_Clear()`](exceptions#c.PyErr_Clear "PyErr_Clear") clears the exception state. The full exception state consists of three objects (all of which can be `NULL`): the exception type, the corresponding exception value, and the traceback. These have the same meanings as the Python result of `sys.exc_info()`; however, they are not the same: the Python objects represent the last exception being handled by a Python [`try`](../reference/compound_stmts#try) … [`except`](../reference/compound_stmts#except) statement, while the C level exception state only exists while an exception is being passed on between C functions until it reaches the Python bytecode interpreter’s main loop, which takes care of transferring it to `sys.exc_info()` and friends. Note that starting with Python 1.5, the preferred, thread-safe way to access the exception state from Python code is to call the function [`sys.exc_info()`](../library/sys#sys.exc_info "sys.exc_info"), which returns the per-thread exception state for Python code. Also, the semantics of both ways to access the exception state have changed so that a function which catches an exception will save and restore its thread’s exception state so as to preserve the exception state of its caller. This prevents common bugs in exception handling code caused by an innocent-looking function overwriting the exception being handled; it also reduces the often unwanted lifetime extension for objects that are referenced by the stack frames in the traceback. As a general principle, a function that calls another function to perform some task should check whether the called function raised an exception, and if so, pass the exception state on to its caller. It should discard any object references that it owns, and return an error indicator, but it should *not* set another exception — that would overwrite the exception that was just raised, and lose important information about the exact cause of the error. A simple example of detecting exceptions and passing them on is shown in the `sum_sequence()` example above. It so happens that this example doesn’t need to clean up any owned references when it detects an error. The following example function shows some error cleanup. First, to remind you why you like Python, we show the equivalent Python code: ``` def incr_item(dict, key): try: item = dict[key] except KeyError: item = 0 dict[key] = item + 1 ``` Here is the corresponding C code, in all its glory: ``` int incr_item(PyObject *dict, PyObject *key) { /* Objects all initialized to NULL for Py_XDECREF */ PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL; int rv = -1; /* Return value initialized to -1 (failure) */ item = PyObject_GetItem(dict, key); if (item == NULL) { /* Handle KeyError only: */ if (!PyErr_ExceptionMatches(PyExc_KeyError)) goto error; /* Clear the error and use zero: */ PyErr_Clear(); item = PyLong_FromLong(0L); if (item == NULL) goto error; } const_one = PyLong_FromLong(1L); if (const_one == NULL) goto error; incremented_item = PyNumber_Add(item, const_one); if (incremented_item == NULL) goto error; if (PyObject_SetItem(dict, key, incremented_item) < 0) goto error; rv = 0; /* Success */ /* Continue with cleanup code */ error: /* Cleanup code, shared by success and failure path */ /* Use Py_XDECREF() to ignore NULL references */ Py_XDECREF(item); Py_XDECREF(const_one); Py_XDECREF(incremented_item); return rv; /* -1 for error, 0 for success */ } ``` This example represents an endorsed use of the `goto` statement in C! It illustrates the use of [`PyErr_ExceptionMatches()`](exceptions#c.PyErr_ExceptionMatches "PyErr_ExceptionMatches") and [`PyErr_Clear()`](exceptions#c.PyErr_Clear "PyErr_Clear") to handle specific exceptions, and the use of [`Py_XDECREF()`](refcounting#c.Py_XDECREF "Py_XDECREF") to dispose of owned references that may be `NULL` (note the `'X'` in the name; [`Py_DECREF()`](refcounting#c.Py_DECREF "Py_DECREF") would crash when confronted with a `NULL` reference). It is important that the variables used to hold owned references are initialized to `NULL` for this to work; likewise, the proposed return value is initialized to `-1` (failure) and only set to success after the final call made is successful. Embedding Python ---------------- The one important task that only embedders (as opposed to extension writers) of the Python interpreter have to worry about is the initialization, and possibly the finalization, of the Python interpreter. Most functionality of the interpreter can only be used after the interpreter has been initialized. The basic initialization function is [`Py_Initialize()`](init#c.Py_Initialize "Py_Initialize"). This initializes the table of loaded modules, and creates the fundamental modules [`builtins`](../library/builtins#module-builtins "builtins: The module that provides the built-in namespace."), [`__main__`](../library/__main__#module-__main__ "__main__: The environment where the top-level script is run."), and [`sys`](../library/sys#module-sys "sys: Access system-specific parameters and functions."). It also initializes the module search path (`sys.path`). [`Py_Initialize()`](init#c.Py_Initialize "Py_Initialize") does not set the “script argument list” (`sys.argv`). If this variable is needed by Python code that will be executed later, it must be set explicitly with a call to `PySys_SetArgvEx(argc, argv, updatepath)` after the call to [`Py_Initialize()`](init#c.Py_Initialize "Py_Initialize"). On most systems (in particular, on Unix and Windows, although the details are slightly different), [`Py_Initialize()`](init#c.Py_Initialize "Py_Initialize") calculates the module search path based upon its best guess for the location of the standard Python interpreter executable, assuming that the Python library is found in a fixed location relative to the Python interpreter executable. In particular, it looks for a directory named `lib/python*X.Y*` relative to the parent directory where the executable named `python` is found on the shell command search path (the environment variable `PATH`). For instance, if the Python executable is found in `/usr/local/bin/python`, it will assume that the libraries are in `/usr/local/lib/python*X.Y*`. (In fact, this particular path is also the “fallback” location, used when no executable file named `python` is found along `PATH`.) The user can override this behavior by setting the environment variable [`PYTHONHOME`](../using/cmdline#envvar-PYTHONHOME), or insert additional directories in front of the standard path by setting [`PYTHONPATH`](../using/cmdline#envvar-PYTHONPATH). The embedding application can steer the search by calling `Py_SetProgramName(file)` *before* calling [`Py_Initialize()`](init#c.Py_Initialize "Py_Initialize"). Note that [`PYTHONHOME`](../using/cmdline#envvar-PYTHONHOME) still overrides this and [`PYTHONPATH`](../using/cmdline#envvar-PYTHONPATH) is still inserted in front of the standard path. An application that requires total control has to provide its own implementation of [`Py_GetPath()`](init#c.Py_GetPath "Py_GetPath"), [`Py_GetPrefix()`](init#c.Py_GetPrefix "Py_GetPrefix"), [`Py_GetExecPrefix()`](init#c.Py_GetExecPrefix "Py_GetExecPrefix"), and [`Py_GetProgramFullPath()`](init#c.Py_GetProgramFullPath "Py_GetProgramFullPath") (all defined in `Modules/getpath.c`). Sometimes, it is desirable to “uninitialize” Python. For instance, the application may want to start over (make another call to [`Py_Initialize()`](init#c.Py_Initialize "Py_Initialize")) or the application is simply done with its use of Python and wants to free memory allocated by Python. This can be accomplished by calling [`Py_FinalizeEx()`](init#c.Py_FinalizeEx "Py_FinalizeEx"). The function [`Py_IsInitialized()`](init#c.Py_IsInitialized "Py_IsInitialized") returns true if Python is currently in the initialized state. More information about these functions is given in a later chapter. Notice that [`Py_FinalizeEx()`](init#c.Py_FinalizeEx "Py_FinalizeEx") does *not* free all memory allocated by the Python interpreter, e.g. memory allocated by extension modules currently cannot be released. Debugging Builds ---------------- Python can be built with several macros to enable extra checks of the interpreter and extension modules. These checks tend to add a large amount of overhead to the runtime so they are not enabled by default. A full list of the various types of debugging builds is in the file `Misc/SpecialBuilds.txt` in the Python source distribution. Builds are available that support tracing of reference counts, debugging the memory allocator, or low-level profiling of the main interpreter loop. Only the most frequently-used builds will be described in the remainder of this section. Compiling the interpreter with the `Py_DEBUG` macro defined produces what is generally meant by “a debug build” of Python. `Py_DEBUG` is enabled in the Unix build by adding `--with-pydebug` to the `./configure` command. It is also implied by the presence of the not-Python-specific `_DEBUG` macro. When `Py_DEBUG` is enabled in the Unix build, compiler optimization is disabled. In addition to the reference count debugging described below, the following extra checks are performed: * Extra checks are added to the object allocator. * Extra checks are added to the parser and compiler. * Downcasts from wide types to narrow types are checked for loss of information. * A number of assertions are added to the dictionary and set implementations. In addition, the set object acquires a `test_c_api()` method. * Sanity checks of the input arguments are added to frame creation. * The storage for ints is initialized with a known invalid pattern to catch reference to uninitialized digits. * Low-level tracing and extra exception checking are added to the runtime virtual machine. * Extra checks are added to the memory arena implementation. * Extra debugging is added to the thread module. There may be additional checks not mentioned here. Defining `Py_TRACE_REFS` enables reference tracing. When defined, a circular doubly linked list of active objects is maintained by adding two extra fields to every [`PyObject`](structures#c.PyObject "PyObject"). Total allocations are tracked as well. Upon exit, all existing references are printed. (In interactive mode this happens after every statement run by the interpreter.) Implied by `Py_DEBUG`. Please refer to `Misc/SpecialBuilds.txt` in the Python source distribution for more detailed information.
programming_docs
python Exception Handling Exception Handling ================== The functions described in this chapter will let you handle and raise Python exceptions. It is important to understand some of the basics of Python exception handling. It works somewhat like the POSIX `errno` variable: there is a global indicator (per thread) of the last error that occurred. Most C API functions don’t clear this on success, but will set it to indicate the cause of the error on failure. Most C API functions also return an error indicator, usually `NULL` if they are supposed to return a pointer, or `-1` if they return an integer (exception: the `PyArg_*()` functions return `1` for success and `0` for failure). Concretely, the error indicator consists of three object pointers: the exception’s type, the exception’s value, and the traceback object. Any of those pointers can be `NULL` if non-set (although some combinations are forbidden, for example you can’t have a non-`NULL` traceback if the exception type is `NULL`). When a function must fail because some function it called failed, it generally doesn’t set the error indicator; the function it called already set it. It is responsible for either handling the error and clearing the exception or returning after cleaning up any resources it holds (such as object references or memory allocations); it should *not* continue normally if it is not prepared to handle the error. If returning due to an error, it is important to indicate to the caller that an error has been set. If the error is not handled or carefully propagated, additional calls into the Python/C API may not behave as intended and may fail in mysterious ways. Note The error indicator is **not** the result of [`sys.exc_info()`](../library/sys#sys.exc_info "sys.exc_info"). The former corresponds to an exception that is not yet caught (and is therefore still propagating), while the latter returns an exception after it is caught (and has therefore stopped propagating). Printing and clearing --------------------- `void PyErr_Clear()` Clear the error indicator. If the error indicator is not set, there is no effect. `void PyErr_PrintEx(int set_sys_last_vars)` Print a standard traceback to `sys.stderr` and clear the error indicator. **Unless** the error is a `SystemExit`, in that case no traceback is printed and the Python process will exit with the error code specified by the `SystemExit` instance. Call this function **only** when the error indicator is set. Otherwise it will cause a fatal error! If *set\_sys\_last\_vars* is nonzero, the variables [`sys.last_type`](../library/sys#sys.last_type "sys.last_type"), [`sys.last_value`](../library/sys#sys.last_value "sys.last_value") and [`sys.last_traceback`](../library/sys#sys.last_traceback "sys.last_traceback") will be set to the type, value and traceback of the printed exception, respectively. `void PyErr_Print()` Alias for `PyErr_PrintEx(1)`. `void PyErr_WriteUnraisable(PyObject *obj)` Call [`sys.unraisablehook()`](../library/sys#sys.unraisablehook "sys.unraisablehook") using the current exception and *obj* argument. This utility function prints a warning message to `sys.stderr` when an exception has been set but it is impossible for the interpreter to actually raise the exception. It is used, for example, when an exception occurs in an [`__del__()`](../reference/datamodel#object.__del__ "object.__del__") method. The function is called with a single argument *obj* that identifies the context in which the unraisable exception occurred. If possible, the repr of *obj* will be printed in the warning message. An exception must be set when calling this function. Raising exceptions ------------------ These functions help you set the current thread’s error indicator. For convenience, some of these functions will always return a `NULL` pointer for use in a `return` statement. `void PyErr_SetString(PyObject *type, const char *message)` This is the most common way to set the error indicator. The first argument specifies the exception type; it is normally one of the standard exceptions, e.g. `PyExc_RuntimeError`. You need not increment its reference count. The second argument is an error message; it is decoded from `'utf-8'`. `void PyErr_SetObject(PyObject *type, PyObject *value)` This function is similar to [`PyErr_SetString()`](#c.PyErr_SetString "PyErr_SetString") but lets you specify an arbitrary Python object for the “value” of the exception. `PyObject* PyErr_Format(PyObject *exception, const char *format, ...)` *Return value: Always NULL.*This function sets the error indicator and returns `NULL`. *exception* should be a Python exception class. The *format* and subsequent parameters help format the error message; they have the same meaning and values as in [`PyUnicode_FromFormat()`](unicode#c.PyUnicode_FromFormat "PyUnicode_FromFormat"). *format* is an ASCII-encoded string. `PyObject* PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)` *Return value: Always NULL.*Same as [`PyErr_Format()`](#c.PyErr_Format "PyErr_Format"), but taking a `va_list` argument rather than a variable number of arguments. New in version 3.5. `void PyErr_SetNone(PyObject *type)` This is a shorthand for `PyErr_SetObject(type, Py_None)`. `int PyErr_BadArgument()` This is a shorthand for `PyErr_SetString(PyExc_TypeError, message)`, where *message* indicates that a built-in operation was invoked with an illegal argument. It is mostly for internal use. `PyObject* PyErr_NoMemory()` *Return value: Always NULL.*This is a shorthand for `PyErr_SetNone(PyExc_MemoryError)`; it returns `NULL` so an object allocation function can write `return PyErr_NoMemory();` when it runs out of memory. `PyObject* PyErr_SetFromErrno(PyObject *type)` *Return value: Always NULL.*This is a convenience function to raise an exception when a C library function has returned an error and set the C variable `errno`. It constructs a tuple object whose first item is the integer `errno` value and whose second item is the corresponding error message (gotten from `strerror()`), and then calls `PyErr_SetObject(type, object)`. On Unix, when the `errno` value is `EINTR`, indicating an interrupted system call, this calls [`PyErr_CheckSignals()`](#c.PyErr_CheckSignals "PyErr_CheckSignals"), and if that set the error indicator, leaves it set to that. The function always returns `NULL`, so a wrapper function around a system call can write `return PyErr_SetFromErrno(type);` when the system call returns an error. `PyObject* PyErr_SetFromErrnoWithFilenameObject(PyObject *type, PyObject *filenameObject)` *Return value: Always NULL.*Similar to [`PyErr_SetFromErrno()`](#c.PyErr_SetFromErrno "PyErr_SetFromErrno"), with the additional behavior that if *filenameObject* is not `NULL`, it is passed to the constructor of *type* as a third parameter. In the case of [`OSError`](../library/exceptions#OSError "OSError") exception, this is used to define the `filename` attribute of the exception instance. `PyObject* PyErr_SetFromErrnoWithFilenameObjects(PyObject *type, PyObject *filenameObject, PyObject *filenameObject2)` *Return value: Always NULL.*Similar to [`PyErr_SetFromErrnoWithFilenameObject()`](#c.PyErr_SetFromErrnoWithFilenameObject "PyErr_SetFromErrnoWithFilenameObject"), but takes a second filename object, for raising errors when a function that takes two filenames fails. New in version 3.4. `PyObject* PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename)` *Return value: Always NULL.*Similar to [`PyErr_SetFromErrnoWithFilenameObject()`](#c.PyErr_SetFromErrnoWithFilenameObject "PyErr_SetFromErrnoWithFilenameObject"), but the filename is given as a C string. *filename* is decoded from the filesystem encoding ([`os.fsdecode()`](../library/os#os.fsdecode "os.fsdecode")). `PyObject* PyErr_SetFromWindowsErr(int ierr)` *Return value: Always NULL.*This is a convenience function to raise [`WindowsError`](../library/exceptions#WindowsError "WindowsError"). If called with *ierr* of `0`, the error code returned by a call to `GetLastError()` is used instead. It calls the Win32 function `FormatMessage()` to retrieve the Windows description of error code given by *ierr* or `GetLastError()`, then it constructs a tuple object whose first item is the *ierr* value and whose second item is the corresponding error message (gotten from `FormatMessage()`), and then calls `PyErr_SetObject(PyExc_WindowsError, object)`. This function always returns `NULL`. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Windows. `PyObject* PyErr_SetExcFromWindowsErr(PyObject *type, int ierr)` *Return value: Always NULL.*Similar to [`PyErr_SetFromWindowsErr()`](#c.PyErr_SetFromWindowsErr "PyErr_SetFromWindowsErr"), with an additional parameter specifying the exception type to be raised. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Windows. `PyObject* PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename)` *Return value: Always NULL.*Similar to `PyErr_SetFromWindowsErrWithFilenameObject()`, but the filename is given as a C string. *filename* is decoded from the filesystem encoding ([`os.fsdecode()`](../library/os#os.fsdecode "os.fsdecode")). [Availability](https://docs.python.org/3.9/library/intro.html#availability): Windows. `PyObject* PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject *type, int ierr, PyObject *filename)` *Return value: Always NULL.*Similar to `PyErr_SetFromWindowsErrWithFilenameObject()`, with an additional parameter specifying the exception type to be raised. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Windows. `PyObject* PyErr_SetExcFromWindowsErrWithFilenameObjects(PyObject *type, int ierr, PyObject *filename, PyObject *filename2)` *Return value: Always NULL.*Similar to [`PyErr_SetExcFromWindowsErrWithFilenameObject()`](#c.PyErr_SetExcFromWindowsErrWithFilenameObject "PyErr_SetExcFromWindowsErrWithFilenameObject"), but accepts a second filename object. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Windows. New in version 3.4. `PyObject* PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, const char *filename)` *Return value: Always NULL.*Similar to [`PyErr_SetFromWindowsErrWithFilename()`](#c.PyErr_SetFromWindowsErrWithFilename "PyErr_SetFromWindowsErrWithFilename"), with an additional parameter specifying the exception type to be raised. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Windows. `PyObject* PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)` *Return value: Always NULL.*This is a convenience function to raise [`ImportError`](../library/exceptions#ImportError "ImportError"). *msg* will be set as the exception’s message string. *name* and *path*, both of which can be `NULL`, will be set as the [`ImportError`](../library/exceptions#ImportError "ImportError")’s respective `name` and `path` attributes. New in version 3.3. `PyObject* PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg, PyObject *name, PyObject *path)` *Return value: Always NULL.*Much like [`PyErr_SetImportError()`](#c.PyErr_SetImportError "PyErr_SetImportError") but this function allows for specifying a subclass of [`ImportError`](../library/exceptions#ImportError "ImportError") to raise. New in version 3.6. `void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)` Set file, line, and offset information for the current exception. If the current exception is not a [`SyntaxError`](../library/exceptions#SyntaxError "SyntaxError"), then it sets additional attributes, which make the exception printing subsystem think the exception is a [`SyntaxError`](../library/exceptions#SyntaxError "SyntaxError"). New in version 3.4. `void PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)` Like [`PyErr_SyntaxLocationObject()`](#c.PyErr_SyntaxLocationObject "PyErr_SyntaxLocationObject"), but *filename* is a byte string decoded from the filesystem encoding ([`os.fsdecode()`](../library/os#os.fsdecode "os.fsdecode")). New in version 3.2. `void PyErr_SyntaxLocation(const char *filename, int lineno)` Like [`PyErr_SyntaxLocationEx()`](#c.PyErr_SyntaxLocationEx "PyErr_SyntaxLocationEx"), but the *col\_offset* parameter is omitted. `void PyErr_BadInternalCall()` This is a shorthand for `PyErr_SetString(PyExc_SystemError, message)`, where *message* indicates that an internal operation (e.g. a Python/C API function) was invoked with an illegal argument. It is mostly for internal use. Issuing warnings ---------------- Use these functions to issue warnings from C code. They mirror similar functions exported by the Python [`warnings`](../library/warnings#module-warnings "warnings: Issue warning messages and control their disposition.") module. They normally print a warning message to *sys.stderr*; however, it is also possible that the user has specified that warnings are to be turned into errors, and in that case they will raise an exception. It is also possible that the functions raise an exception because of a problem with the warning machinery. The return value is `0` if no exception is raised, or `-1` if an exception is raised. (It is not possible to determine whether a warning message is actually printed, nor what the reason is for the exception; this is intentional.) If an exception is raised, the caller should do its normal exception handling (for example, [`Py_DECREF()`](refcounting#c.Py_DECREF "Py_DECREF") owned references and return an error value). `int PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level)` Issue a warning message. The *category* argument is a warning category (see below) or `NULL`; the *message* argument is a UTF-8 encoded string. *stack\_level* is a positive number giving a number of stack frames; the warning will be issued from the currently executing line of code in that stack frame. A *stack\_level* of 1 is the function calling [`PyErr_WarnEx()`](#c.PyErr_WarnEx "PyErr_WarnEx"), 2 is the function above that, and so forth. Warning categories must be subclasses of `PyExc_Warning`; `PyExc_Warning` is a subclass of `PyExc_Exception`; the default warning category is `PyExc_RuntimeWarning`. The standard Python warning categories are available as global variables whose names are enumerated at [Standard Warning Categories](#standardwarningcategories). For information about warning control, see the documentation for the [`warnings`](../library/warnings#module-warnings "warnings: Issue warning messages and control their disposition.") module and the [`-W`](../using/cmdline#cmdoption-w) option in the command line documentation. There is no C API for warning control. `int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry)` Issue a warning message with explicit control over all warning attributes. This is a straightforward wrapper around the Python function [`warnings.warn_explicit()`](../library/warnings#warnings.warn_explicit "warnings.warn_explicit"); see there for more information. The *module* and *registry* arguments may be set to `NULL` to get the default effect described there. New in version 3.4. `int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const char *module, PyObject *registry)` Similar to [`PyErr_WarnExplicitObject()`](#c.PyErr_WarnExplicitObject "PyErr_WarnExplicitObject") except that *message* and *module* are UTF-8 encoded strings, and *filename* is decoded from the filesystem encoding ([`os.fsdecode()`](../library/os#os.fsdecode "os.fsdecode")). `int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...)` Function similar to [`PyErr_WarnEx()`](#c.PyErr_WarnEx "PyErr_WarnEx"), but use [`PyUnicode_FromFormat()`](unicode#c.PyUnicode_FromFormat "PyUnicode_FromFormat") to format the warning message. *format* is an ASCII-encoded string. New in version 3.2. `int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...)` Function similar to [`PyErr_WarnFormat()`](#c.PyErr_WarnFormat "PyErr_WarnFormat"), but *category* is [`ResourceWarning`](../library/exceptions#ResourceWarning "ResourceWarning") and it passes *source* to `warnings.WarningMessage()`. New in version 3.6. Querying the error indicator ---------------------------- `PyObject* PyErr_Occurred()` *Return value: Borrowed reference.*Test whether the error indicator is set. If set, return the exception *type* (the first argument to the last call to one of the `PyErr_Set*()` functions or to [`PyErr_Restore()`](#c.PyErr_Restore "PyErr_Restore")). If not set, return `NULL`. You do not own a reference to the return value, so you do not need to [`Py_DECREF()`](refcounting#c.Py_DECREF "Py_DECREF") it. The caller must hold the GIL. Note Do not compare the return value to a specific exception; use [`PyErr_ExceptionMatches()`](#c.PyErr_ExceptionMatches "PyErr_ExceptionMatches") instead, shown below. (The comparison could easily fail since the exception may be an instance instead of a class, in the case of a class exception, or it may be a subclass of the expected exception.) `int PyErr_ExceptionMatches(PyObject *exc)` Equivalent to `PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)`. This should only be called when an exception is actually set; a memory access violation will occur if no exception has been raised. `int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc)` Return true if the *given* exception matches the exception type in *exc*. If *exc* is a class object, this also returns true when *given* is an instance of a subclass. If *exc* is a tuple, all exception types in the tuple (and recursively in subtuples) are searched for a match. `void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)` Retrieve the error indicator into three variables whose addresses are passed. If the error indicator is not set, set all three variables to `NULL`. If it is set, it will be cleared and you own a reference to each object retrieved. The value and traceback object may be `NULL` even when the type object is not. Note This function is normally only used by code that needs to catch exceptions or by code that needs to save and restore the error indicator temporarily, e.g.: ``` { PyObject *type, *value, *traceback; PyErr_Fetch(&type, &value, &traceback); /* ... code that might produce other errors ... */ PyErr_Restore(type, value, traceback); } ``` `void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)` Set the error indicator from the three objects. If the error indicator is already set, it is cleared first. If the objects are `NULL`, the error indicator is cleared. Do not pass a `NULL` type and non-`NULL` value or traceback. The exception type should be a class. Do not pass an invalid exception type or value. (Violating these rules will cause subtle problems later.) This call takes away a reference to each object: you must own a reference to each object before the call and after the call you no longer own these references. (If you don’t understand this, don’t use this function. I warned you.) Note This function is normally only used by code that needs to save and restore the error indicator temporarily. Use [`PyErr_Fetch()`](#c.PyErr_Fetch "PyErr_Fetch") to save the current error indicator. `void PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)` Under certain circumstances, the values returned by [`PyErr_Fetch()`](#c.PyErr_Fetch "PyErr_Fetch") below can be “unnormalized”, meaning that `*exc` is a class object but `*val` is not an instance of the same class. This function can be used to instantiate the class in that case. If the values are already normalized, nothing happens. The delayed normalization is implemented to improve performance. Note This function *does not* implicitly set the `__traceback__` attribute on the exception value. If setting the traceback appropriately is desired, the following additional snippet is needed: ``` if (tb != NULL) { PyException_SetTraceback(val, tb); } ``` `void PyErr_GetExcInfo(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)` Retrieve the exception info, as known from `sys.exc_info()`. This refers to an exception that was *already caught*, not to an exception that was freshly raised. Returns new references for the three objects, any of which may be `NULL`. Does not modify the exception info state. Note This function is not normally used by code that wants to handle exceptions. Rather, it can be used when code needs to save and restore the exception state temporarily. Use [`PyErr_SetExcInfo()`](#c.PyErr_SetExcInfo "PyErr_SetExcInfo") to restore or clear the exception state. New in version 3.3. `void PyErr_SetExcInfo(PyObject *type, PyObject *value, PyObject *traceback)` Set the exception info, as known from `sys.exc_info()`. This refers to an exception that was *already caught*, not to an exception that was freshly raised. This function steals the references of the arguments. To clear the exception state, pass `NULL` for all three arguments. For general rules about the three arguments, see [`PyErr_Restore()`](#c.PyErr_Restore "PyErr_Restore"). Note This function is not normally used by code that wants to handle exceptions. Rather, it can be used when code needs to save and restore the exception state temporarily. Use [`PyErr_GetExcInfo()`](#c.PyErr_GetExcInfo "PyErr_GetExcInfo") to read the exception state. New in version 3.3. Signal Handling --------------- `int PyErr_CheckSignals()` This function interacts with Python’s signal handling. It checks whether a signal has been sent to the processes and if so, invokes the corresponding signal handler. If the [`signal`](../library/signal#module-signal "signal: Set handlers for asynchronous events.") module is supported, this can invoke a signal handler written in Python. In all cases, the default effect for `SIGINT` is to raise the [`KeyboardInterrupt`](../library/exceptions#KeyboardInterrupt "KeyboardInterrupt") exception. If an exception is raised the error indicator is set and the function returns `-1`; otherwise the function returns `0`. The error indicator may or may not be cleared if it was previously set. `void PyErr_SetInterrupt()` Simulate the effect of a `SIGINT` signal arriving. The next time [`PyErr_CheckSignals()`](#c.PyErr_CheckSignals "PyErr_CheckSignals") is called, the Python signal handler for `SIGINT` will be called. If `SIGINT` isn’t handled by Python (it was set to [`signal.SIG_DFL`](../library/signal#signal.SIG_DFL "signal.SIG_DFL") or [`signal.SIG_IGN`](../library/signal#signal.SIG_IGN "signal.SIG_IGN")), this function does nothing. `int PySignal_SetWakeupFd(int fd)` This utility function specifies a file descriptor to which the signal number is written as a single byte whenever a signal is received. *fd* must be non-blocking. It returns the previous such file descriptor. The value `-1` disables the feature; this is the initial state. This is equivalent to [`signal.set_wakeup_fd()`](../library/signal#signal.set_wakeup_fd "signal.set_wakeup_fd") in Python, but without any error checking. *fd* should be a valid file descriptor. The function should only be called from the main thread. Changed in version 3.5: On Windows, the function now also supports socket handles. Exception Classes ----------------- `PyObject* PyErr_NewException(const char *name, PyObject *base, PyObject *dict)` *Return value: New reference.*This utility function creates and returns a new exception class. The *name* argument must be the name of the new exception, a C string of the form `module.classname`. The *base* and *dict* arguments are normally `NULL`. This creates a class object derived from [`Exception`](../library/exceptions#Exception "Exception") (accessible in C as `PyExc_Exception`). The `__module__` attribute of the new class is set to the first part (up to the last dot) of the *name* argument, and the class name is set to the last part (after the last dot). The *base* argument can be used to specify alternate base classes; it can either be only one class or a tuple of classes. The *dict* argument can be used to specify a dictionary of class variables and methods. `PyObject* PyErr_NewExceptionWithDoc(const char *name, const char *doc, PyObject *base, PyObject *dict)` *Return value: New reference.*Same as [`PyErr_NewException()`](#c.PyErr_NewException "PyErr_NewException"), except that the new exception class can easily be given a docstring: If *doc* is non-`NULL`, it will be used as the docstring for the exception class. New in version 3.2. Exception Objects ----------------- `PyObject* PyException_GetTraceback(PyObject *ex)` *Return value: New reference.*Return the traceback associated with the exception as a new reference, as accessible from Python through `__traceback__`. If there is no traceback associated, this returns `NULL`. `int PyException_SetTraceback(PyObject *ex, PyObject *tb)` Set the traceback associated with the exception to *tb*. Use `Py_None` to clear it. `PyObject* PyException_GetContext(PyObject *ex)` *Return value: New reference.*Return the context (another exception instance during whose handling *ex* was raised) associated with the exception as a new reference, as accessible from Python through `__context__`. If there is no context associated, this returns `NULL`. `void PyException_SetContext(PyObject *ex, PyObject *ctx)` Set the context associated with the exception to *ctx*. Use `NULL` to clear it. There is no type check to make sure that *ctx* is an exception instance. This steals a reference to *ctx*. `PyObject* PyException_GetCause(PyObject *ex)` *Return value: New reference.*Return the cause (either an exception instance, or [`None`](../library/constants#None "None"), set by `raise ... from ...`) associated with the exception as a new reference, as accessible from Python through `__cause__`. `void PyException_SetCause(PyObject *ex, PyObject *cause)` Set the cause associated with the exception to *cause*. Use `NULL` to clear it. There is no type check to make sure that *cause* is either an exception instance or [`None`](../library/constants#None "None"). This steals a reference to *cause*. `__suppress_context__` is implicitly set to `True` by this function. Unicode Exception Objects ------------------------- The following functions are used to create and modify Unicode exceptions from C. `PyObject* PyUnicodeDecodeError_Create(const char *encoding, const char *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)` *Return value: New reference.*Create a [`UnicodeDecodeError`](../library/exceptions#UnicodeDecodeError "UnicodeDecodeError") object with the attributes *encoding*, *object*, *length*, *start*, *end* and *reason*. *encoding* and *reason* are UTF-8 encoded strings. `PyObject* PyUnicodeEncodeError_Create(const char *encoding, const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)` *Return value: New reference.*Create a [`UnicodeEncodeError`](../library/exceptions#UnicodeEncodeError "UnicodeEncodeError") object with the attributes *encoding*, *object*, *length*, *start*, *end* and *reason*. *encoding* and *reason* are UTF-8 encoded strings. Deprecated since version 3.3: 3.11 `Py_UNICODE` is deprecated since Python 3.3. Please migrate to `PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnns", ...)`. `PyObject* PyUnicodeTranslateError_Create(const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)` *Return value: New reference.*Create a [`UnicodeTranslateError`](../library/exceptions#UnicodeTranslateError "UnicodeTranslateError") object with the attributes *object*, *length*, *start*, *end* and *reason*. *reason* is a UTF-8 encoded string. Deprecated since version 3.3: 3.11 `Py_UNICODE` is deprecated since Python 3.3. Please migrate to `PyObject_CallFunction(PyExc_UnicodeTranslateError, "Onns", ...)`. `PyObject* PyUnicodeDecodeError_GetEncoding(PyObject *exc)` `PyObject* PyUnicodeEncodeError_GetEncoding(PyObject *exc)` *Return value: New reference.*Return the *encoding* attribute of the given exception object. `PyObject* PyUnicodeDecodeError_GetObject(PyObject *exc)` `PyObject* PyUnicodeEncodeError_GetObject(PyObject *exc)` `PyObject* PyUnicodeTranslateError_GetObject(PyObject *exc)` *Return value: New reference.*Return the *object* attribute of the given exception object. `int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)` `int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)` `int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)` Get the *start* attribute of the given exception object and place it into *\*start*. *start* must not be `NULL`. Return `0` on success, `-1` on failure. `int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)` `int PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)` `int PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)` Set the *start* attribute of the given exception object to *start*. Return `0` on success, `-1` on failure. `int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)` `int PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)` `int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end)` Get the *end* attribute of the given exception object and place it into *\*end*. *end* must not be `NULL`. Return `0` on success, `-1` on failure. `int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)` `int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)` `int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)` Set the *end* attribute of the given exception object to *end*. Return `0` on success, `-1` on failure. `PyObject* PyUnicodeDecodeError_GetReason(PyObject *exc)` `PyObject* PyUnicodeEncodeError_GetReason(PyObject *exc)` `PyObject* PyUnicodeTranslateError_GetReason(PyObject *exc)` *Return value: New reference.*Return the *reason* attribute of the given exception object. `int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)` `int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)` `int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)` Set the *reason* attribute of the given exception object to *reason*. Return `0` on success, `-1` on failure. Recursion Control ----------------- These two functions provide a way to perform safe recursive calls at the C level, both in the core and in extension modules. They are needed if the recursive code does not necessarily invoke Python code (which tracks its recursion depth automatically). They are also not needed for *tp\_call* implementations because the [call protocol](call#call) takes care of recursion handling. `int Py_EnterRecursiveCall(const char *where)` Marks a point where a recursive C-level call is about to be performed. If `USE_STACKCHECK` is defined, this function checks if the OS stack overflowed using [`PyOS_CheckStack()`](sys#c.PyOS_CheckStack "PyOS_CheckStack"). In this is the case, it sets a [`MemoryError`](../library/exceptions#MemoryError "MemoryError") and returns a nonzero value. The function then checks if the recursion limit is reached. If this is the case, a [`RecursionError`](../library/exceptions#RecursionError "RecursionError") is set and a nonzero value is returned. Otherwise, zero is returned. *where* should be a UTF-8 encoded string such as `" in instance check"` to be concatenated to the [`RecursionError`](../library/exceptions#RecursionError "RecursionError") message caused by the recursion depth limit. Changed in version 3.9: This function is now also available in the limited API. `void Py_LeaveRecursiveCall(void)` Ends a [`Py_EnterRecursiveCall()`](#c.Py_EnterRecursiveCall "Py_EnterRecursiveCall"). Must be called once for each *successful* invocation of [`Py_EnterRecursiveCall()`](#c.Py_EnterRecursiveCall "Py_EnterRecursiveCall"). Changed in version 3.9: This function is now also available in the limited API. Properly implementing [`tp_repr`](typeobj#c.PyTypeObject.tp_repr "PyTypeObject.tp_repr") for container types requires special recursion handling. In addition to protecting the stack, [`tp_repr`](typeobj#c.PyTypeObject.tp_repr "PyTypeObject.tp_repr") also needs to track objects to prevent cycles. The following two functions facilitate this functionality. Effectively, these are the C equivalent to [`reprlib.recursive_repr()`](../library/reprlib#reprlib.recursive_repr "reprlib.recursive_repr"). `int Py_ReprEnter(PyObject *object)` Called at the beginning of the [`tp_repr`](typeobj#c.PyTypeObject.tp_repr "PyTypeObject.tp_repr") implementation to detect cycles. If the object has already been processed, the function returns a positive integer. In that case the [`tp_repr`](typeobj#c.PyTypeObject.tp_repr "PyTypeObject.tp_repr") implementation should return a string object indicating a cycle. As examples, [`dict`](../library/stdtypes#dict "dict") objects return `{...}` and [`list`](../library/stdtypes#list "list") objects return `[...]`. The function will return a negative integer if the recursion limit is reached. In that case the [`tp_repr`](typeobj#c.PyTypeObject.tp_repr "PyTypeObject.tp_repr") implementation should typically return `NULL`. Otherwise, the function returns zero and the [`tp_repr`](typeobj#c.PyTypeObject.tp_repr "PyTypeObject.tp_repr") implementation can continue normally. `void Py_ReprLeave(PyObject *object)` Ends a [`Py_ReprEnter()`](#c.Py_ReprEnter "Py_ReprEnter"). Must be called once for each invocation of [`Py_ReprEnter()`](#c.Py_ReprEnter "Py_ReprEnter") that returns zero. Standard Exceptions ------------------- All standard Python exceptions are available as global variables whose names are `PyExc_` followed by the Python exception name. These have the type [`PyObject*`](structures#c.PyObject "PyObject"); they are all class objects. For completeness, here are all the variables: | C Name | Python Name | Notes | | --- | --- | --- | | `PyExc_BaseException` | [`BaseException`](../library/exceptions#BaseException "BaseException") | [1](#id7) | | `PyExc_Exception` | [`Exception`](../library/exceptions#Exception "Exception") | [1](#id7) | | `PyExc_ArithmeticError` | [`ArithmeticError`](../library/exceptions#ArithmeticError "ArithmeticError") | [1](#id7) | | `PyExc_AssertionError` | [`AssertionError`](../library/exceptions#AssertionError "AssertionError") | | | `PyExc_AttributeError` | [`AttributeError`](../library/exceptions#AttributeError "AttributeError") | | | `PyExc_BlockingIOError` | [`BlockingIOError`](../library/exceptions#BlockingIOError "BlockingIOError") | | | `PyExc_BrokenPipeError` | [`BrokenPipeError`](../library/exceptions#BrokenPipeError "BrokenPipeError") | | | `PyExc_BufferError` | [`BufferError`](../library/exceptions#BufferError "BufferError") | | | `PyExc_ChildProcessError` | [`ChildProcessError`](../library/exceptions#ChildProcessError "ChildProcessError") | | | `PyExc_ConnectionAbortedError` | [`ConnectionAbortedError`](../library/exceptions#ConnectionAbortedError "ConnectionAbortedError") | | | `PyExc_ConnectionError` | [`ConnectionError`](../library/exceptions#ConnectionError "ConnectionError") | | | `PyExc_ConnectionRefusedError` | [`ConnectionRefusedError`](../library/exceptions#ConnectionRefusedError "ConnectionRefusedError") | | | `PyExc_ConnectionResetError` | [`ConnectionResetError`](../library/exceptions#ConnectionResetError "ConnectionResetError") | | | `PyExc_EOFError` | [`EOFError`](../library/exceptions#EOFError "EOFError") | | | `PyExc_FileExistsError` | [`FileExistsError`](../library/exceptions#FileExistsError "FileExistsError") | | | `PyExc_FileNotFoundError` | [`FileNotFoundError`](../library/exceptions#FileNotFoundError "FileNotFoundError") | | | `PyExc_FloatingPointError` | [`FloatingPointError`](../library/exceptions#FloatingPointError "FloatingPointError") | | | `PyExc_GeneratorExit` | [`GeneratorExit`](../library/exceptions#GeneratorExit "GeneratorExit") | | | `PyExc_ImportError` | [`ImportError`](../library/exceptions#ImportError "ImportError") | | | `PyExc_IndentationError` | [`IndentationError`](../library/exceptions#IndentationError "IndentationError") | | | `PyExc_IndexError` | [`IndexError`](../library/exceptions#IndexError "IndexError") | | | `PyExc_InterruptedError` | [`InterruptedError`](../library/exceptions#InterruptedError "InterruptedError") | | | `PyExc_IsADirectoryError` | [`IsADirectoryError`](../library/exceptions#IsADirectoryError "IsADirectoryError") | | | `PyExc_KeyError` | [`KeyError`](../library/exceptions#KeyError "KeyError") | | | `PyExc_KeyboardInterrupt` | [`KeyboardInterrupt`](../library/exceptions#KeyboardInterrupt "KeyboardInterrupt") | | | `PyExc_LookupError` | [`LookupError`](../library/exceptions#LookupError "LookupError") | [1](#id7) | | `PyExc_MemoryError` | [`MemoryError`](../library/exceptions#MemoryError "MemoryError") | | | `PyExc_ModuleNotFoundError` | [`ModuleNotFoundError`](../library/exceptions#ModuleNotFoundError "ModuleNotFoundError") | | | `PyExc_NameError` | [`NameError`](../library/exceptions#NameError "NameError") | | | `PyExc_NotADirectoryError` | [`NotADirectoryError`](../library/exceptions#NotADirectoryError "NotADirectoryError") | | | `PyExc_NotImplementedError` | [`NotImplementedError`](../library/exceptions#NotImplementedError "NotImplementedError") | | | `PyExc_OSError` | [`OSError`](../library/exceptions#OSError "OSError") | [1](#id7) | | `PyExc_OverflowError` | [`OverflowError`](../library/exceptions#OverflowError "OverflowError") | | | `PyExc_PermissionError` | [`PermissionError`](../library/exceptions#PermissionError "PermissionError") | | | `PyExc_ProcessLookupError` | [`ProcessLookupError`](../library/exceptions#ProcessLookupError "ProcessLookupError") | | | `PyExc_RecursionError` | [`RecursionError`](../library/exceptions#RecursionError "RecursionError") | | | `PyExc_ReferenceError` | [`ReferenceError`](../library/exceptions#ReferenceError "ReferenceError") | | | `PyExc_RuntimeError` | [`RuntimeError`](../library/exceptions#RuntimeError "RuntimeError") | | | `PyExc_StopAsyncIteration` | [`StopAsyncIteration`](../library/exceptions#StopAsyncIteration "StopAsyncIteration") | | | `PyExc_StopIteration` | [`StopIteration`](../library/exceptions#StopIteration "StopIteration") | | | `PyExc_SyntaxError` | [`SyntaxError`](../library/exceptions#SyntaxError "SyntaxError") | | | `PyExc_SystemError` | [`SystemError`](../library/exceptions#SystemError "SystemError") | | | `PyExc_SystemExit` | [`SystemExit`](../library/exceptions#SystemExit "SystemExit") | | | `PyExc_TabError` | [`TabError`](../library/exceptions#TabError "TabError") | | | `PyExc_TimeoutError` | [`TimeoutError`](../library/exceptions#TimeoutError "TimeoutError") | | | `PyExc_TypeError` | [`TypeError`](../library/exceptions#TypeError "TypeError") | | | `PyExc_UnboundLocalError` | [`UnboundLocalError`](../library/exceptions#UnboundLocalError "UnboundLocalError") | | | `PyExc_UnicodeDecodeError` | [`UnicodeDecodeError`](../library/exceptions#UnicodeDecodeError "UnicodeDecodeError") | | | `PyExc_UnicodeEncodeError` | [`UnicodeEncodeError`](../library/exceptions#UnicodeEncodeError "UnicodeEncodeError") | | | `PyExc_UnicodeError` | [`UnicodeError`](../library/exceptions#UnicodeError "UnicodeError") | | | `PyExc_UnicodeTranslateError` | [`UnicodeTranslateError`](../library/exceptions#UnicodeTranslateError "UnicodeTranslateError") | | | `PyExc_ValueError` | [`ValueError`](../library/exceptions#ValueError "ValueError") | | | `PyExc_ZeroDivisionError` | [`ZeroDivisionError`](../library/exceptions#ZeroDivisionError "ZeroDivisionError") | | New in version 3.3: `PyExc_BlockingIOError`, `PyExc_BrokenPipeError`, `PyExc_ChildProcessError`, `PyExc_ConnectionError`, `PyExc_ConnectionAbortedError`, `PyExc_ConnectionRefusedError`, `PyExc_ConnectionResetError`, `PyExc_FileExistsError`, `PyExc_FileNotFoundError`, `PyExc_InterruptedError`, `PyExc_IsADirectoryError`, `PyExc_NotADirectoryError`, `PyExc_PermissionError`, `PyExc_ProcessLookupError` and `PyExc_TimeoutError` were introduced following [**PEP 3151**](https://www.python.org/dev/peps/pep-3151). New in version 3.5: `PyExc_StopAsyncIteration` and `PyExc_RecursionError`. New in version 3.6: `PyExc_ModuleNotFoundError`. These are compatibility aliases to `PyExc_OSError`: | C Name | Notes | | --- | --- | | `PyExc_EnvironmentError` | | | `PyExc_IOError` | | | `PyExc_WindowsError` | [2](#id8) | Changed in version 3.3: These aliases used to be separate exception types. Notes: `1(1,2,3,4,5)` This is a base class for other standard exceptions. `2` Only defined on Windows; protect code that uses this by testing that the preprocessor macro `MS_WINDOWS` is defined. Standard Warning Categories --------------------------- All standard Python warning categories are available as global variables whose names are `PyExc_` followed by the Python exception name. These have the type [`PyObject*`](structures#c.PyObject "PyObject"); they are all class objects. For completeness, here are all the variables: | C Name | Python Name | Notes | | --- | --- | --- | | `PyExc_Warning` | [`Warning`](../library/exceptions#Warning "Warning") | [3](#id10) | | `PyExc_BytesWarning` | [`BytesWarning`](../library/exceptions#BytesWarning "BytesWarning") | | | `PyExc_DeprecationWarning` | [`DeprecationWarning`](../library/exceptions#DeprecationWarning "DeprecationWarning") | | | `PyExc_FutureWarning` | [`FutureWarning`](../library/exceptions#FutureWarning "FutureWarning") | | | `PyExc_ImportWarning` | [`ImportWarning`](../library/exceptions#ImportWarning "ImportWarning") | | | `PyExc_PendingDeprecationWarning` | [`PendingDeprecationWarning`](../library/exceptions#PendingDeprecationWarning "PendingDeprecationWarning") | | | `PyExc_ResourceWarning` | [`ResourceWarning`](../library/exceptions#ResourceWarning "ResourceWarning") | | | `PyExc_RuntimeWarning` | [`RuntimeWarning`](../library/exceptions#RuntimeWarning "RuntimeWarning") | | | `PyExc_SyntaxWarning` | [`SyntaxWarning`](../library/exceptions#SyntaxWarning "SyntaxWarning") | | | `PyExc_UnicodeWarning` | [`UnicodeWarning`](../library/exceptions#UnicodeWarning "UnicodeWarning") | | | `PyExc_UserWarning` | [`UserWarning`](../library/exceptions#UserWarning "UserWarning") | | New in version 3.2: `PyExc_ResourceWarning`. Notes: `3` This is a base class for other standard warning categories.
programming_docs
python Unicode Objects and Codecs Unicode Objects and Codecs ========================== Unicode Objects --------------- Since the implementation of [**PEP 393**](https://www.python.org/dev/peps/pep-0393) in Python 3.3, Unicode objects internally use a variety of representations, in order to allow handling the complete range of Unicode characters while staying memory efficient. There are special cases for strings where all code points are below 128, 256, or 65536; otherwise, code points must be below 1114112 (which is the full Unicode range). [`Py_UNICODE*`](#c.Py_UNICODE "Py_UNICODE") and UTF-8 representations are created on demand and cached in the Unicode object. The [`Py_UNICODE*`](#c.Py_UNICODE "Py_UNICODE") representation is deprecated and inefficient. Due to the transition between the old APIs and the new APIs, Unicode objects can internally be in two states depending on how they were created: * “canonical” Unicode objects are all objects created by a non-deprecated Unicode API. They use the most efficient representation allowed by the implementation. * “legacy” Unicode objects have been created through one of the deprecated APIs (typically [`PyUnicode_FromUnicode()`](#c.PyUnicode_FromUnicode "PyUnicode_FromUnicode")) and only bear the [`Py_UNICODE*`](#c.Py_UNICODE "Py_UNICODE") representation; you will have to call [`PyUnicode_READY()`](#c.PyUnicode_READY "PyUnicode_READY") on them before calling any other API. Note The “legacy” Unicode object will be removed in Python 3.12 with deprecated APIs. All Unicode objects will be “canonical” since then. See [**PEP 623**](https://www.python.org/dev/peps/pep-0623) for more information. ### Unicode Type These are the basic Unicode object types used for the Unicode implementation in Python: `Py_UCS4` `Py_UCS2` `Py_UCS1` These types are typedefs for unsigned integer types wide enough to contain characters of 32 bits, 16 bits and 8 bits, respectively. When dealing with single Unicode characters, use [`Py_UCS4`](#c.Py_UCS4 "Py_UCS4"). New in version 3.3. `Py_UNICODE` This is a typedef of `wchar_t`, which is a 16-bit type or 32-bit type depending on the platform. Changed in version 3.3: In previous versions, this was a 16-bit type or a 32-bit type depending on whether you selected a “narrow” or “wide” Unicode version of Python at build time. `PyASCIIObject` `PyCompactUnicodeObject` `PyUnicodeObject` These subtypes of [`PyObject`](structures#c.PyObject "PyObject") represent a Python Unicode object. In almost all cases, they shouldn’t be used directly, since all API functions that deal with Unicode objects take and return [`PyObject`](structures#c.PyObject "PyObject") pointers. New in version 3.3. `PyTypeObject PyUnicode_Type` This instance of [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject") represents the Python Unicode type. It is exposed to Python code as `str`. The following APIs are really C macros and can be used to do fast checks and to access internal read-only data of Unicode objects: `int PyUnicode_Check(PyObject *o)` Return true if the object *o* is a Unicode object or an instance of a Unicode subtype. This function always succeeds. `int PyUnicode_CheckExact(PyObject *o)` Return true if the object *o* is a Unicode object, but not an instance of a subtype. This function always succeeds. `int PyUnicode_READY(PyObject *o)` Ensure the string object *o* is in the “canonical” representation. This is required before using any of the access macros described below. Returns `0` on success and `-1` with an exception set on failure, which in particular happens if memory allocation fails. New in version 3.3. Deprecated since version 3.10, will be removed in version 3.12: This API will be removed with [`PyUnicode_FromUnicode()`](#c.PyUnicode_FromUnicode "PyUnicode_FromUnicode"). `Py_ssize_t PyUnicode_GET_LENGTH(PyObject *o)` Return the length of the Unicode string, in code points. *o* has to be a Unicode object in the “canonical” representation (not checked). New in version 3.3. `Py_UCS1* PyUnicode_1BYTE_DATA(PyObject *o)` `Py_UCS2* PyUnicode_2BYTE_DATA(PyObject *o)` `Py_UCS4* PyUnicode_4BYTE_DATA(PyObject *o)` Return a pointer to the canonical representation cast to UCS1, UCS2 or UCS4 integer types for direct character access. No checks are performed if the canonical representation has the correct character size; use [`PyUnicode_KIND()`](#c.PyUnicode_KIND "PyUnicode_KIND") to select the right macro. Make sure [`PyUnicode_READY()`](#c.PyUnicode_READY "PyUnicode_READY") has been called before accessing this. New in version 3.3. `PyUnicode_WCHAR_KIND` `PyUnicode_1BYTE_KIND` `PyUnicode_2BYTE_KIND` `PyUnicode_4BYTE_KIND` Return values of the [`PyUnicode_KIND()`](#c.PyUnicode_KIND "PyUnicode_KIND") macro. New in version 3.3. Deprecated since version 3.10, will be removed in version 3.12: `PyUnicode_WCHAR_KIND` is deprecated. `unsigned int PyUnicode_KIND(PyObject *o)` Return one of the PyUnicode kind constants (see above) that indicate how many bytes per character this Unicode object uses to store its data. *o* has to be a Unicode object in the “canonical” representation (not checked). New in version 3.3. `void* PyUnicode_DATA(PyObject *o)` Return a void pointer to the raw Unicode buffer. *o* has to be a Unicode object in the “canonical” representation (not checked). New in version 3.3. `void PyUnicode_WRITE(int kind, void *data, Py_ssize_t index, Py_UCS4 value)` Write into a canonical representation *data* (as obtained with [`PyUnicode_DATA()`](#c.PyUnicode_DATA "PyUnicode_DATA")). This macro does not do any sanity checks and is intended for usage in loops. The caller should cache the *kind* value and *data* pointer as obtained from other macro calls. *index* is the index in the string (starts at 0) and *value* is the new code point value which should be written to that location. New in version 3.3. `Py_UCS4 PyUnicode_READ(int kind, void *data, Py_ssize_t index)` Read a code point from a canonical representation *data* (as obtained with [`PyUnicode_DATA()`](#c.PyUnicode_DATA "PyUnicode_DATA")). No checks or ready calls are performed. New in version 3.3. `Py_UCS4 PyUnicode_READ_CHAR(PyObject *o, Py_ssize_t index)` Read a character from a Unicode object *o*, which must be in the “canonical” representation. This is less efficient than [`PyUnicode_READ()`](#c.PyUnicode_READ "PyUnicode_READ") if you do multiple consecutive reads. New in version 3.3. `PyUnicode_MAX_CHAR_VALUE(o)` Return the maximum code point that is suitable for creating another string based on *o*, which must be in the “canonical” representation. This is always an approximation but more efficient than iterating over the string. New in version 3.3. `Py_ssize_t PyUnicode_GET_SIZE(PyObject *o)` Return the size of the deprecated [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") representation, in code units (this includes surrogate pairs as 2 units). *o* has to be a Unicode object (not checked). Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style Unicode API, please migrate to using [`PyUnicode_GET_LENGTH()`](#c.PyUnicode_GET_LENGTH "PyUnicode_GET_LENGTH"). `Py_ssize_t PyUnicode_GET_DATA_SIZE(PyObject *o)` Return the size of the deprecated [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") representation in bytes. *o* has to be a Unicode object (not checked). Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style Unicode API, please migrate to using [`PyUnicode_GET_LENGTH()`](#c.PyUnicode_GET_LENGTH "PyUnicode_GET_LENGTH"). `Py_UNICODE* PyUnicode_AS_UNICODE(PyObject *o)` `const char* PyUnicode_AS_DATA(PyObject *o)` Return a pointer to a [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") representation of the object. The returned buffer is always terminated with an extra null code point. It may also contain embedded null code points, which would cause the string to be truncated when used in most C functions. The `AS_DATA` form casts the pointer to `const char *`. The *o* argument has to be a Unicode object (not checked). Changed in version 3.3: This macro is now inefficient – because in many cases the [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") representation does not exist and needs to be created – and can fail (return `NULL` with an exception set). Try to port the code to use the new `PyUnicode_nBYTE_DATA()` macros or use [`PyUnicode_WRITE()`](#c.PyUnicode_WRITE "PyUnicode_WRITE") or [`PyUnicode_READ()`](#c.PyUnicode_READ "PyUnicode_READ"). Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style Unicode API, please migrate to using the `PyUnicode_nBYTE_DATA()` family of macros. `int PyUnicode_IsIdentifier(PyObject *o)` Return `1` if the string is a valid identifier according to the language definition, section [Identifiers and keywords](../reference/lexical_analysis#identifiers). Return `0` otherwise. Changed in version 3.9: The function does not call [`Py_FatalError()`](sys#c.Py_FatalError "Py_FatalError") anymore if the string is not ready. ### Unicode Character Properties Unicode provides many different character properties. The most often needed ones are available through these macros which are mapped to C functions depending on the Python configuration. `int Py_UNICODE_ISSPACE(Py_UCS4 ch)` Return `1` or `0` depending on whether *ch* is a whitespace character. `int Py_UNICODE_ISLOWER(Py_UCS4 ch)` Return `1` or `0` depending on whether *ch* is a lowercase character. `int Py_UNICODE_ISUPPER(Py_UCS4 ch)` Return `1` or `0` depending on whether *ch* is an uppercase character. `int Py_UNICODE_ISTITLE(Py_UCS4 ch)` Return `1` or `0` depending on whether *ch* is a titlecase character. `int Py_UNICODE_ISLINEBREAK(Py_UCS4 ch)` Return `1` or `0` depending on whether *ch* is a linebreak character. `int Py_UNICODE_ISDECIMAL(Py_UCS4 ch)` Return `1` or `0` depending on whether *ch* is a decimal character. `int Py_UNICODE_ISDIGIT(Py_UCS4 ch)` Return `1` or `0` depending on whether *ch* is a digit character. `int Py_UNICODE_ISNUMERIC(Py_UCS4 ch)` Return `1` or `0` depending on whether *ch* is a numeric character. `int Py_UNICODE_ISALPHA(Py_UCS4 ch)` Return `1` or `0` depending on whether *ch* is an alphabetic character. `int Py_UNICODE_ISALNUM(Py_UCS4 ch)` Return `1` or `0` depending on whether *ch* is an alphanumeric character. `int Py_UNICODE_ISPRINTABLE(Py_UCS4 ch)` Return `1` or `0` depending on whether *ch* is a printable character. Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space (0x20) which is considered printable. (Note that printable characters in this context are those which should not be escaped when [`repr()`](../library/functions#repr "repr") is invoked on a string. It has no bearing on the handling of strings written to [`sys.stdout`](../library/sys#sys.stdout "sys.stdout") or [`sys.stderr`](../library/sys#sys.stderr "sys.stderr").) These APIs can be used for fast direct character conversions: `Py_UCS4 Py_UNICODE_TOLOWER(Py_UCS4 ch)` Return the character *ch* converted to lower case. Deprecated since version 3.3: This function uses simple case mappings. `Py_UCS4 Py_UNICODE_TOUPPER(Py_UCS4 ch)` Return the character *ch* converted to upper case. Deprecated since version 3.3: This function uses simple case mappings. `Py_UCS4 Py_UNICODE_TOTITLE(Py_UCS4 ch)` Return the character *ch* converted to title case. Deprecated since version 3.3: This function uses simple case mappings. `int Py_UNICODE_TODECIMAL(Py_UCS4 ch)` Return the character *ch* converted to a decimal positive integer. Return `-1` if this is not possible. This macro does not raise exceptions. `int Py_UNICODE_TODIGIT(Py_UCS4 ch)` Return the character *ch* converted to a single digit integer. Return `-1` if this is not possible. This macro does not raise exceptions. `double Py_UNICODE_TONUMERIC(Py_UCS4 ch)` Return the character *ch* converted to a double. Return `-1.0` if this is not possible. This macro does not raise exceptions. These APIs can be used to work with surrogates: `Py_UNICODE_IS_SURROGATE(ch)` Check if *ch* is a surrogate (`0xD800 <= ch <= 0xDFFF`). `Py_UNICODE_IS_HIGH_SURROGATE(ch)` Check if *ch* is a high surrogate (`0xD800 <= ch <= 0xDBFF`). `Py_UNICODE_IS_LOW_SURROGATE(ch)` Check if *ch* is a low surrogate (`0xDC00 <= ch <= 0xDFFF`). `Py_UNICODE_JOIN_SURROGATES(high, low)` Join two surrogate characters and return a single Py\_UCS4 value. *high* and *low* are respectively the leading and trailing surrogates in a surrogate pair. ### Creating and accessing Unicode strings To create Unicode objects and access their basic sequence properties, use these APIs: `PyObject* PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)` *Return value: New reference.*Create a new Unicode object. *maxchar* should be the true maximum code point to be placed in the string. As an approximation, it can be rounded up to the nearest value in the sequence 127, 255, 65535, 1114111. This is the recommended way to allocate a new Unicode object. Objects created using this function are not resizable. New in version 3.3. `PyObject* PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)` *Return value: New reference.*Create a new Unicode object with the given *kind* (possible values are [`PyUnicode_1BYTE_KIND`](#c.PyUnicode_1BYTE_KIND "PyUnicode_1BYTE_KIND") etc., as returned by [`PyUnicode_KIND()`](#c.PyUnicode_KIND "PyUnicode_KIND")). The *buffer* must point to an array of *size* units of 1, 2 or 4 bytes per character, as given by the kind. New in version 3.3. `PyObject* PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)` *Return value: New reference.*Create a Unicode object from the char buffer *u*. The bytes will be interpreted as being UTF-8 encoded. The buffer is copied into the new object. If the buffer is not `NULL`, the return value might be a shared object, i.e. modification of the data is not allowed. If *u* is `NULL`, this function behaves like [`PyUnicode_FromUnicode()`](#c.PyUnicode_FromUnicode "PyUnicode_FromUnicode") with the buffer set to `NULL`. This usage is deprecated in favor of [`PyUnicode_New()`](#c.PyUnicode_New "PyUnicode_New"), and will be removed in Python 3.12. `PyObject *PyUnicode_FromString(const char *u)` *Return value: New reference.*Create a Unicode object from a UTF-8 encoded null-terminated char buffer *u*. `PyObject* PyUnicode_FromFormat(const char *format, ...)` *Return value: New reference.*Take a C `printf()`-style *format* string and a variable number of arguments, calculate the size of the resulting Python Unicode string and return a string with the values formatted into it. The variable arguments must be C types and must correspond exactly to the format characters in the *format* ASCII-encoded string. The following format characters are allowed: | Format Characters | Type | Comment | | --- | --- | --- | | `%%` | *n/a* | The literal % character. | | `%c` | int | A single character, represented as a C int. | | `%d` | int | Equivalent to `printf("%d")`. [1](#id14) | | `%u` | unsigned int | Equivalent to `printf("%u")`. [1](#id14) | | `%ld` | long | Equivalent to `printf("%ld")`. [1](#id14) | | `%li` | long | Equivalent to `printf("%li")`. [1](#id14) | | `%lu` | unsigned long | Equivalent to `printf("%lu")`. [1](#id14) | | `%lld` | long long | Equivalent to `printf("%lld")`. [1](#id14) | | `%lli` | long long | Equivalent to `printf("%lli")`. [1](#id14) | | `%llu` | unsigned long long | Equivalent to `printf("%llu")`. [1](#id14) | | `%zd` | [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t") | Equivalent to `printf("%zd")`. [1](#id14) | | `%zi` | [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t") | Equivalent to `printf("%zi")`. [1](#id14) | | `%zu` | size\_t | Equivalent to `printf("%zu")`. [1](#id14) | | `%i` | int | Equivalent to `printf("%i")`. [1](#id14) | | `%x` | int | Equivalent to `printf("%x")`. [1](#id14) | | `%s` | const char\* | A null-terminated C character array. | | `%p` | const void\* | The hex representation of a C pointer. Mostly equivalent to `printf("%p")` except that it is guaranteed to start with the literal `0x` regardless of what the platform’s `printf` yields. | | `%A` | PyObject\* | The result of calling [`ascii()`](../library/functions#ascii "ascii"). | | `%U` | PyObject\* | A Unicode object. | | `%V` | PyObject\*, const char\* | A Unicode object (which may be `NULL`) and a null-terminated C character array as a second parameter (which will be used, if the first parameter is `NULL`). | | `%S` | PyObject\* | The result of calling [`PyObject_Str()`](object#c.PyObject_Str "PyObject_Str"). | | `%R` | PyObject\* | The result of calling [`PyObject_Repr()`](object#c.PyObject_Repr "PyObject_Repr"). | An unrecognized format character causes all the rest of the format string to be copied as-is to the result string, and any extra arguments discarded. Note The width formatter unit is number of characters rather than bytes. The precision formatter unit is number of bytes for `"%s"` and `"%V"` (if the `PyObject*` argument is `NULL`), and a number of characters for `"%A"`, `"%U"`, `"%S"`, `"%R"` and `"%V"` (if the `PyObject*` argument is not `NULL`). `1(1,2,3,4,5,6,7,8,9,10,11,12,13)` For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd, zi, zu, i, x): the 0-conversion flag has effect even when a precision is given. Changed in version 3.2: Support for `"%lld"` and `"%llu"` added. Changed in version 3.3: Support for `"%li"`, `"%lli"` and `"%zi"` added. Changed in version 3.4: Support width and precision formatter for `"%s"`, `"%A"`, `"%U"`, `"%V"`, `"%S"`, `"%R"` added. `PyObject* PyUnicode_FromFormatV(const char *format, va_list vargs)` *Return value: New reference.*Identical to [`PyUnicode_FromFormat()`](#c.PyUnicode_FromFormat "PyUnicode_FromFormat") except that it takes exactly two arguments. `PyObject* PyUnicode_FromEncodedObject(PyObject *obj, const char *encoding, const char *errors)` *Return value: New reference.*Decode an encoded object *obj* to a Unicode object. [`bytes`](../library/stdtypes#bytes "bytes"), [`bytearray`](../library/stdtypes#bytearray "bytearray") and other [bytes-like objects](../glossary#term-bytes-like-object) are decoded according to the given *encoding* and using the error handling defined by *errors*. Both can be `NULL` to have the interface use the default values (see [Built-in Codecs](#builtincodecs) for details). All other objects, including Unicode objects, cause a [`TypeError`](../library/exceptions#TypeError "TypeError") to be set. The API returns `NULL` if there was an error. The caller is responsible for decref’ing the returned objects. `Py_ssize_t PyUnicode_GetLength(PyObject *unicode)` Return the length of the Unicode object, in code points. New in version 3.3. `Py_ssize_t PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start, PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)` Copy characters from one Unicode object into another. This function performs character conversion when necessary and falls back to `memcpy()` if possible. Returns `-1` and sets an exception on error, otherwise returns the number of copied characters. New in version 3.3. `Py_ssize_t PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length, Py_UCS4 fill_char)` Fill a string with a character: write *fill\_char* into `unicode[start:start+length]`. Fail if *fill\_char* is bigger than the string maximum character, or if the string has more than 1 reference. Return the number of written character, or return `-1` and raise an exception on error. New in version 3.3. `int PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 character)` Write a character to a string. The string must have been created through [`PyUnicode_New()`](#c.PyUnicode_New "PyUnicode_New"). Since Unicode strings are supposed to be immutable, the string must not be shared, or have been hashed yet. This function checks that *unicode* is a Unicode object, that the index is not out of bounds, and that the object can be modified safely (i.e. that it its reference count is one). New in version 3.3. `Py_UCS4 PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)` Read a character from a string. This function checks that *unicode* is a Unicode object and the index is not out of bounds, in contrast to the macro version [`PyUnicode_READ_CHAR()`](#c.PyUnicode_READ_CHAR "PyUnicode_READ_CHAR"). New in version 3.3. `PyObject* PyUnicode_Substring(PyObject *str, Py_ssize_t start, Py_ssize_t end)` *Return value: New reference.*Return a substring of *str*, from character index *start* (included) to character index *end* (excluded). Negative indices are not supported. New in version 3.3. `Py_UCS4* PyUnicode_AsUCS4(PyObject *u, Py_UCS4 *buffer, Py_ssize_t buflen, int copy_null)` Copy the string *u* into a UCS4 buffer, including a null character, if *copy\_null* is set. Returns `NULL` and sets an exception on error (in particular, a [`SystemError`](../library/exceptions#SystemError "SystemError") if *buflen* is smaller than the length of *u*). *buffer* is returned on success. New in version 3.3. `Py_UCS4* PyUnicode_AsUCS4Copy(PyObject *u)` Copy the string *u* into a new UCS4 buffer that is allocated using [`PyMem_Malloc()`](memory#c.PyMem_Malloc "PyMem_Malloc"). If this fails, `NULL` is returned with a [`MemoryError`](../library/exceptions#MemoryError "MemoryError") set. The returned buffer always has an extra null code point appended. New in version 3.3. ### Deprecated Py\_UNICODE APIs Deprecated since version 3.3, will be removed in version 3.12. These API functions are deprecated with the implementation of [**PEP 393**](https://www.python.org/dev/peps/pep-0393). Extension modules can continue using them, as they will not be removed in Python 3.x, but need to be aware that their use can now cause performance and memory hits. `PyObject* PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)` *Return value: New reference.*Create a Unicode object from the Py\_UNICODE buffer *u* of the given size. *u* may be `NULL` which causes the contents to be undefined. It is the user’s responsibility to fill in the needed data. The buffer is copied into the new object. If the buffer is not `NULL`, the return value might be a shared object. Therefore, modification of the resulting Unicode object is only allowed when *u* is `NULL`. If the buffer is `NULL`, [`PyUnicode_READY()`](#c.PyUnicode_READY "PyUnicode_READY") must be called once the string content has been filled before using any of the access macros such as [`PyUnicode_KIND()`](#c.PyUnicode_KIND "PyUnicode_KIND"). Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style Unicode API, please migrate to using [`PyUnicode_FromKindAndData()`](#c.PyUnicode_FromKindAndData "PyUnicode_FromKindAndData"), [`PyUnicode_FromWideChar()`](#c.PyUnicode_FromWideChar "PyUnicode_FromWideChar"), or [`PyUnicode_New()`](#c.PyUnicode_New "PyUnicode_New"). `Py_UNICODE* PyUnicode_AsUnicode(PyObject *unicode)` Return a read-only pointer to the Unicode object’s internal [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") buffer, or `NULL` on error. This will create the [`Py_UNICODE*`](#c.Py_UNICODE "Py_UNICODE") representation of the object if it is not yet available. The buffer is always terminated with an extra null code point. Note that the resulting [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") string may also contain embedded null code points, which would cause the string to be truncated when used in most C functions. Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style Unicode API, please migrate to using [`PyUnicode_AsUCS4()`](#c.PyUnicode_AsUCS4 "PyUnicode_AsUCS4"), [`PyUnicode_AsWideChar()`](#c.PyUnicode_AsWideChar "PyUnicode_AsWideChar"), [`PyUnicode_ReadChar()`](#c.PyUnicode_ReadChar "PyUnicode_ReadChar") or similar new APIs. Deprecated since version 3.3, will be removed in version 3.10. `PyObject* PyUnicode_TransformDecimalToASCII(Py_UNICODE *s, Py_ssize_t size)` *Return value: New reference.*Create a Unicode object by replacing all decimal digits in [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") buffer of the given *size* by ASCII digits 0–9 according to their decimal value. Return `NULL` if an exception occurs. Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") API; please migrate to using [`Py_UNICODE_TODECIMAL()`](#c.Py_UNICODE_TODECIMAL "Py_UNICODE_TODECIMAL"). `Py_UNICODE* PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)` Like [`PyUnicode_AsUnicode()`](#c.PyUnicode_AsUnicode "PyUnicode_AsUnicode"), but also saves the [`Py_UNICODE()`](#c.Py_UNICODE "Py_UNICODE") array length (excluding the extra null terminator) in *size*. Note that the resulting [`Py_UNICODE*`](#c.Py_UNICODE "Py_UNICODE") string may contain embedded null code points, which would cause the string to be truncated when used in most C functions. New in version 3.3. Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style Unicode API, please migrate to using [`PyUnicode_AsUCS4()`](#c.PyUnicode_AsUCS4 "PyUnicode_AsUCS4"), [`PyUnicode_AsWideChar()`](#c.PyUnicode_AsWideChar "PyUnicode_AsWideChar"), [`PyUnicode_ReadChar()`](#c.PyUnicode_ReadChar "PyUnicode_ReadChar") or similar new APIs. `Py_UNICODE* PyUnicode_AsUnicodeCopy(PyObject *unicode)` Create a copy of a Unicode string ending with a null code point. Return `NULL` and raise a [`MemoryError`](../library/exceptions#MemoryError "MemoryError") exception on memory allocation failure, otherwise return a new allocated buffer (use [`PyMem_Free()`](memory#c.PyMem_Free "PyMem_Free") to free the buffer). Note that the resulting [`Py_UNICODE*`](#c.Py_UNICODE "Py_UNICODE") string may contain embedded null code points, which would cause the string to be truncated when used in most C functions. New in version 3.2. Please migrate to using [`PyUnicode_AsUCS4Copy()`](#c.PyUnicode_AsUCS4Copy "PyUnicode_AsUCS4Copy") or similar new APIs. `Py_ssize_t PyUnicode_GetSize(PyObject *unicode)` Return the size of the deprecated [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") representation, in code units (this includes surrogate pairs as 2 units). Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style Unicode API, please migrate to using [`PyUnicode_GET_LENGTH()`](#c.PyUnicode_GET_LENGTH "PyUnicode_GET_LENGTH"). `PyObject* PyUnicode_FromObject(PyObject *obj)` *Return value: New reference.*Copy an instance of a Unicode subtype to a new true Unicode object if necessary. If *obj* is already a true Unicode object (not a subtype), return the reference with incremented refcount. Objects other than Unicode or its subtypes will cause a [`TypeError`](../library/exceptions#TypeError "TypeError"). ### Locale Encoding The current locale encoding can be used to decode text from the operating system. `PyObject* PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len, const char *errors)` *Return value: New reference.*Decode a string from UTF-8 on Android and VxWorks, or from the current locale encoding on other platforms. The supported error handlers are `"strict"` and `"surrogateescape"` ([**PEP 383**](https://www.python.org/dev/peps/pep-0383)). The decoder uses `"strict"` error handler if *errors* is `NULL`. *str* must end with a null character but cannot contain embedded null characters. Use [`PyUnicode_DecodeFSDefaultAndSize()`](#c.PyUnicode_DecodeFSDefaultAndSize "PyUnicode_DecodeFSDefaultAndSize") to decode a string from `Py_FileSystemDefaultEncoding` (the locale encoding read at Python startup). This function ignores the Python UTF-8 mode. See also The [`Py_DecodeLocale()`](sys#c.Py_DecodeLocale "Py_DecodeLocale") function. New in version 3.3. Changed in version 3.7: The function now also uses the current locale encoding for the `surrogateescape` error handler, except on Android. Previously, [`Py_DecodeLocale()`](sys#c.Py_DecodeLocale "Py_DecodeLocale") was used for the `surrogateescape`, and the current locale encoding was used for `strict`. `PyObject* PyUnicode_DecodeLocale(const char *str, const char *errors)` *Return value: New reference.*Similar to [`PyUnicode_DecodeLocaleAndSize()`](#c.PyUnicode_DecodeLocaleAndSize "PyUnicode_DecodeLocaleAndSize"), but compute the string length using `strlen()`. New in version 3.3. `PyObject* PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)` *Return value: New reference.*Encode a Unicode object to UTF-8 on Android and VxWorks, or to the current locale encoding on other platforms. The supported error handlers are `"strict"` and `"surrogateescape"` ([**PEP 383**](https://www.python.org/dev/peps/pep-0383)). The encoder uses `"strict"` error handler if *errors* is `NULL`. Return a [`bytes`](../library/stdtypes#bytes "bytes") object. *unicode* cannot contain embedded null characters. Use [`PyUnicode_EncodeFSDefault()`](#c.PyUnicode_EncodeFSDefault "PyUnicode_EncodeFSDefault") to encode a string to `Py_FileSystemDefaultEncoding` (the locale encoding read at Python startup). This function ignores the Python UTF-8 mode. See also The [`Py_EncodeLocale()`](sys#c.Py_EncodeLocale "Py_EncodeLocale") function. New in version 3.3. Changed in version 3.7: The function now also uses the current locale encoding for the `surrogateescape` error handler, except on Android. Previously, [`Py_EncodeLocale()`](sys#c.Py_EncodeLocale "Py_EncodeLocale") was used for the `surrogateescape`, and the current locale encoding was used for `strict`. ### File System Encoding To encode and decode file names and other environment strings, `Py_FileSystemDefaultEncoding` should be used as the encoding, and `Py_FileSystemDefaultEncodeErrors` should be used as the error handler ([**PEP 383**](https://www.python.org/dev/peps/pep-0383) and [**PEP 529**](https://www.python.org/dev/peps/pep-0529)). To encode file names to [`bytes`](../library/stdtypes#bytes "bytes") during argument parsing, the `"O&"` converter should be used, passing [`PyUnicode_FSConverter()`](#c.PyUnicode_FSConverter "PyUnicode_FSConverter") as the conversion function: `int PyUnicode_FSConverter(PyObject* obj, void* result)` ParseTuple converter: encode [`str`](../library/stdtypes#str "str") objects – obtained directly or through the [`os.PathLike`](../library/os#os.PathLike "os.PathLike") interface – to [`bytes`](../library/stdtypes#bytes "bytes") using [`PyUnicode_EncodeFSDefault()`](#c.PyUnicode_EncodeFSDefault "PyUnicode_EncodeFSDefault"); [`bytes`](../library/stdtypes#bytes "bytes") objects are output as-is. *result* must be a [`PyBytesObject*`](bytes#c.PyBytesObject "PyBytesObject") which must be released when it is no longer used. New in version 3.1. Changed in version 3.6: Accepts a [path-like object](../glossary#term-path-like-object). To decode file names to [`str`](../library/stdtypes#str "str") during argument parsing, the `"O&"` converter should be used, passing [`PyUnicode_FSDecoder()`](#c.PyUnicode_FSDecoder "PyUnicode_FSDecoder") as the conversion function: `int PyUnicode_FSDecoder(PyObject* obj, void* result)` ParseTuple converter: decode [`bytes`](../library/stdtypes#bytes "bytes") objects – obtained either directly or indirectly through the [`os.PathLike`](../library/os#os.PathLike "os.PathLike") interface – to [`str`](../library/stdtypes#str "str") using [`PyUnicode_DecodeFSDefaultAndSize()`](#c.PyUnicode_DecodeFSDefaultAndSize "PyUnicode_DecodeFSDefaultAndSize"); [`str`](../library/stdtypes#str "str") objects are output as-is. *result* must be a [`PyUnicodeObject*`](#c.PyUnicodeObject "PyUnicodeObject") which must be released when it is no longer used. New in version 3.2. Changed in version 3.6: Accepts a [path-like object](../glossary#term-path-like-object). `PyObject* PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)` *Return value: New reference.*Decode a string using `Py_FileSystemDefaultEncoding` and the `Py_FileSystemDefaultEncodeErrors` error handler. If `Py_FileSystemDefaultEncoding` is not set, fall back to the locale encoding. `Py_FileSystemDefaultEncoding` is initialized at startup from the locale encoding and cannot be modified later. If you need to decode a string from the current locale encoding, use [`PyUnicode_DecodeLocaleAndSize()`](#c.PyUnicode_DecodeLocaleAndSize "PyUnicode_DecodeLocaleAndSize"). See also The [`Py_DecodeLocale()`](sys#c.Py_DecodeLocale "Py_DecodeLocale") function. Changed in version 3.6: Use `Py_FileSystemDefaultEncodeErrors` error handler. `PyObject* PyUnicode_DecodeFSDefault(const char *s)` *Return value: New reference.*Decode a null-terminated string using `Py_FileSystemDefaultEncoding` and the `Py_FileSystemDefaultEncodeErrors` error handler. If `Py_FileSystemDefaultEncoding` is not set, fall back to the locale encoding. Use [`PyUnicode_DecodeFSDefaultAndSize()`](#c.PyUnicode_DecodeFSDefaultAndSize "PyUnicode_DecodeFSDefaultAndSize") if you know the string length. Changed in version 3.6: Use `Py_FileSystemDefaultEncodeErrors` error handler. `PyObject* PyUnicode_EncodeFSDefault(PyObject *unicode)` *Return value: New reference.*Encode a Unicode object to `Py_FileSystemDefaultEncoding` with the `Py_FileSystemDefaultEncodeErrors` error handler, and return [`bytes`](../library/stdtypes#bytes "bytes"). Note that the resulting [`bytes`](../library/stdtypes#bytes "bytes") object may contain null bytes. If `Py_FileSystemDefaultEncoding` is not set, fall back to the locale encoding. `Py_FileSystemDefaultEncoding` is initialized at startup from the locale encoding and cannot be modified later. If you need to encode a string to the current locale encoding, use [`PyUnicode_EncodeLocale()`](#c.PyUnicode_EncodeLocale "PyUnicode_EncodeLocale"). See also The [`Py_EncodeLocale()`](sys#c.Py_EncodeLocale "Py_EncodeLocale") function. New in version 3.2. Changed in version 3.6: Use `Py_FileSystemDefaultEncodeErrors` error handler. ### wchar\_t Support `wchar_t` support for platforms which support it: `PyObject* PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)` *Return value: New reference.*Create a Unicode object from the `wchar_t` buffer *w* of the given *size*. Passing `-1` as the *size* indicates that the function must itself compute the length, using wcslen. Return `NULL` on failure. `Py_ssize_t PyUnicode_AsWideChar(PyObject *unicode, wchar_t *w, Py_ssize_t size)` Copy the Unicode object contents into the `wchar_t` buffer *w*. At most *size* `wchar_t` characters are copied (excluding a possibly trailing null termination character). Return the number of `wchar_t` characters copied or `-1` in case of an error. Note that the resulting `wchar_t*` string may or may not be null-terminated. It is the responsibility of the caller to make sure that the `wchar_t*` string is null-terminated in case this is required by the application. Also, note that the `wchar_t*` string might contain null characters, which would cause the string to be truncated when used with most C functions. `wchar_t* PyUnicode_AsWideCharString(PyObject *unicode, Py_ssize_t *size)` Convert the Unicode object to a wide character string. The output string always ends with a null character. If *size* is not `NULL`, write the number of wide characters (excluding the trailing null termination character) into *\*size*. Note that the resulting `wchar_t` string might contain null characters, which would cause the string to be truncated when used with most C functions. If *size* is `NULL` and the `wchar_t*` string contains null characters a [`ValueError`](../library/exceptions#ValueError "ValueError") is raised. Returns a buffer allocated by `PyMem_Alloc()` (use [`PyMem_Free()`](memory#c.PyMem_Free "PyMem_Free") to free it) on success. On error, returns `NULL` and *\*size* is undefined. Raises a [`MemoryError`](../library/exceptions#MemoryError "MemoryError") if memory allocation is failed. New in version 3.2. Changed in version 3.7: Raises a [`ValueError`](../library/exceptions#ValueError "ValueError") if *size* is `NULL` and the `wchar_t*` string contains null characters. Built-in Codecs --------------- Python provides a set of built-in codecs which are written in C for speed. All of these codecs are directly usable via the following functions. Many of the following APIs take two arguments encoding and errors, and they have the same semantics as the ones of the built-in [`str()`](../library/stdtypes#str "str") string object constructor. Setting encoding to `NULL` causes the default encoding to be used which is UTF-8. The file system calls should use [`PyUnicode_FSConverter()`](#c.PyUnicode_FSConverter "PyUnicode_FSConverter") for encoding file names. This uses the variable `Py_FileSystemDefaultEncoding` internally. This variable should be treated as read-only: on some systems, it will be a pointer to a static string, on others, it will change at run-time (such as when the application invokes setlocale). Error handling is set by errors which may also be set to `NULL` meaning to use the default handling defined for the codec. Default error handling for all built-in codecs is “strict” ([`ValueError`](../library/exceptions#ValueError "ValueError") is raised). The codecs all use a similar interface. Only deviations from the following generic ones are documented for simplicity. ### Generic Codecs These are the generic codec APIs: `PyObject* PyUnicode_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors)` *Return value: New reference.*Create a Unicode object by decoding *size* bytes of the encoded string *s*. *encoding* and *errors* have the same meaning as the parameters of the same name in the [`str()`](../library/stdtypes#str "str") built-in function. The codec to be used is looked up using the Python codec registry. Return `NULL` if an exception was raised by the codec. `PyObject* PyUnicode_AsEncodedString(PyObject *unicode, const char *encoding, const char *errors)` *Return value: New reference.*Encode a Unicode object and return the result as Python bytes object. *encoding* and *errors* have the same meaning as the parameters of the same name in the Unicode [`encode()`](../library/stdtypes#str.encode "str.encode") method. The codec to be used is looked up using the Python codec registry. Return `NULL` if an exception was raised by the codec. `PyObject* PyUnicode_Encode(const Py_UNICODE *s, Py_ssize_t size, const char *encoding, const char *errors)` *Return value: New reference.*Encode the [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") buffer *s* of the given *size* and return a Python bytes object. *encoding* and *errors* have the same meaning as the parameters of the same name in the Unicode [`encode()`](../library/stdtypes#str.encode "str.encode") method. The codec to be used is looked up using the Python codec registry. Return `NULL` if an exception was raised by the codec. Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") API; please migrate to using [`PyUnicode_AsEncodedString()`](#c.PyUnicode_AsEncodedString "PyUnicode_AsEncodedString"). ### UTF-8 Codecs These are the UTF-8 codec APIs: `PyObject* PyUnicode_DecodeUTF8(const char *s, Py_ssize_t size, const char *errors)` *Return value: New reference.*Create a Unicode object by decoding *size* bytes of the UTF-8 encoded string *s*. Return `NULL` if an exception was raised by the codec. `PyObject* PyUnicode_DecodeUTF8Stateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)` *Return value: New reference.*If *consumed* is `NULL`, behave like [`PyUnicode_DecodeUTF8()`](#c.PyUnicode_DecodeUTF8 "PyUnicode_DecodeUTF8"). If *consumed* is not `NULL`, trailing incomplete UTF-8 byte sequences will not be treated as an error. Those bytes will not be decoded and the number of bytes that have been decoded will be stored in *consumed*. `PyObject* PyUnicode_AsUTF8String(PyObject *unicode)` *Return value: New reference.*Encode a Unicode object using UTF-8 and return the result as Python bytes object. Error handling is “strict”. Return `NULL` if an exception was raised by the codec. `const char* PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *size)` Return a pointer to the UTF-8 encoding of the Unicode object, and store the size of the encoded representation (in bytes) in *size*. The *size* argument can be `NULL`; in this case no size will be stored. The returned buffer always has an extra null byte appended (not included in *size*), regardless of whether there are any other null code points. In the case of an error, `NULL` is returned with an exception set and no *size* is stored. This caches the UTF-8 representation of the string in the Unicode object, and subsequent calls will return a pointer to the same buffer. The caller is not responsible for deallocating the buffer. The buffer is deallocated and pointers to it become invalid when the Unicode object is garbage collected. New in version 3.3. Changed in version 3.7: The return type is now `const char *` rather of `char *`. `const char* PyUnicode_AsUTF8(PyObject *unicode)` As [`PyUnicode_AsUTF8AndSize()`](#c.PyUnicode_AsUTF8AndSize "PyUnicode_AsUTF8AndSize"), but does not store the size. New in version 3.3. Changed in version 3.7: The return type is now `const char *` rather of `char *`. `PyObject* PyUnicode_EncodeUTF8(const Py_UNICODE *s, Py_ssize_t size, const char *errors)` *Return value: New reference.*Encode the [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") buffer *s* of the given *size* using UTF-8 and return a Python bytes object. Return `NULL` if an exception was raised by the codec. Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") API; please migrate to using [`PyUnicode_AsUTF8String()`](#c.PyUnicode_AsUTF8String "PyUnicode_AsUTF8String"), [`PyUnicode_AsUTF8AndSize()`](#c.PyUnicode_AsUTF8AndSize "PyUnicode_AsUTF8AndSize") or [`PyUnicode_AsEncodedString()`](#c.PyUnicode_AsEncodedString "PyUnicode_AsEncodedString"). ### UTF-32 Codecs These are the UTF-32 codec APIs: `PyObject* PyUnicode_DecodeUTF32(const char *s, Py_ssize_t size, const char *errors, int *byteorder)` *Return value: New reference.*Decode *size* bytes from a UTF-32 encoded buffer string and return the corresponding Unicode object. *errors* (if non-`NULL`) defines the error handling. It defaults to “strict”. If *byteorder* is non-`NULL`, the decoder starts decoding using the given byte order: ``` *byteorder == -1: little endian *byteorder == 0: native order *byteorder == 1: big endian ``` If `*byteorder` is zero, and the first four bytes of the input data are a byte order mark (BOM), the decoder switches to this byte order and the BOM is not copied into the resulting Unicode string. If `*byteorder` is `-1` or `1`, any byte order mark is copied to the output. After completion, *\*byteorder* is set to the current byte order at the end of input data. If *byteorder* is `NULL`, the codec starts in native order mode. Return `NULL` if an exception was raised by the codec. `PyObject* PyUnicode_DecodeUTF32Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed)` *Return value: New reference.*If *consumed* is `NULL`, behave like [`PyUnicode_DecodeUTF32()`](#c.PyUnicode_DecodeUTF32 "PyUnicode_DecodeUTF32"). If *consumed* is not `NULL`, [`PyUnicode_DecodeUTF32Stateful()`](#c.PyUnicode_DecodeUTF32Stateful "PyUnicode_DecodeUTF32Stateful") will not treat trailing incomplete UTF-32 byte sequences (such as a number of bytes not divisible by four) as an error. Those bytes will not be decoded and the number of bytes that have been decoded will be stored in *consumed*. `PyObject* PyUnicode_AsUTF32String(PyObject *unicode)` *Return value: New reference.*Return a Python byte string using the UTF-32 encoding in native byte order. The string always starts with a BOM mark. Error handling is “strict”. Return `NULL` if an exception was raised by the codec. `PyObject* PyUnicode_EncodeUTF32(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder)` *Return value: New reference.*Return a Python bytes object holding the UTF-32 encoded value of the Unicode data in *s*. Output is written according to the following byte order: ``` byteorder == -1: little endian byteorder == 0: native byte order (writes a BOM mark) byteorder == 1: big endian ``` If byteorder is `0`, the output string will always start with the Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is prepended. If `Py_UNICODE_WIDE` is not defined, surrogate pairs will be output as a single code point. Return `NULL` if an exception was raised by the codec. Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") API; please migrate to using [`PyUnicode_AsUTF32String()`](#c.PyUnicode_AsUTF32String "PyUnicode_AsUTF32String") or [`PyUnicode_AsEncodedString()`](#c.PyUnicode_AsEncodedString "PyUnicode_AsEncodedString"). ### UTF-16 Codecs These are the UTF-16 codec APIs: `PyObject* PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors, int *byteorder)` *Return value: New reference.*Decode *size* bytes from a UTF-16 encoded buffer string and return the corresponding Unicode object. *errors* (if non-`NULL`) defines the error handling. It defaults to “strict”. If *byteorder* is non-`NULL`, the decoder starts decoding using the given byte order: ``` *byteorder == -1: little endian *byteorder == 0: native order *byteorder == 1: big endian ``` If `*byteorder` is zero, and the first two bytes of the input data are a byte order mark (BOM), the decoder switches to this byte order and the BOM is not copied into the resulting Unicode string. If `*byteorder` is `-1` or `1`, any byte order mark is copied to the output (where it will result in either a `\ufeff` or a `\ufffe` character). After completion, `*byteorder` is set to the current byte order at the end of input data. If *byteorder* is `NULL`, the codec starts in native order mode. Return `NULL` if an exception was raised by the codec. `PyObject* PyUnicode_DecodeUTF16Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed)` *Return value: New reference.*If *consumed* is `NULL`, behave like [`PyUnicode_DecodeUTF16()`](#c.PyUnicode_DecodeUTF16 "PyUnicode_DecodeUTF16"). If *consumed* is not `NULL`, [`PyUnicode_DecodeUTF16Stateful()`](#c.PyUnicode_DecodeUTF16Stateful "PyUnicode_DecodeUTF16Stateful") will not treat trailing incomplete UTF-16 byte sequences (such as an odd number of bytes or a split surrogate pair) as an error. Those bytes will not be decoded and the number of bytes that have been decoded will be stored in *consumed*. `PyObject* PyUnicode_AsUTF16String(PyObject *unicode)` *Return value: New reference.*Return a Python byte string using the UTF-16 encoding in native byte order. The string always starts with a BOM mark. Error handling is “strict”. Return `NULL` if an exception was raised by the codec. `PyObject* PyUnicode_EncodeUTF16(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder)` *Return value: New reference.*Return a Python bytes object holding the UTF-16 encoded value of the Unicode data in *s*. Output is written according to the following byte order: ``` byteorder == -1: little endian byteorder == 0: native byte order (writes a BOM mark) byteorder == 1: big endian ``` If byteorder is `0`, the output string will always start with the Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is prepended. If `Py_UNICODE_WIDE` is defined, a single [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") value may get represented as a surrogate pair. If it is not defined, each [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") values is interpreted as a UCS-2 character. Return `NULL` if an exception was raised by the codec. Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") API; please migrate to using [`PyUnicode_AsUTF16String()`](#c.PyUnicode_AsUTF16String "PyUnicode_AsUTF16String") or [`PyUnicode_AsEncodedString()`](#c.PyUnicode_AsEncodedString "PyUnicode_AsEncodedString"). ### UTF-7 Codecs These are the UTF-7 codec APIs: `PyObject* PyUnicode_DecodeUTF7(const char *s, Py_ssize_t size, const char *errors)` *Return value: New reference.*Create a Unicode object by decoding *size* bytes of the UTF-7 encoded string *s*. Return `NULL` if an exception was raised by the codec. `PyObject* PyUnicode_DecodeUTF7Stateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)` *Return value: New reference.*If *consumed* is `NULL`, behave like [`PyUnicode_DecodeUTF7()`](#c.PyUnicode_DecodeUTF7 "PyUnicode_DecodeUTF7"). If *consumed* is not `NULL`, trailing incomplete UTF-7 base-64 sections will not be treated as an error. Those bytes will not be decoded and the number of bytes that have been decoded will be stored in *consumed*. `PyObject* PyUnicode_EncodeUTF7(const Py_UNICODE *s, Py_ssize_t size, int base64SetO, int base64WhiteSpace, const char *errors)` *Return value: New reference.*Encode the [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") buffer of the given size using UTF-7 and return a Python bytes object. Return `NULL` if an exception was raised by the codec. If *base64SetO* is nonzero, “Set O” (punctuation that has no otherwise special meaning) will be encoded in base-64. If *base64WhiteSpace* is nonzero, whitespace will be encoded in base-64. Both are set to zero for the Python “utf-7” codec. Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") API; please migrate to using [`PyUnicode_AsEncodedString()`](#c.PyUnicode_AsEncodedString "PyUnicode_AsEncodedString"). ### Unicode-Escape Codecs These are the “Unicode Escape” codec APIs: `PyObject* PyUnicode_DecodeUnicodeEscape(const char *s, Py_ssize_t size, const char *errors)` *Return value: New reference.*Create a Unicode object by decoding *size* bytes of the Unicode-Escape encoded string *s*. Return `NULL` if an exception was raised by the codec. `PyObject* PyUnicode_AsUnicodeEscapeString(PyObject *unicode)` *Return value: New reference.*Encode a Unicode object using Unicode-Escape and return the result as a bytes object. Error handling is “strict”. Return `NULL` if an exception was raised by the codec. `PyObject* PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size)` *Return value: New reference.*Encode the [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") buffer of the given *size* using Unicode-Escape and return a bytes object. Return `NULL` if an exception was raised by the codec. Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") API; please migrate to using [`PyUnicode_AsUnicodeEscapeString()`](#c.PyUnicode_AsUnicodeEscapeString "PyUnicode_AsUnicodeEscapeString"). ### Raw-Unicode-Escape Codecs These are the “Raw Unicode Escape” codec APIs: `PyObject* PyUnicode_DecodeRawUnicodeEscape(const char *s, Py_ssize_t size, const char *errors)` *Return value: New reference.*Create a Unicode object by decoding *size* bytes of the Raw-Unicode-Escape encoded string *s*. Return `NULL` if an exception was raised by the codec. `PyObject* PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)` *Return value: New reference.*Encode a Unicode object using Raw-Unicode-Escape and return the result as a bytes object. Error handling is “strict”. Return `NULL` if an exception was raised by the codec. `PyObject* PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size)` *Return value: New reference.*Encode the [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") buffer of the given *size* using Raw-Unicode-Escape and return a bytes object. Return `NULL` if an exception was raised by the codec. Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") API; please migrate to using [`PyUnicode_AsRawUnicodeEscapeString()`](#c.PyUnicode_AsRawUnicodeEscapeString "PyUnicode_AsRawUnicodeEscapeString") or [`PyUnicode_AsEncodedString()`](#c.PyUnicode_AsEncodedString "PyUnicode_AsEncodedString"). ### Latin-1 Codecs These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 Unicode ordinals and only these are accepted by the codecs during encoding. `PyObject* PyUnicode_DecodeLatin1(const char *s, Py_ssize_t size, const char *errors)` *Return value: New reference.*Create a Unicode object by decoding *size* bytes of the Latin-1 encoded string *s*. Return `NULL` if an exception was raised by the codec. `PyObject* PyUnicode_AsLatin1String(PyObject *unicode)` *Return value: New reference.*Encode a Unicode object using Latin-1 and return the result as Python bytes object. Error handling is “strict”. Return `NULL` if an exception was raised by the codec. `PyObject* PyUnicode_EncodeLatin1(const Py_UNICODE *s, Py_ssize_t size, const char *errors)` *Return value: New reference.*Encode the [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") buffer of the given *size* using Latin-1 and return a Python bytes object. Return `NULL` if an exception was raised by the codec. Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") API; please migrate to using [`PyUnicode_AsLatin1String()`](#c.PyUnicode_AsLatin1String "PyUnicode_AsLatin1String") or [`PyUnicode_AsEncodedString()`](#c.PyUnicode_AsEncodedString "PyUnicode_AsEncodedString"). ### ASCII Codecs These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All other codes generate errors. `PyObject* PyUnicode_DecodeASCII(const char *s, Py_ssize_t size, const char *errors)` *Return value: New reference.*Create a Unicode object by decoding *size* bytes of the ASCII encoded string *s*. Return `NULL` if an exception was raised by the codec. `PyObject* PyUnicode_AsASCIIString(PyObject *unicode)` *Return value: New reference.*Encode a Unicode object using ASCII and return the result as Python bytes object. Error handling is “strict”. Return `NULL` if an exception was raised by the codec. `PyObject* PyUnicode_EncodeASCII(const Py_UNICODE *s, Py_ssize_t size, const char *errors)` *Return value: New reference.*Encode the [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") buffer of the given *size* using ASCII and return a Python bytes object. Return `NULL` if an exception was raised by the codec. Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") API; please migrate to using [`PyUnicode_AsASCIIString()`](#c.PyUnicode_AsASCIIString "PyUnicode_AsASCIIString") or [`PyUnicode_AsEncodedString()`](#c.PyUnicode_AsEncodedString "PyUnicode_AsEncodedString"). ### Character Map Codecs This codec is special in that it can be used to implement many different codecs (and this is in fact what was done to obtain most of the standard codecs included in the `encodings` package). The codec uses mappings to encode and decode characters. The mapping objects provided must support the [`__getitem__()`](../reference/datamodel#object.__getitem__ "object.__getitem__") mapping interface; dictionaries and sequences work well. These are the mapping codec APIs: `PyObject* PyUnicode_DecodeCharmap(const char *data, Py_ssize_t size, PyObject *mapping, const char *errors)` *Return value: New reference.*Create a Unicode object by decoding *size* bytes of the encoded string *s* using the given *mapping* object. Return `NULL` if an exception was raised by the codec. If *mapping* is `NULL`, Latin-1 decoding will be applied. Else *mapping* must map bytes ordinals (integers in the range from 0 to 255) to Unicode strings, integers (which are then interpreted as Unicode ordinals) or `None`. Unmapped data bytes – ones which cause a [`LookupError`](../library/exceptions#LookupError "LookupError"), as well as ones which get mapped to `None`, `0xFFFE` or `'\ufffe'`, are treated as undefined mappings and cause an error. `PyObject* PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping)` *Return value: New reference.*Encode a Unicode object using the given *mapping* object and return the result as a bytes object. Error handling is “strict”. Return `NULL` if an exception was raised by the codec. The *mapping* object must map Unicode ordinal integers to bytes objects, integers in the range from 0 to 255 or `None`. Unmapped character ordinals (ones which cause a [`LookupError`](../library/exceptions#LookupError "LookupError")) as well as mapped to `None` are treated as “undefined mapping” and cause an error. `PyObject* PyUnicode_EncodeCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *mapping, const char *errors)` *Return value: New reference.*Encode the [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") buffer of the given *size* using the given *mapping* object and return the result as a bytes object. Return `NULL` if an exception was raised by the codec. Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") API; please migrate to using [`PyUnicode_AsCharmapString()`](#c.PyUnicode_AsCharmapString "PyUnicode_AsCharmapString") or [`PyUnicode_AsEncodedString()`](#c.PyUnicode_AsEncodedString "PyUnicode_AsEncodedString"). The following codec API is special in that maps Unicode to Unicode. `PyObject* PyUnicode_Translate(PyObject *str, PyObject *table, const char *errors)` *Return value: New reference.*Translate a string by applying a character mapping table to it and return the resulting Unicode object. Return `NULL` if an exception was raised by the codec. The mapping table must map Unicode ordinal integers to Unicode ordinal integers or `None` (causing deletion of the character). Mapping tables need only provide the [`__getitem__()`](../reference/datamodel#object.__getitem__ "object.__getitem__") interface; dictionaries and sequences work well. Unmapped character ordinals (ones which cause a [`LookupError`](../library/exceptions#LookupError "LookupError")) are left untouched and are copied as-is. *errors* has the usual meaning for codecs. It may be `NULL` which indicates to use the default error handling. `PyObject* PyUnicode_TranslateCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *mapping, const char *errors)` *Return value: New reference.*Translate a [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") buffer of the given *size* by applying a character *mapping* table to it and return the resulting Unicode object. Return `NULL` when an exception was raised by the codec. Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") API; please migrate to using [`PyUnicode_Translate()`](#c.PyUnicode_Translate "PyUnicode_Translate"). or [generic codec based API](codec#codec-registry) ### MBCS codecs for Windows These are the MBCS codec APIs. They are currently only available on Windows and use the Win32 MBCS converters to implement the conversions. Note that MBCS (or DBCS) is a class of encodings, not just one. The target encoding is defined by the user settings on the machine running the codec. `PyObject* PyUnicode_DecodeMBCS(const char *s, Py_ssize_t size, const char *errors)` *Return value: New reference.*Create a Unicode object by decoding *size* bytes of the MBCS encoded string *s*. Return `NULL` if an exception was raised by the codec. `PyObject* PyUnicode_DecodeMBCSStateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)` *Return value: New reference.*If *consumed* is `NULL`, behave like [`PyUnicode_DecodeMBCS()`](#c.PyUnicode_DecodeMBCS "PyUnicode_DecodeMBCS"). If *consumed* is not `NULL`, [`PyUnicode_DecodeMBCSStateful()`](#c.PyUnicode_DecodeMBCSStateful "PyUnicode_DecodeMBCSStateful") will not decode trailing lead byte and the number of bytes that have been decoded will be stored in *consumed*. `PyObject* PyUnicode_AsMBCSString(PyObject *unicode)` *Return value: New reference.*Encode a Unicode object using MBCS and return the result as Python bytes object. Error handling is “strict”. Return `NULL` if an exception was raised by the codec. `PyObject* PyUnicode_EncodeCodePage(int code_page, PyObject *unicode, const char *errors)` *Return value: New reference.*Encode the Unicode object using the specified code page and return a Python bytes object. Return `NULL` if an exception was raised by the codec. Use `CP_ACP` code page to get the MBCS encoder. New in version 3.3. `PyObject* PyUnicode_EncodeMBCS(const Py_UNICODE *s, Py_ssize_t size, const char *errors)` *Return value: New reference.*Encode the [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") buffer of the given *size* using MBCS and return a Python bytes object. Return `NULL` if an exception was raised by the codec. Deprecated since version 3.3, will be removed in version 4.0: Part of the old-style [`Py_UNICODE`](#c.Py_UNICODE "Py_UNICODE") API; please migrate to using [`PyUnicode_AsMBCSString()`](#c.PyUnicode_AsMBCSString "PyUnicode_AsMBCSString"), [`PyUnicode_EncodeCodePage()`](#c.PyUnicode_EncodeCodePage "PyUnicode_EncodeCodePage") or [`PyUnicode_AsEncodedString()`](#c.PyUnicode_AsEncodedString "PyUnicode_AsEncodedString"). ### Methods & Slots Methods and Slot Functions -------------------------- The following APIs are capable of handling Unicode objects and strings on input (we refer to them as strings in the descriptions) and return Unicode objects or integers as appropriate. They all return `NULL` or `-1` if an exception occurs. `PyObject* PyUnicode_Concat(PyObject *left, PyObject *right)` *Return value: New reference.*Concat two strings giving a new Unicode string. `PyObject* PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)` *Return value: New reference.*Split a string giving a list of Unicode strings. If *sep* is `NULL`, splitting will be done at all whitespace substrings. Otherwise, splits occur at the given separator. At most *maxsplit* splits will be done. If negative, no limit is set. Separators are not included in the resulting list. `PyObject* PyUnicode_Splitlines(PyObject *s, int keepend)` *Return value: New reference.*Split a Unicode string at line breaks, returning a list of Unicode strings. CRLF is considered to be one line break. If *keepend* is `0`, the line break characters are not included in the resulting strings. `PyObject* PyUnicode_Join(PyObject *separator, PyObject *seq)` *Return value: New reference.*Join a sequence of strings using the given *separator* and return the resulting Unicode string. `Py_ssize_t PyUnicode_Tailmatch(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)` Return `1` if *substr* matches `str[start:end]` at the given tail end (*direction* == `-1` means to do a prefix match, *direction* == `1` a suffix match), `0` otherwise. Return `-1` if an error occurred. `Py_ssize_t PyUnicode_Find(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)` Return the first position of *substr* in `str[start:end]` using the given *direction* (*direction* == `1` means to do a forward search, *direction* == `-1` a backward search). The return value is the index of the first match; a value of `-1` indicates that no match was found, and `-2` indicates that an error occurred and an exception has been set. `Py_ssize_t PyUnicode_FindChar(PyObject *str, Py_UCS4 ch, Py_ssize_t start, Py_ssize_t end, int direction)` Return the first position of the character *ch* in `str[start:end]` using the given *direction* (*direction* == `1` means to do a forward search, *direction* == `-1` a backward search). The return value is the index of the first match; a value of `-1` indicates that no match was found, and `-2` indicates that an error occurred and an exception has been set. New in version 3.3. Changed in version 3.7: *start* and *end* are now adjusted to behave like `str[start:end]`. `Py_ssize_t PyUnicode_Count(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end)` Return the number of non-overlapping occurrences of *substr* in `str[start:end]`. Return `-1` if an error occurred. `PyObject* PyUnicode_Replace(PyObject *str, PyObject *substr, PyObject *replstr, Py_ssize_t maxcount)` *Return value: New reference.*Replace at most *maxcount* occurrences of *substr* in *str* with *replstr* and return the resulting Unicode object. *maxcount* == `-1` means replace all occurrences. `int PyUnicode_Compare(PyObject *left, PyObject *right)` Compare two strings and return `-1`, `0`, `1` for less than, equal, and greater than, respectively. This function returns `-1` upon failure, so one should call [`PyErr_Occurred()`](exceptions#c.PyErr_Occurred "PyErr_Occurred") to check for errors. `int PyUnicode_CompareWithASCIIString(PyObject *uni, const char *string)` Compare a Unicode object, *uni*, with *string* and return `-1`, `0`, `1` for less than, equal, and greater than, respectively. It is best to pass only ASCII-encoded strings, but the function interprets the input string as ISO-8859-1 if it contains non-ASCII characters. This function does not raise exceptions. `PyObject* PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)` *Return value: New reference.*Rich compare two Unicode strings and return one of the following: * `NULL` in case an exception was raised * `Py_True` or `Py_False` for successful comparisons * `Py_NotImplemented` in case the type combination is unknown Possible values for *op* are `Py_GT`, `Py_GE`, `Py_EQ`, `Py_NE`, `Py_LT`, and `Py_LE`. `PyObject* PyUnicode_Format(PyObject *format, PyObject *args)` *Return value: New reference.*Return a new string object from *format* and *args*; this is analogous to `format % args`. `int PyUnicode_Contains(PyObject *container, PyObject *element)` Check whether *element* is contained in *container* and return true or false accordingly. *element* has to coerce to a one element Unicode string. `-1` is returned if there was an error. `void PyUnicode_InternInPlace(PyObject **string)` Intern the argument *\*string* in place. The argument must be the address of a pointer variable pointing to a Python Unicode string object. If there is an existing interned string that is the same as *\*string*, it sets *\*string* to it (decrementing the reference count of the old string object and incrementing the reference count of the interned string object), otherwise it leaves *\*string* alone and interns it (incrementing its reference count). (Clarification: even though there is a lot of talk about reference counts, think of this function as reference-count-neutral; you own the object after the call if and only if you owned it before the call.) `PyObject* PyUnicode_InternFromString(const char *v)` *Return value: New reference.*A combination of [`PyUnicode_FromString()`](#c.PyUnicode_FromString "PyUnicode_FromString") and [`PyUnicode_InternInPlace()`](#c.PyUnicode_InternInPlace "PyUnicode_InternInPlace"), returning either a new Unicode string object that has been interned, or a new (“owned”) reference to an earlier interned string object with the same value.
programming_docs
python Number Protocol Number Protocol =============== `int PyNumber_Check(PyObject *o)` Returns `1` if the object *o* provides numeric protocols, and false otherwise. This function always succeeds. Changed in version 3.8: Returns `1` if *o* is an index integer. `PyObject* PyNumber_Add(PyObject *o1, PyObject *o2)` *Return value: New reference.*Returns the result of adding *o1* and *o2*, or `NULL` on failure. This is the equivalent of the Python expression `o1 + o2`. `PyObject* PyNumber_Subtract(PyObject *o1, PyObject *o2)` *Return value: New reference.*Returns the result of subtracting *o2* from *o1*, or `NULL` on failure. This is the equivalent of the Python expression `o1 - o2`. `PyObject* PyNumber_Multiply(PyObject *o1, PyObject *o2)` *Return value: New reference.*Returns the result of multiplying *o1* and *o2*, or `NULL` on failure. This is the equivalent of the Python expression `o1 * o2`. `PyObject* PyNumber_MatrixMultiply(PyObject *o1, PyObject *o2)` *Return value: New reference.*Returns the result of matrix multiplication on *o1* and *o2*, or `NULL` on failure. This is the equivalent of the Python expression `o1 @ o2`. New in version 3.5. `PyObject* PyNumber_FloorDivide(PyObject *o1, PyObject *o2)` *Return value: New reference.*Return the floor of *o1* divided by *o2*, or `NULL` on failure. This is the equivalent of the Python expression `o1 // o2`. `PyObject* PyNumber_TrueDivide(PyObject *o1, PyObject *o2)` *Return value: New reference.*Return a reasonable approximation for the mathematical value of *o1* divided by *o2*, or `NULL` on failure. The return value is “approximate” because binary floating point numbers are approximate; it is not possible to represent all real numbers in base two. This function can return a floating point value when passed two integers. This is the equivalent of the Python expression `o1 / o2`. `PyObject* PyNumber_Remainder(PyObject *o1, PyObject *o2)` *Return value: New reference.*Returns the remainder of dividing *o1* by *o2*, or `NULL` on failure. This is the equivalent of the Python expression `o1 % o2`. `PyObject* PyNumber_Divmod(PyObject *o1, PyObject *o2)` *Return value: New reference.*See the built-in function [`divmod()`](../library/functions#divmod "divmod"). Returns `NULL` on failure. This is the equivalent of the Python expression `divmod(o1, o2)`. `PyObject* PyNumber_Power(PyObject *o1, PyObject *o2, PyObject *o3)` *Return value: New reference.*See the built-in function [`pow()`](../library/functions#pow "pow"). Returns `NULL` on failure. This is the equivalent of the Python expression `pow(o1, o2, o3)`, where *o3* is optional. If *o3* is to be ignored, pass [`Py_None`](none#c.Py_None "Py_None") in its place (passing `NULL` for *o3* would cause an illegal memory access). `PyObject* PyNumber_Negative(PyObject *o)` *Return value: New reference.*Returns the negation of *o* on success, or `NULL` on failure. This is the equivalent of the Python expression `-o`. `PyObject* PyNumber_Positive(PyObject *o)` *Return value: New reference.*Returns *o* on success, or `NULL` on failure. This is the equivalent of the Python expression `+o`. `PyObject* PyNumber_Absolute(PyObject *o)` *Return value: New reference.*Returns the absolute value of *o*, or `NULL` on failure. This is the equivalent of the Python expression `abs(o)`. `PyObject* PyNumber_Invert(PyObject *o)` *Return value: New reference.*Returns the bitwise negation of *o* on success, or `NULL` on failure. This is the equivalent of the Python expression `~o`. `PyObject* PyNumber_Lshift(PyObject *o1, PyObject *o2)` *Return value: New reference.*Returns the result of left shifting *o1* by *o2* on success, or `NULL` on failure. This is the equivalent of the Python expression `o1 << o2`. `PyObject* PyNumber_Rshift(PyObject *o1, PyObject *o2)` *Return value: New reference.*Returns the result of right shifting *o1* by *o2* on success, or `NULL` on failure. This is the equivalent of the Python expression `o1 >> o2`. `PyObject* PyNumber_And(PyObject *o1, PyObject *o2)` *Return value: New reference.*Returns the “bitwise and” of *o1* and *o2* on success and `NULL` on failure. This is the equivalent of the Python expression `o1 & o2`. `PyObject* PyNumber_Xor(PyObject *o1, PyObject *o2)` *Return value: New reference.*Returns the “bitwise exclusive or” of *o1* by *o2* on success, or `NULL` on failure. This is the equivalent of the Python expression `o1 ^ o2`. `PyObject* PyNumber_Or(PyObject *o1, PyObject *o2)` *Return value: New reference.*Returns the “bitwise or” of *o1* and *o2* on success, or `NULL` on failure. This is the equivalent of the Python expression `o1 | o2`. `PyObject* PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2)` *Return value: New reference.*Returns the result of adding *o1* and *o2*, or `NULL` on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement `o1 += o2`. `PyObject* PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2)` *Return value: New reference.*Returns the result of subtracting *o2* from *o1*, or `NULL` on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement `o1 -= o2`. `PyObject* PyNumber_InPlaceMultiply(PyObject *o1, PyObject *o2)` *Return value: New reference.*Returns the result of multiplying *o1* and *o2*, or `NULL` on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement `o1 *= o2`. `PyObject* PyNumber_InPlaceMatrixMultiply(PyObject *o1, PyObject *o2)` *Return value: New reference.*Returns the result of matrix multiplication on *o1* and *o2*, or `NULL` on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement `o1 @= o2`. New in version 3.5. `PyObject* PyNumber_InPlaceFloorDivide(PyObject *o1, PyObject *o2)` *Return value: New reference.*Returns the mathematical floor of dividing *o1* by *o2*, or `NULL` on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement `o1 //= o2`. `PyObject* PyNumber_InPlaceTrueDivide(PyObject *o1, PyObject *o2)` *Return value: New reference.*Return a reasonable approximation for the mathematical value of *o1* divided by *o2*, or `NULL` on failure. The return value is “approximate” because binary floating point numbers are approximate; it is not possible to represent all real numbers in base two. This function can return a floating point value when passed two integers. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement `o1 /= o2`. `PyObject* PyNumber_InPlaceRemainder(PyObject *o1, PyObject *o2)` *Return value: New reference.*Returns the remainder of dividing *o1* by *o2*, or `NULL` on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement `o1 %= o2`. `PyObject* PyNumber_InPlacePower(PyObject *o1, PyObject *o2, PyObject *o3)` *Return value: New reference.*See the built-in function [`pow()`](../library/functions#pow "pow"). Returns `NULL` on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement `o1 **= o2` when o3 is [`Py_None`](none#c.Py_None "Py_None"), or an in-place variant of `pow(o1, o2, o3)` otherwise. If *o3* is to be ignored, pass [`Py_None`](none#c.Py_None "Py_None") in its place (passing `NULL` for *o3* would cause an illegal memory access). `PyObject* PyNumber_InPlaceLshift(PyObject *o1, PyObject *o2)` *Return value: New reference.*Returns the result of left shifting *o1* by *o2* on success, or `NULL` on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement `o1 <<= o2`. `PyObject* PyNumber_InPlaceRshift(PyObject *o1, PyObject *o2)` *Return value: New reference.*Returns the result of right shifting *o1* by *o2* on success, or `NULL` on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement `o1 >>= o2`. `PyObject* PyNumber_InPlaceAnd(PyObject *o1, PyObject *o2)` *Return value: New reference.*Returns the “bitwise and” of *o1* and *o2* on success and `NULL` on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement `o1 &= o2`. `PyObject* PyNumber_InPlaceXor(PyObject *o1, PyObject *o2)` *Return value: New reference.*Returns the “bitwise exclusive or” of *o1* by *o2* on success, or `NULL` on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement `o1 ^= o2`. `PyObject* PyNumber_InPlaceOr(PyObject *o1, PyObject *o2)` *Return value: New reference.*Returns the “bitwise or” of *o1* and *o2* on success, or `NULL` on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement `o1 |= o2`. `PyObject* PyNumber_Long(PyObject *o)` *Return value: New reference.*Returns the *o* converted to an integer object on success, or `NULL` on failure. This is the equivalent of the Python expression `int(o)`. `PyObject* PyNumber_Float(PyObject *o)` *Return value: New reference.*Returns the *o* converted to a float object on success, or `NULL` on failure. This is the equivalent of the Python expression `float(o)`. `PyObject* PyNumber_Index(PyObject *o)` *Return value: New reference.*Returns the *o* converted to a Python int on success or `NULL` with a [`TypeError`](../library/exceptions#TypeError "TypeError") exception raised on failure. `PyObject* PyNumber_ToBase(PyObject *n, int base)` *Return value: New reference.*Returns the integer *n* converted to base *base* as a string. The *base* argument must be one of 2, 8, 10, or 16. For base 2, 8, or 16, the returned string is prefixed with a base marker of `'0b'`, `'0o'`, or `'0x'`, respectively. If *n* is not a Python int, it is converted with [`PyNumber_Index()`](#c.PyNumber_Index "PyNumber_Index") first. `Py_ssize_t PyNumber_AsSsize_t(PyObject *o, PyObject *exc)` Returns *o* converted to a [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t") value if *o* can be interpreted as an integer. If the call fails, an exception is raised and `-1` is returned. If *o* can be converted to a Python int but the attempt to convert to a [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t") value would raise an [`OverflowError`](../library/exceptions#OverflowError "OverflowError"), then the *exc* argument is the type of exception that will be raised (usually [`IndexError`](../library/exceptions#IndexError "IndexError") or [`OverflowError`](../library/exceptions#OverflowError "OverflowError")). If *exc* is `NULL`, then the exception is cleared and the value is clipped to `PY_SSIZE_T_MIN` for a negative integer or `PY_SSIZE_T_MAX` for a positive integer. `int PyIndex_Check(PyObject *o)` Returns `1` if *o* is an index integer (has the `nb_index` slot of the `tp_as_number` structure filled in), and `0` otherwise. This function always succeeds. python Call Protocol Call Protocol ============= CPython supports two different calling protocols: *tp\_call* and vectorcall. The *tp\_call* Protocol ----------------------- Instances of classes that set [`tp_call`](typeobj#c.PyTypeObject.tp_call "PyTypeObject.tp_call") are callable. The signature of the slot is: ``` PyObject *tp_call(PyObject *callable, PyObject *args, PyObject *kwargs); ``` A call is made using a tuple for the positional arguments and a dict for the keyword arguments, similarly to `callable(*args, **kwargs)` in Python code. *args* must be non-NULL (use an empty tuple if there are no arguments) but *kwargs* may be *NULL* if there are no keyword arguments. This convention is not only used by *tp\_call*: [`tp_new`](typeobj#c.PyTypeObject.tp_new "PyTypeObject.tp_new") and [`tp_init`](typeobj#c.PyTypeObject.tp_init "PyTypeObject.tp_init") also pass arguments this way. To call an object, use [`PyObject_Call()`](#c.PyObject_Call "PyObject_Call") or another [call API](#capi-call). The Vectorcall Protocol ----------------------- New in version 3.9. The vectorcall protocol was introduced in [**PEP 590**](https://www.python.org/dev/peps/pep-0590) as an additional protocol for making calls more efficient. As rule of thumb, CPython will prefer the vectorcall for internal calls if the callable supports it. However, this is not a hard rule. Additionally, some third-party extensions use *tp\_call* directly (rather than using [`PyObject_Call()`](#c.PyObject_Call "PyObject_Call")). Therefore, a class supporting vectorcall must also implement [`tp_call`](typeobj#c.PyTypeObject.tp_call "PyTypeObject.tp_call"). Moreover, the callable must behave the same regardless of which protocol is used. The recommended way to achieve this is by setting [`tp_call`](typeobj#c.PyTypeObject.tp_call "PyTypeObject.tp_call") to [`PyVectorcall_Call()`](#c.PyVectorcall_Call "PyVectorcall_Call"). This bears repeating: Warning A class supporting vectorcall **must** also implement [`tp_call`](typeobj#c.PyTypeObject.tp_call "PyTypeObject.tp_call") with the same semantics. A class should not implement vectorcall if that would be slower than *tp\_call*. For example, if the callee needs to convert the arguments to an args tuple and kwargs dict anyway, then there is no point in implementing vectorcall. Classes can implement the vectorcall protocol by enabling the [`Py_TPFLAGS_HAVE_VECTORCALL`](typeobj#Py_TPFLAGS_HAVE_VECTORCALL "Py_TPFLAGS_HAVE_VECTORCALL") flag and setting [`tp_vectorcall_offset`](typeobj#c.PyTypeObject.tp_vectorcall_offset "PyTypeObject.tp_vectorcall_offset") to the offset inside the object structure where a *vectorcallfunc* appears. This is a pointer to a function with the following signature: `PyObject *(*vectorcallfunc)(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject *kwnames)` * *callable* is the object being called. * *args* is a C array consisting of the positional arguments followed by the values of the keyword arguments. This can be *NULL* if there are no arguments. * *nargsf* is the number of positional arguments plus possibly the `PY_VECTORCALL_ARGUMENTS_OFFSET` flag. To get the actual number of positional arguments from *nargsf*, use [`PyVectorcall_NARGS()`](#c.PyVectorcall_NARGS "PyVectorcall_NARGS"). * *kwnames* is a tuple containing the names of the keyword arguments; in other words, the keys of the kwargs dict. These names must be strings (instances of `str` or a subclass) and they must be unique. If there are no keyword arguments, then *kwnames* can instead be *NULL*. `PY_VECTORCALL_ARGUMENTS_OFFSET` If this flag is set in a vectorcall *nargsf* argument, the callee is allowed to temporarily change `args[-1]`. In other words, *args* points to argument 1 (not 0) in the allocated vector. The callee must restore the value of `args[-1]` before returning. For [`PyObject_VectorcallMethod()`](#c.PyObject_VectorcallMethod "PyObject_VectorcallMethod"), this flag means instead that `args[0]` may be changed. Whenever they can do so cheaply (without additional allocation), callers are encouraged to use `PY_VECTORCALL_ARGUMENTS_OFFSET`. Doing so will allow callables such as bound methods to make their onward calls (which include a prepended *self* argument) very efficiently. To call an object that implements vectorcall, use a [call API](#capi-call) function as with any other callable. [`PyObject_Vectorcall()`](#c.PyObject_Vectorcall "PyObject_Vectorcall") will usually be most efficient. Note In CPython 3.8, the vectorcall API and related functions were available provisionally under names with a leading underscore: `_PyObject_Vectorcall`, `_Py_TPFLAGS_HAVE_VECTORCALL`, `_PyObject_VectorcallMethod`, `_PyVectorcall_Function`, `_PyObject_CallOneArg`, `_PyObject_CallMethodNoArgs`, `_PyObject_CallMethodOneArg`. Additionally, `PyObject_VectorcallDict` was available as `_PyObject_FastCallDict`. The old names are still defined as aliases of the new, non-underscored names. ### Recursion Control When using *tp\_call*, callees do not need to worry about [recursion](exceptions#recursion): CPython uses [`Py_EnterRecursiveCall()`](exceptions#c.Py_EnterRecursiveCall "Py_EnterRecursiveCall") and [`Py_LeaveRecursiveCall()`](exceptions#c.Py_LeaveRecursiveCall "Py_LeaveRecursiveCall") for calls made using *tp\_call*. For efficiency, this is not the case for calls done using vectorcall: the callee should use *Py\_EnterRecursiveCall* and *Py\_LeaveRecursiveCall* if needed. ### Vectorcall Support API `Py_ssize_t PyVectorcall_NARGS(size_t nargsf)` Given a vectorcall *nargsf* argument, return the actual number of arguments. Currently equivalent to: ``` (Py_ssize_t)(nargsf & ~PY_VECTORCALL_ARGUMENTS_OFFSET) ``` However, the function `PyVectorcall_NARGS` should be used to allow for future extensions. This function is not part of the [limited API](stable#stable). New in version 3.8. `vectorcallfunc PyVectorcall_Function(PyObject *op)` If *op* does not support the vectorcall protocol (either because the type does not or because the specific instance does not), return *NULL*. Otherwise, return the vectorcall function pointer stored in *op*. This function never raises an exception. This is mostly useful to check whether or not *op* supports vectorcall, which can be done by checking `PyVectorcall_Function(op) != NULL`. This function is not part of the [limited API](stable#stable). New in version 3.8. `PyObject* PyVectorcall_Call(PyObject *callable, PyObject *tuple, PyObject *dict)` Call *callable*’s [`vectorcallfunc`](#c.vectorcallfunc "vectorcallfunc") with positional and keyword arguments given in a tuple and dict, respectively. This is a specialized function, intended to be put in the [`tp_call`](typeobj#c.PyTypeObject.tp_call "PyTypeObject.tp_call") slot or be used in an implementation of `tp_call`. It does not check the [`Py_TPFLAGS_HAVE_VECTORCALL`](typeobj#Py_TPFLAGS_HAVE_VECTORCALL "Py_TPFLAGS_HAVE_VECTORCALL") flag and it does not fall back to `tp_call`. This function is not part of the [limited API](stable#stable). New in version 3.8. Object Calling API ------------------ Various functions are available for calling a Python object. Each converts its arguments to a convention supported by the called object – either *tp\_call* or vectorcall. In order to do as little conversion as possible, pick one that best fits the format of data you have available. The following table summarizes the available functions; please see individual documentation for details. | Function | callable | args | kwargs | | --- | --- | --- | --- | | [`PyObject_Call()`](#c.PyObject_Call "PyObject_Call") | `PyObject *` | tuple | dict/`NULL` | | [`PyObject_CallNoArgs()`](#c.PyObject_CallNoArgs "PyObject_CallNoArgs") | `PyObject *` | — | — | | [`PyObject_CallOneArg()`](#c.PyObject_CallOneArg "PyObject_CallOneArg") | `PyObject *` | 1 object | — | | [`PyObject_CallObject()`](#c.PyObject_CallObject "PyObject_CallObject") | `PyObject *` | tuple/`NULL` | — | | [`PyObject_CallFunction()`](#c.PyObject_CallFunction "PyObject_CallFunction") | `PyObject *` | format | — | | [`PyObject_CallMethod()`](#c.PyObject_CallMethod "PyObject_CallMethod") | obj + `char*` | format | — | | [`PyObject_CallFunctionObjArgs()`](#c.PyObject_CallFunctionObjArgs "PyObject_CallFunctionObjArgs") | `PyObject *` | variadic | — | | [`PyObject_CallMethodObjArgs()`](#c.PyObject_CallMethodObjArgs "PyObject_CallMethodObjArgs") | obj + name | variadic | — | | [`PyObject_CallMethodNoArgs()`](#c.PyObject_CallMethodNoArgs "PyObject_CallMethodNoArgs") | obj + name | — | — | | [`PyObject_CallMethodOneArg()`](#c.PyObject_CallMethodOneArg "PyObject_CallMethodOneArg") | obj + name | 1 object | — | | [`PyObject_Vectorcall()`](#c.PyObject_Vectorcall "PyObject_Vectorcall") | `PyObject *` | vectorcall | vectorcall | | [`PyObject_VectorcallDict()`](#c.PyObject_VectorcallDict "PyObject_VectorcallDict") | `PyObject *` | vectorcall | dict/`NULL` | | [`PyObject_VectorcallMethod()`](#c.PyObject_VectorcallMethod "PyObject_VectorcallMethod") | arg + name | vectorcall | vectorcall | `PyObject* PyObject_Call(PyObject *callable, PyObject *args, PyObject *kwargs)` *Return value: New reference.*Call a callable Python object *callable*, with arguments given by the tuple *args*, and named arguments given by the dictionary *kwargs*. *args* must not be *NULL*; use an empty tuple if no arguments are needed. If no named arguments are needed, *kwargs* can be *NULL*. Return the result of the call on success, or raise an exception and return *NULL* on failure. This is the equivalent of the Python expression: `callable(*args, **kwargs)`. `PyObject* PyObject_CallNoArgs(PyObject *callable)` Call a callable Python object *callable* without any arguments. It is the most efficient way to call a callable Python object without any argument. Return the result of the call on success, or raise an exception and return *NULL* on failure. New in version 3.9. `PyObject* PyObject_CallOneArg(PyObject *callable, PyObject *arg)` Call a callable Python object *callable* with exactly 1 positional argument *arg* and no keyword arguments. Return the result of the call on success, or raise an exception and return *NULL* on failure. This function is not part of the [limited API](stable#stable). New in version 3.9. `PyObject* PyObject_CallObject(PyObject *callable, PyObject *args)` *Return value: New reference.*Call a callable Python object *callable*, with arguments given by the tuple *args*. If no arguments are needed, then *args* can be *NULL*. Return the result of the call on success, or raise an exception and return *NULL* on failure. This is the equivalent of the Python expression: `callable(*args)`. `PyObject* PyObject_CallFunction(PyObject *callable, const char *format, ...)` *Return value: New reference.*Call a callable Python object *callable*, with a variable number of C arguments. The C arguments are described using a [`Py_BuildValue()`](arg#c.Py_BuildValue "Py_BuildValue") style format string. The format can be *NULL*, indicating that no arguments are provided. Return the result of the call on success, or raise an exception and return *NULL* on failure. This is the equivalent of the Python expression: `callable(*args)`. Note that if you only pass [`PyObject *`](structures#c.PyObject "PyObject") args, [`PyObject_CallFunctionObjArgs()`](#c.PyObject_CallFunctionObjArgs "PyObject_CallFunctionObjArgs") is a faster alternative. Changed in version 3.4: The type of *format* was changed from `char *`. `PyObject* PyObject_CallMethod(PyObject *obj, const char *name, const char *format, ...)` *Return value: New reference.*Call the method named *name* of object *obj* with a variable number of C arguments. The C arguments are described by a [`Py_BuildValue()`](arg#c.Py_BuildValue "Py_BuildValue") format string that should produce a tuple. The format can be *NULL*, indicating that no arguments are provided. Return the result of the call on success, or raise an exception and return *NULL* on failure. This is the equivalent of the Python expression: `obj.name(arg1, arg2, ...)`. Note that if you only pass [`PyObject *`](structures#c.PyObject "PyObject") args, [`PyObject_CallMethodObjArgs()`](#c.PyObject_CallMethodObjArgs "PyObject_CallMethodObjArgs") is a faster alternative. Changed in version 3.4: The types of *name* and *format* were changed from `char *`. `PyObject* PyObject_CallFunctionObjArgs(PyObject *callable, ...)` *Return value: New reference.*Call a callable Python object *callable*, with a variable number of [`PyObject *`](structures#c.PyObject "PyObject") arguments. The arguments are provided as a variable number of parameters followed by *NULL*. Return the result of the call on success, or raise an exception and return *NULL* on failure. This is the equivalent of the Python expression: `callable(arg1, arg2, ...)`. `PyObject* PyObject_CallMethodObjArgs(PyObject *obj, PyObject *name, ...)` *Return value: New reference.*Call a method of the Python object *obj*, where the name of the method is given as a Python string object in *name*. It is called with a variable number of [`PyObject *`](structures#c.PyObject "PyObject") arguments. The arguments are provided as a variable number of parameters followed by *NULL*. Return the result of the call on success, or raise an exception and return *NULL* on failure. `PyObject* PyObject_CallMethodNoArgs(PyObject *obj, PyObject *name)` Call a method of the Python object *obj* without arguments, where the name of the method is given as a Python string object in *name*. Return the result of the call on success, or raise an exception and return *NULL* on failure. This function is not part of the [limited API](stable#stable). New in version 3.9. `PyObject* PyObject_CallMethodOneArg(PyObject *obj, PyObject *name, PyObject *arg)` Call a method of the Python object *obj* with a single positional argument *arg*, where the name of the method is given as a Python string object in *name*. Return the result of the call on success, or raise an exception and return *NULL* on failure. This function is not part of the [limited API](stable#stable). New in version 3.9. `PyObject* PyObject_Vectorcall(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject *kwnames)` Call a callable Python object *callable*. The arguments are the same as for [`vectorcallfunc`](#c.vectorcallfunc "vectorcallfunc"). If *callable* supports [vectorcall](#vectorcall), this directly calls the vectorcall function stored in *callable*. Return the result of the call on success, or raise an exception and return *NULL* on failure. This function is not part of the [limited API](stable#stable). New in version 3.9. `PyObject* PyObject_VectorcallDict(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject *kwdict)` Call *callable* with positional arguments passed exactly as in the [vectorcall](#vectorcall) protocol, but with keyword arguments passed as a dictionary *kwdict*. The *args* array contains only the positional arguments. Regardless of which protocol is used internally, a conversion of arguments needs to be done. Therefore, this function should only be used if the caller already has a dictionary ready to use for the keyword arguments, but not a tuple for the positional arguments. This function is not part of the [limited API](stable#stable). New in version 3.9. `PyObject* PyObject_VectorcallMethod(PyObject *name, PyObject *const *args, size_t nargsf, PyObject *kwnames)` Call a method using the vectorcall calling convention. The name of the method is given as a Python string *name*. The object whose method is called is *args[0]*, and the *args* array starting at *args[1]* represents the arguments of the call. There must be at least one positional argument. *nargsf* is the number of positional arguments including *args[0]*, plus `PY_VECTORCALL_ARGUMENTS_OFFSET` if the value of `args[0]` may temporarily be changed. Keyword arguments can be passed just like in [`PyObject_Vectorcall()`](#c.PyObject_Vectorcall "PyObject_Vectorcall"). If the object has the [`Py_TPFLAGS_METHOD_DESCRIPTOR`](typeobj#Py_TPFLAGS_METHOD_DESCRIPTOR "Py_TPFLAGS_METHOD_DESCRIPTOR") feature, this will call the unbound method object with the full *args* vector as arguments. Return the result of the call on success, or raise an exception and return *NULL* on failure. This function is not part of the [limited API](stable#stable). New in version 3.9. Call Support API ---------------- `int PyCallable_Check(PyObject *o)` Determine if the object *o* is callable. Return `1` if the object is callable and `0` otherwise. This function always succeeds.
programming_docs
python Object Implementation Support Object Implementation Support ============================= This chapter describes the functions, types, and macros used when defining new object types. * [Allocating Objects on the Heap](allocation) * [Common Object Structures](structures) + [Base object types and macros](structures#base-object-types-and-macros) + [Implementing functions and methods](structures#implementing-functions-and-methods) + [Accessing attributes of extension types](structures#accessing-attributes-of-extension-types) * [Type Objects](typeobj) + [Quick Reference](typeobj#quick-reference) - [“tp slots”](typeobj#tp-slots) - [sub-slots](typeobj#sub-slots) - [slot typedefs](typeobj#slot-typedefs) + [PyTypeObject Definition](typeobj#pytypeobject-definition) + [PyObject Slots](typeobj#pyobject-slots) + [PyVarObject Slots](typeobj#pyvarobject-slots) + [PyTypeObject Slots](typeobj#pytypeobject-slots) + [Heap Types](typeobj#heap-types) * [Number Object Structures](typeobj#number-object-structures) * [Mapping Object Structures](typeobj#mapping-object-structures) * [Sequence Object Structures](typeobj#sequence-object-structures) * [Buffer Object Structures](typeobj#buffer-object-structures) * [Async Object Structures](typeobj#async-object-structures) * [Slot Type typedefs](typeobj#slot-type-typedefs) * [Examples](typeobj#examples) * [Supporting Cyclic Garbage Collection](gcsupport) python Concrete Objects Layer Concrete Objects Layer ====================== The functions in this chapter are specific to certain Python object types. Passing them an object of the wrong type is not a good idea; if you receive an object from a Python program and you are not sure that it has the right type, you must perform a type check first; for example, to check that an object is a dictionary, use [`PyDict_Check()`](dict#c.PyDict_Check "PyDict_Check"). The chapter is structured like the “family tree” of Python object types. Warning While the functions described in this chapter carefully check the type of the objects which are passed in, many of them do not check for `NULL` being passed instead of a valid object. Allowing `NULL` to be passed in can cause memory access violations and immediate termination of the interpreter. Fundamental Objects ------------------- This section describes Python type objects and the singleton object `None`. * [Type Objects](type) + [Creating Heap-Allocated Types](type#creating-heap-allocated-types) * [The `None` Object](none) Numeric Objects --------------- * [Integer Objects](long) * [Boolean Objects](bool) * [Floating Point Objects](float) * [Complex Number Objects](complex) + [Complex Numbers as C Structures](complex#complex-numbers-as-c-structures) + [Complex Numbers as Python Objects](complex#complex-numbers-as-python-objects) Sequence Objects ---------------- Generic operations on sequence objects were discussed in the previous chapter; this section deals with the specific kinds of sequence objects that are intrinsic to the Python language. * [Bytes Objects](bytes) * [Byte Array Objects](bytearray) + [Type check macros](bytearray#type-check-macros) + [Direct API functions](bytearray#direct-api-functions) + [Macros](bytearray#macros) * [Unicode Objects and Codecs](unicode) + [Unicode Objects](unicode#unicode-objects) - [Unicode Type](unicode#unicode-type) - [Unicode Character Properties](unicode#unicode-character-properties) - [Creating and accessing Unicode strings](unicode#creating-and-accessing-unicode-strings) - [Deprecated Py\_UNICODE APIs](unicode#deprecated-py-unicode-apis) - [Locale Encoding](unicode#locale-encoding) - [File System Encoding](unicode#file-system-encoding) - [wchar\_t Support](unicode#wchar-t-support) + [Built-in Codecs](unicode#built-in-codecs) - [Generic Codecs](unicode#generic-codecs) - [UTF-8 Codecs](unicode#utf-8-codecs) - [UTF-32 Codecs](unicode#utf-32-codecs) - [UTF-16 Codecs](unicode#utf-16-codecs) - [UTF-7 Codecs](unicode#utf-7-codecs) - [Unicode-Escape Codecs](unicode#unicode-escape-codecs) - [Raw-Unicode-Escape Codecs](unicode#raw-unicode-escape-codecs) - [Latin-1 Codecs](unicode#latin-1-codecs) - [ASCII Codecs](unicode#ascii-codecs) - [Character Map Codecs](unicode#character-map-codecs) - [MBCS codecs for Windows](unicode#mbcs-codecs-for-windows) - [Methods & Slots](unicode#methods-slots) + [Methods and Slot Functions](unicode#methods-and-slot-functions) * [Tuple Objects](tuple) * [Struct Sequence Objects](tuple#struct-sequence-objects) * [List Objects](list) Container Objects ----------------- * [Dictionary Objects](dict) * [Set Objects](set) Function Objects ---------------- * [Function Objects](function) * [Instance Method Objects](method) * [Method Objects](method#method-objects) * [Cell Objects](cell) * [Code Objects](code) Other Objects ------------- * [File Objects](file) * [Module Objects](module) + [Initializing C modules](module#initializing-c-modules) - [Single-phase initialization](module#single-phase-initialization) - [Multi-phase initialization](module#multi-phase-initialization) - [Low-level module creation functions](module#low-level-module-creation-functions) - [Support functions](module#support-functions) + [Module lookup](module#module-lookup) * [Iterator Objects](iterator) * [Descriptor Objects](descriptor) * [Slice Objects](slice) * [Ellipsis Object](slice#ellipsis-object) * [MemoryView objects](memoryview) * [Weak Reference Objects](weakref) * [Capsules](capsule) * [Generator Objects](gen) * [Coroutine Objects](coro) * [Context Variables Objects](contextvars) * [DateTime Objects](datetime) * [Objects for Type Hinting](typehints) python Slice Objects Slice Objects ============= `PyTypeObject PySlice_Type` The type object for slice objects. This is the same as [`slice`](../library/functions#slice "slice") in the Python layer. `int PySlice_Check(PyObject *ob)` Return true if *ob* is a slice object; *ob* must not be `NULL`. This function always succeeds. `PyObject* PySlice_New(PyObject *start, PyObject *stop, PyObject *step)` *Return value: New reference.*Return a new slice object with the given values. The *start*, *stop*, and *step* parameters are used as the values of the slice object attributes of the same names. Any of the values may be `NULL`, in which case the `None` will be used for the corresponding attribute. Return `NULL` if the new object could not be allocated. `int PySlice_GetIndices(PyObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)` Retrieve the start, stop and step indices from the slice object *slice*, assuming a sequence of length *length*. Treats indices greater than *length* as errors. Returns `0` on success and `-1` on error with no exception set (unless one of the indices was not [`None`](../library/constants#None "None") and failed to be converted to an integer, in which case `-1` is returned with an exception set). You probably do not want to use this function. Changed in version 3.2: The parameter type for the *slice* parameter was `PySliceObject*` before. `int PySlice_GetIndicesEx(PyObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength)` Usable replacement for [`PySlice_GetIndices()`](#c.PySlice_GetIndices "PySlice_GetIndices"). Retrieve the start, stop, and step indices from the slice object *slice* assuming a sequence of length *length*, and store the length of the slice in *slicelength*. Out of bounds indices are clipped in a manner consistent with the handling of normal slices. Returns `0` on success and `-1` on error with exception set. Note This function is considered not safe for resizable sequences. Its invocation should be replaced by a combination of [`PySlice_Unpack()`](#c.PySlice_Unpack "PySlice_Unpack") and [`PySlice_AdjustIndices()`](#c.PySlice_AdjustIndices "PySlice_AdjustIndices") where ``` if (PySlice_GetIndicesEx(slice, length, &start, &stop, &step, &slicelength) < 0) { // return error } ``` is replaced by ``` if (PySlice_Unpack(slice, &start, &stop, &step) < 0) { // return error } slicelength = PySlice_AdjustIndices(length, &start, &stop, step); ``` Changed in version 3.2: The parameter type for the *slice* parameter was `PySliceObject*` before. Changed in version 3.6.1: If `Py_LIMITED_API` is not set or set to the value between `0x03050400` and `0x03060000` (not including) or `0x03060100` or higher `PySlice_GetIndicesEx()` is implemented as a macro using `PySlice_Unpack()` and `PySlice_AdjustIndices()`. Arguments *start*, *stop* and *step* are evaluated more than once. Deprecated since version 3.6.1: If `Py_LIMITED_API` is set to the value less than `0x03050400` or between `0x03060000` and `0x03060100` (not including) `PySlice_GetIndicesEx()` is a deprecated function. `int PySlice_Unpack(PyObject *slice, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)` Extract the start, stop and step data members from a slice object as C integers. Silently reduce values larger than `PY_SSIZE_T_MAX` to `PY_SSIZE_T_MAX`, silently boost the start and stop values less than `PY_SSIZE_T_MIN` to `PY_SSIZE_T_MIN`, and silently boost the step values less than `-PY_SSIZE_T_MAX` to `-PY_SSIZE_T_MAX`. Return `-1` on error, `0` on success. New in version 3.6.1. `Py_ssize_t PySlice_AdjustIndices(Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t step)` Adjust start/end slice indices assuming a sequence of the specified length. Out of bounds indices are clipped in a manner consistent with the handling of normal slices. Return the length of the slice. Always successful. Doesn’t call Python code. New in version 3.6.1. python Type Objects Type Objects ============ Perhaps one of the most important structures of the Python object system is the structure that defines a new type: the [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject") structure. Type objects can be handled using any of the `PyObject_*()` or `PyType_*()` functions, but do not offer much that’s interesting to most Python applications. These objects are fundamental to how objects behave, so they are very important to the interpreter itself and to any extension module that implements new types. Type objects are fairly large compared to most of the standard types. The reason for the size is that each type object stores a large number of values, mostly C function pointers, each of which implements a small part of the type’s functionality. The fields of the type object are examined in detail in this section. The fields will be described in the order in which they occur in the structure. In addition to the following quick reference, the [Examples](#typedef-examples) section provides at-a-glance insight into the meaning and use of [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject"). Quick Reference --------------- ### “tp slots” | PyTypeObject Slot [1](#slots) | [Type](#slot-typedefs-table) | special methods/attrs | Info [2](#cols) | | --- | --- | --- | --- | | O | T | D | I | | <R> [`tp_name`](#c.PyTypeObject.tp_name "PyTypeObject.tp_name") | const char \* | \_\_name\_\_ | X | X | | | | [`tp_basicsize`](#c.PyTypeObject.tp_basicsize "PyTypeObject.tp_basicsize") | [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t") | | X | X | | X | | [`tp_itemsize`](#c.PyTypeObject.tp_itemsize "PyTypeObject.tp_itemsize") | [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t") | | | X | | X | | [`tp_dealloc`](#c.PyTypeObject.tp_dealloc "PyTypeObject.tp_dealloc") | [`destructor`](#c.destructor "destructor") | | X | X | | X | | [`tp_vectorcall_offset`](#c.PyTypeObject.tp_vectorcall_offset "PyTypeObject.tp_vectorcall_offset") | [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t") | | | X | | X | | ([`tp_getattr`](#c.PyTypeObject.tp_getattr "PyTypeObject.tp_getattr")) | [`getattrfunc`](#c.getattrfunc "getattrfunc") | \_\_getattribute\_\_, \_\_getattr\_\_ | | | | G | | ([`tp_setattr`](#c.PyTypeObject.tp_setattr "PyTypeObject.tp_setattr")) | [`setattrfunc`](#c.setattrfunc "setattrfunc") | \_\_setattr\_\_, \_\_delattr\_\_ | | | | G | | [`tp_as_async`](#c.PyTypeObject.tp_as_async "PyTypeObject.tp_as_async") | [`PyAsyncMethods`](#c.PyAsyncMethods "PyAsyncMethods") \* | [sub-slots](#sub-slots) | | | | % | | [`tp_repr`](#c.PyTypeObject.tp_repr "PyTypeObject.tp_repr") | [`reprfunc`](#c.reprfunc "reprfunc") | \_\_repr\_\_ | X | X | | X | | [`tp_as_number`](#c.PyTypeObject.tp_as_number "PyTypeObject.tp_as_number") | [`PyNumberMethods`](#c.PyNumberMethods "PyNumberMethods") \* | [sub-slots](#sub-slots) | | | | % | | [`tp_as_sequence`](#c.PyTypeObject.tp_as_sequence "PyTypeObject.tp_as_sequence") | [`PySequenceMethods`](#c.PySequenceMethods "PySequenceMethods") \* | [sub-slots](#sub-slots) | | | | % | | [`tp_as_mapping`](#c.PyTypeObject.tp_as_mapping "PyTypeObject.tp_as_mapping") | [`PyMappingMethods`](#c.PyMappingMethods "PyMappingMethods") \* | [sub-slots](#sub-slots) | | | | % | | [`tp_hash`](#c.PyTypeObject.tp_hash "PyTypeObject.tp_hash") | [`hashfunc`](#c.hashfunc "hashfunc") | \_\_hash\_\_ | X | | | G | | [`tp_call`](#c.PyTypeObject.tp_call "PyTypeObject.tp_call") | [`ternaryfunc`](#c.ternaryfunc "ternaryfunc") | \_\_call\_\_ | | X | | X | | [`tp_str`](#c.PyTypeObject.tp_str "PyTypeObject.tp_str") | [`reprfunc`](#c.reprfunc "reprfunc") | \_\_str\_\_ | X | | | X | | [`tp_getattro`](#c.PyTypeObject.tp_getattro "PyTypeObject.tp_getattro") | [`getattrofunc`](#c.getattrofunc "getattrofunc") | \_\_getattribute\_\_, \_\_getattr\_\_ | X | X | | G | | [`tp_setattro`](#c.PyTypeObject.tp_setattro "PyTypeObject.tp_setattro") | [`setattrofunc`](#c.setattrofunc "setattrofunc") | \_\_setattr\_\_, \_\_delattr\_\_ | X | X | | G | | [`tp_as_buffer`](#c.PyTypeObject.tp_as_buffer "PyTypeObject.tp_as_buffer") | [`PyBufferProcs`](#c.PyBufferProcs "PyBufferProcs") \* | | | | | % | | [`tp_flags`](#c.PyTypeObject.tp_flags "PyTypeObject.tp_flags") | unsigned long | | X | X | | ? | | [`tp_doc`](#c.PyTypeObject.tp_doc "PyTypeObject.tp_doc") | const char \* | \_\_doc\_\_ | X | X | | | | [`tp_traverse`](#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse") | [`traverseproc`](gcsupport#c.traverseproc "traverseproc") | | | X | | G | | [`tp_clear`](#c.PyTypeObject.tp_clear "PyTypeObject.tp_clear") | [`inquiry`](gcsupport#c.inquiry "inquiry") | | | X | | G | | [`tp_richcompare`](#c.PyTypeObject.tp_richcompare "PyTypeObject.tp_richcompare") | [`richcmpfunc`](#c.richcmpfunc "richcmpfunc") | \_\_lt\_\_, \_\_le\_\_, \_\_eq\_\_, \_\_ne\_\_, \_\_gt\_\_, \_\_ge\_\_ | X | | | G | | [`tp_weaklistoffset`](#c.PyTypeObject.tp_weaklistoffset "PyTypeObject.tp_weaklistoffset") | [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t") | | | X | | ? | | [`tp_iter`](#c.PyTypeObject.tp_iter "PyTypeObject.tp_iter") | [`getiterfunc`](#c.getiterfunc "getiterfunc") | \_\_iter\_\_ | | | | X | | [`tp_iternext`](#c.PyTypeObject.tp_iternext "PyTypeObject.tp_iternext") | [`iternextfunc`](#c.iternextfunc "iternextfunc") | \_\_next\_\_ | | | | X | | [`tp_methods`](#c.PyTypeObject.tp_methods "PyTypeObject.tp_methods") | [`PyMethodDef`](structures#c.PyMethodDef "PyMethodDef") [] | | X | X | | | | [`tp_members`](#c.PyTypeObject.tp_members "PyTypeObject.tp_members") | [`PyMemberDef`](structures#c.PyMemberDef "PyMemberDef") [] | | | X | | | | [`tp_getset`](#c.PyTypeObject.tp_getset "PyTypeObject.tp_getset") | [`PyGetSetDef`](structures#c.PyGetSetDef "PyGetSetDef") [] | | X | X | | | | [`tp_base`](#c.PyTypeObject.tp_base "PyTypeObject.tp_base") | [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject") \* | \_\_base\_\_ | | | X | | | [`tp_dict`](#c.PyTypeObject.tp_dict "PyTypeObject.tp_dict") | [`PyObject`](structures#c.PyObject "PyObject") \* | \_\_dict\_\_ | | | ? | | | [`tp_descr_get`](#c.PyTypeObject.tp_descr_get "PyTypeObject.tp_descr_get") | [`descrgetfunc`](#c.descrgetfunc "descrgetfunc") | \_\_get\_\_ | | | | X | | [`tp_descr_set`](#c.PyTypeObject.tp_descr_set "PyTypeObject.tp_descr_set") | [`descrsetfunc`](#c.descrsetfunc "descrsetfunc") | \_\_set\_\_, \_\_delete\_\_ | | | | X | | [`tp_dictoffset`](#c.PyTypeObject.tp_dictoffset "PyTypeObject.tp_dictoffset") | [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t") | | | X | | ? | | [`tp_init`](#c.PyTypeObject.tp_init "PyTypeObject.tp_init") | [`initproc`](#c.initproc "initproc") | \_\_init\_\_ | X | X | | X | | [`tp_alloc`](#c.PyTypeObject.tp_alloc "PyTypeObject.tp_alloc") | [`allocfunc`](#c.allocfunc "allocfunc") | | X | | ? | ? | | [`tp_new`](#c.PyTypeObject.tp_new "PyTypeObject.tp_new") | [`newfunc`](#c.newfunc "newfunc") | \_\_new\_\_ | X | X | ? | ? | | [`tp_free`](#c.PyTypeObject.tp_free "PyTypeObject.tp_free") | [`freefunc`](#c.freefunc "freefunc") | | X | X | ? | ? | | [`tp_is_gc`](#c.PyTypeObject.tp_is_gc "PyTypeObject.tp_is_gc") | [`inquiry`](gcsupport#c.inquiry "inquiry") | | | X | | X | | <[`tp_bases`](#c.PyTypeObject.tp_bases "PyTypeObject.tp_bases")> | [`PyObject`](structures#c.PyObject "PyObject") \* | \_\_bases\_\_ | | | ~ | | | <[`tp_mro`](#c.PyTypeObject.tp_mro "PyTypeObject.tp_mro")> | [`PyObject`](structures#c.PyObject "PyObject") \* | \_\_mro\_\_ | | | ~ | | | [[`tp_cache`](#c.PyTypeObject.tp_cache "PyTypeObject.tp_cache")] | [`PyObject`](structures#c.PyObject "PyObject") \* | | | | | | [[`tp_subclasses`](#c.PyTypeObject.tp_subclasses "PyTypeObject.tp_subclasses")] | [`PyObject`](structures#c.PyObject "PyObject") \* | \_\_subclasses\_\_ | | | | | [[`tp_weaklist`](#c.PyTypeObject.tp_weaklist "PyTypeObject.tp_weaklist")] | [`PyObject`](structures#c.PyObject "PyObject") \* | | | | | | ([`tp_del`](#c.PyTypeObject.tp_del "PyTypeObject.tp_del")) | [`destructor`](#c.destructor "destructor") | | | | | | | [[`tp_version_tag`](#c.PyTypeObject.tp_version_tag "PyTypeObject.tp_version_tag")] | unsigned int | | | | | | [`tp_finalize`](#c.PyTypeObject.tp_finalize "PyTypeObject.tp_finalize") | [`destructor`](#c.destructor "destructor") | \_\_del\_\_ | | | | X | | [`tp_vectorcall`](#c.PyTypeObject.tp_vectorcall "PyTypeObject.tp_vectorcall") | [`vectorcallfunc`](call#c.vectorcallfunc "vectorcallfunc") | | | | | | `1` A slot name in parentheses indicates it is (effectively) deprecated. Names in angle brackets should be treated as read-only. Names in square brackets are for internal use only. “<R>” (as a prefix) means the field is required (must be non-`NULL`). `2` Columns: **“O”**: set on `PyBaseObject_Type` **“T”**: set on [`PyType_Type`](type#c.PyType_Type "PyType_Type") **“D”**: default (if slot is set to `NULL`) ``` X - PyType_Ready sets this value if it is NULL ~ - PyType_Ready always sets this value (it should be NULL) ? - PyType_Ready may set this value depending on other slots Also see the inheritance column ("I"). ``` **“I”**: inheritance ``` X - type slot is inherited via *PyType_Ready* if defined with a *NULL* value % - the slots of the sub-struct are inherited individually G - inherited, but only in combination with other slots; see the slot's description ? - it's complicated; see the slot's description ``` Note that some slots are effectively inherited through the normal attribute lookup chain. ### sub-slots | Slot | [Type](#slot-typedefs-table) | special methods | | --- | --- | --- | | [`am_await`](#c.PyAsyncMethods.am_await "PyAsyncMethods.am_await") | [`unaryfunc`](#c.unaryfunc "unaryfunc") | \_\_await\_\_ | | [`am_aiter`](#c.PyAsyncMethods.am_aiter "PyAsyncMethods.am_aiter") | [`unaryfunc`](#c.unaryfunc "unaryfunc") | \_\_aiter\_\_ | | [`am_anext`](#c.PyAsyncMethods.am_anext "PyAsyncMethods.am_anext") | [`unaryfunc`](#c.unaryfunc "unaryfunc") | \_\_anext\_\_ | | | | [`nb_add`](#c.PyNumberMethods.nb_add "PyNumberMethods.nb_add") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_add\_\_ \_\_radd\_\_ | | [`nb_inplace_add`](#c.PyNumberMethods.nb_inplace_add "PyNumberMethods.nb_inplace_add") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_iadd\_\_ | | [`nb_subtract`](#c.PyNumberMethods.nb_subtract "PyNumberMethods.nb_subtract") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_sub\_\_ \_\_rsub\_\_ | | [`nb_inplace_subtract`](#c.PyNumberMethods.nb_inplace_subtract "PyNumberMethods.nb_inplace_subtract") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_isub\_\_ | | [`nb_multiply`](#c.PyNumberMethods.nb_multiply "PyNumberMethods.nb_multiply") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_mul\_\_ \_\_rmul\_\_ | | [`nb_inplace_multiply`](#c.PyNumberMethods.nb_inplace_multiply "PyNumberMethods.nb_inplace_multiply") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_imul\_\_ | | [`nb_remainder`](#c.PyNumberMethods.nb_remainder "PyNumberMethods.nb_remainder") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_mod\_\_ \_\_rmod\_\_ | | [`nb_inplace_remainder`](#c.PyNumberMethods.nb_inplace_remainder "PyNumberMethods.nb_inplace_remainder") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_imod\_\_ | | [`nb_divmod`](#c.PyNumberMethods.nb_divmod "PyNumberMethods.nb_divmod") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_divmod\_\_ \_\_rdivmod\_\_ | | [`nb_power`](#c.PyNumberMethods.nb_power "PyNumberMethods.nb_power") | [`ternaryfunc`](#c.ternaryfunc "ternaryfunc") | \_\_pow\_\_ \_\_rpow\_\_ | | [`nb_inplace_power`](#c.PyNumberMethods.nb_inplace_power "PyNumberMethods.nb_inplace_power") | [`ternaryfunc`](#c.ternaryfunc "ternaryfunc") | \_\_ipow\_\_ | | [`nb_negative`](#c.PyNumberMethods.nb_negative "PyNumberMethods.nb_negative") | [`unaryfunc`](#c.unaryfunc "unaryfunc") | \_\_neg\_\_ | | [`nb_positive`](#c.PyNumberMethods.nb_positive "PyNumberMethods.nb_positive") | [`unaryfunc`](#c.unaryfunc "unaryfunc") | \_\_pos\_\_ | | [`nb_absolute`](#c.PyNumberMethods.nb_absolute "PyNumberMethods.nb_absolute") | [`unaryfunc`](#c.unaryfunc "unaryfunc") | \_\_abs\_\_ | | [`nb_bool`](#c.PyNumberMethods.nb_bool "PyNumberMethods.nb_bool") | [`inquiry`](gcsupport#c.inquiry "inquiry") | \_\_bool\_\_ | | [`nb_invert`](#c.PyNumberMethods.nb_invert "PyNumberMethods.nb_invert") | [`unaryfunc`](#c.unaryfunc "unaryfunc") | \_\_invert\_\_ | | [`nb_lshift`](#c.PyNumberMethods.nb_lshift "PyNumberMethods.nb_lshift") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_lshift\_\_ \_\_rlshift\_\_ | | [`nb_inplace_lshift`](#c.PyNumberMethods.nb_inplace_lshift "PyNumberMethods.nb_inplace_lshift") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_ilshift\_\_ | | [`nb_rshift`](#c.PyNumberMethods.nb_rshift "PyNumberMethods.nb_rshift") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_rshift\_\_ \_\_rrshift\_\_ | | [`nb_inplace_rshift`](#c.PyNumberMethods.nb_inplace_rshift "PyNumberMethods.nb_inplace_rshift") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_irshift\_\_ | | [`nb_and`](#c.PyNumberMethods.nb_and "PyNumberMethods.nb_and") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_and\_\_ \_\_rand\_\_ | | [`nb_inplace_and`](#c.PyNumberMethods.nb_inplace_and "PyNumberMethods.nb_inplace_and") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_iand\_\_ | | [`nb_xor`](#c.PyNumberMethods.nb_xor "PyNumberMethods.nb_xor") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_xor\_\_ \_\_rxor\_\_ | | [`nb_inplace_xor`](#c.PyNumberMethods.nb_inplace_xor "PyNumberMethods.nb_inplace_xor") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_ixor\_\_ | | [`nb_or`](#c.PyNumberMethods.nb_or "PyNumberMethods.nb_or") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_or\_\_ \_\_ror\_\_ | | [`nb_inplace_or`](#c.PyNumberMethods.nb_inplace_or "PyNumberMethods.nb_inplace_or") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_ior\_\_ | | [`nb_int`](#c.PyNumberMethods.nb_int "PyNumberMethods.nb_int") | [`unaryfunc`](#c.unaryfunc "unaryfunc") | \_\_int\_\_ | | [`nb_reserved`](#c.PyNumberMethods.nb_reserved "PyNumberMethods.nb_reserved") | void \* | | | [`nb_float`](#c.PyNumberMethods.nb_float "PyNumberMethods.nb_float") | [`unaryfunc`](#c.unaryfunc "unaryfunc") | \_\_float\_\_ | | [`nb_floor_divide`](#c.PyNumberMethods.nb_floor_divide "PyNumberMethods.nb_floor_divide") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_floordiv\_\_ | | [`nb_inplace_floor_divide`](#c.PyNumberMethods.nb_inplace_floor_divide "PyNumberMethods.nb_inplace_floor_divide") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_ifloordiv\_\_ | | [`nb_true_divide`](#c.PyNumberMethods.nb_true_divide "PyNumberMethods.nb_true_divide") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_truediv\_\_ | | [`nb_inplace_true_divide`](#c.PyNumberMethods.nb_inplace_true_divide "PyNumberMethods.nb_inplace_true_divide") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_itruediv\_\_ | | [`nb_index`](#c.PyNumberMethods.nb_index "PyNumberMethods.nb_index") | [`unaryfunc`](#c.unaryfunc "unaryfunc") | \_\_index\_\_ | | [`nb_matrix_multiply`](#c.PyNumberMethods.nb_matrix_multiply "PyNumberMethods.nb_matrix_multiply") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_matmul\_\_ \_\_rmatmul\_\_ | | [`nb_inplace_matrix_multiply`](#c.PyNumberMethods.nb_inplace_matrix_multiply "PyNumberMethods.nb_inplace_matrix_multiply") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_imatmul\_\_ | | | | [`mp_length`](#c.PyMappingMethods.mp_length "PyMappingMethods.mp_length") | [`lenfunc`](#c.lenfunc "lenfunc") | \_\_len\_\_ | | [`mp_subscript`](#c.PyMappingMethods.mp_subscript "PyMappingMethods.mp_subscript") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_getitem\_\_ | | [`mp_ass_subscript`](#c.PyMappingMethods.mp_ass_subscript "PyMappingMethods.mp_ass_subscript") | [`objobjargproc`](#c.objobjargproc "objobjargproc") | \_\_setitem\_\_, \_\_delitem\_\_ | | | | [`sq_length`](#c.PySequenceMethods.sq_length "PySequenceMethods.sq_length") | [`lenfunc`](#c.lenfunc "lenfunc") | \_\_len\_\_ | | [`sq_concat`](#c.PySequenceMethods.sq_concat "PySequenceMethods.sq_concat") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_add\_\_ | | [`sq_repeat`](#c.PySequenceMethods.sq_repeat "PySequenceMethods.sq_repeat") | [`ssizeargfunc`](#c.ssizeargfunc "ssizeargfunc") | \_\_mul\_\_ | | [`sq_item`](#c.PySequenceMethods.sq_item "PySequenceMethods.sq_item") | [`ssizeargfunc`](#c.ssizeargfunc "ssizeargfunc") | \_\_getitem\_\_ | | [`sq_ass_item`](#c.PySequenceMethods.sq_ass_item "PySequenceMethods.sq_ass_item") | [`ssizeobjargproc`](#c.ssizeobjargproc "ssizeobjargproc") | \_\_setitem\_\_ \_\_delitem\_\_ | | [`sq_contains`](#c.PySequenceMethods.sq_contains "PySequenceMethods.sq_contains") | [`objobjproc`](#c.objobjproc "objobjproc") | \_\_contains\_\_ | | [`sq_inplace_concat`](#c.PySequenceMethods.sq_inplace_concat "PySequenceMethods.sq_inplace_concat") | [`binaryfunc`](#c.binaryfunc "binaryfunc") | \_\_iadd\_\_ | | [`sq_inplace_repeat`](#c.PySequenceMethods.sq_inplace_repeat "PySequenceMethods.sq_inplace_repeat") | [`ssizeargfunc`](#c.ssizeargfunc "ssizeargfunc") | \_\_imul\_\_ | | | | [`bf_getbuffer`](#c.PyBufferProcs.bf_getbuffer "PyBufferProcs.bf_getbuffer") | [`getbufferproc()`](#c.getbufferproc "getbufferproc") | | | [`bf_releasebuffer`](#c.PyBufferProcs.bf_releasebuffer "PyBufferProcs.bf_releasebuffer") | [`releasebufferproc()`](#c.releasebufferproc "releasebufferproc") | | ### slot typedefs | typedef | Parameter Types | Return Type | | --- | --- | --- | | [`allocfunc`](#c.allocfunc "allocfunc") | | [`PyObject`](structures#c.PyObject "PyObject") \* | | [`destructor`](#c.destructor "destructor") | void \* | void | | [`freefunc`](#c.freefunc "freefunc") | void \* | void | | [`traverseproc`](gcsupport#c.traverseproc "traverseproc") | | int | | [`newfunc`](#c.newfunc "newfunc") | | [`PyObject`](structures#c.PyObject "PyObject") \* | | [`initproc`](#c.initproc "initproc") | | int | | [`reprfunc`](#c.reprfunc "reprfunc") | [`PyObject`](structures#c.PyObject "PyObject") \* | [`PyObject`](structures#c.PyObject "PyObject") \* | | [`getattrfunc`](#c.getattrfunc "getattrfunc") | | [`PyObject`](structures#c.PyObject "PyObject") \* | | [`setattrfunc`](#c.setattrfunc "setattrfunc") | | int | | [`getattrofunc`](#c.getattrofunc "getattrofunc") | | [`PyObject`](structures#c.PyObject "PyObject") \* | | [`setattrofunc`](#c.setattrofunc "setattrofunc") | | int | | [`descrgetfunc`](#c.descrgetfunc "descrgetfunc") | | [`PyObject`](structures#c.PyObject "PyObject") \* | | [`descrsetfunc`](#c.descrsetfunc "descrsetfunc") | | int | | [`hashfunc`](#c.hashfunc "hashfunc") | [`PyObject`](structures#c.PyObject "PyObject") \* | Py\_hash\_t | | [`richcmpfunc`](#c.richcmpfunc "richcmpfunc") | | [`PyObject`](structures#c.PyObject "PyObject") \* | | [`getiterfunc`](#c.getiterfunc "getiterfunc") | [`PyObject`](structures#c.PyObject "PyObject") \* | [`PyObject`](structures#c.PyObject "PyObject") \* | | [`iternextfunc`](#c.iternextfunc "iternextfunc") | [`PyObject`](structures#c.PyObject "PyObject") \* | [`PyObject`](structures#c.PyObject "PyObject") \* | | [`lenfunc`](#c.lenfunc "lenfunc") | [`PyObject`](structures#c.PyObject "PyObject") \* | [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t") | | [`getbufferproc`](#c.getbufferproc "getbufferproc") | | int | | [`releasebufferproc`](#c.releasebufferproc "releasebufferproc") | | void | | [`inquiry`](gcsupport#c.inquiry "inquiry") | void \* | int | | [`unaryfunc`](#c.unaryfunc "unaryfunc") | | [`PyObject`](structures#c.PyObject "PyObject") \* | | [`binaryfunc`](#c.binaryfunc "binaryfunc") | | [`PyObject`](structures#c.PyObject "PyObject") \* | | [`ternaryfunc`](#c.ternaryfunc "ternaryfunc") | | [`PyObject`](structures#c.PyObject "PyObject") \* | | [`ssizeargfunc`](#c.ssizeargfunc "ssizeargfunc") | | [`PyObject`](structures#c.PyObject "PyObject") \* | | [`ssizeobjargproc`](#c.ssizeobjargproc "ssizeobjargproc") | | int | | [`objobjproc`](#c.objobjproc "objobjproc") | | int | | [`objobjargproc`](#c.objobjargproc "objobjargproc") | | int | See [Slot Type typedefs](#id5) below for more detail. PyTypeObject Definition ----------------------- The structure definition for [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject") can be found in `Include/object.h`. For convenience of reference, this repeats the definition found there: ``` typedef struct _typeobject { PyObject_VAR_HEAD const char *tp_name; /* For printing, in format "<module>.<name>" */ Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */ /* Methods to implement standard operations */ destructor tp_dealloc; Py_ssize_t tp_vectorcall_offset; getattrfunc tp_getattr; setattrfunc tp_setattr; PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2) or tp_reserved (Python 3) */ reprfunc tp_repr; /* Method suites for standard classes */ PyNumberMethods *tp_as_number; PySequenceMethods *tp_as_sequence; PyMappingMethods *tp_as_mapping; /* More standard operations (here for binary compatibility) */ hashfunc tp_hash; ternaryfunc tp_call; reprfunc tp_str; getattrofunc tp_getattro; setattrofunc tp_setattro; /* Functions to access object as input/output buffer */ PyBufferProcs *tp_as_buffer; /* Flags to define presence of optional/expanded features */ unsigned long tp_flags; const char *tp_doc; /* Documentation string */ /* call function for all accessible objects */ traverseproc tp_traverse; /* delete references to contained objects */ inquiry tp_clear; /* rich comparisons */ richcmpfunc tp_richcompare; /* weak reference enabler */ Py_ssize_t tp_weaklistoffset; /* Iterators */ getiterfunc tp_iter; iternextfunc tp_iternext; /* Attribute descriptor and subclassing stuff */ struct PyMethodDef *tp_methods; struct PyMemberDef *tp_members; struct PyGetSetDef *tp_getset; struct _typeobject *tp_base; PyObject *tp_dict; descrgetfunc tp_descr_get; descrsetfunc tp_descr_set; Py_ssize_t tp_dictoffset; initproc tp_init; allocfunc tp_alloc; newfunc tp_new; freefunc tp_free; /* Low-level free-memory routine */ inquiry tp_is_gc; /* For PyObject_IS_GC */ PyObject *tp_bases; PyObject *tp_mro; /* method resolution order */ PyObject *tp_cache; PyObject *tp_subclasses; PyObject *tp_weaklist; destructor tp_del; /* Type attribute cache version tag. Added in version 2.6 */ unsigned int tp_version_tag; destructor tp_finalize; } PyTypeObject; ``` PyObject Slots -------------- The type object structure extends the [`PyVarObject`](structures#c.PyVarObject "PyVarObject") structure. The `ob_size` field is used for dynamic types (created by `type_new()`, usually called from a class statement). Note that [`PyType_Type`](type#c.PyType_Type "PyType_Type") (the metatype) initializes [`tp_itemsize`](#c.PyTypeObject.tp_itemsize "PyTypeObject.tp_itemsize"), which means that its instances (i.e. type objects) *must* have the `ob_size` field. `PyObject* PyObject._ob_next` `PyObject* PyObject._ob_prev` These fields are only present when the macro `Py_TRACE_REFS` is defined. Their initialization to `NULL` is taken care of by the `PyObject_HEAD_INIT` macro. For statically allocated objects, these fields always remain `NULL`. For dynamically allocated objects, these two fields are used to link the object into a doubly-linked list of *all* live objects on the heap. This could be used for various debugging purposes; currently the only use is to print the objects that are still alive at the end of a run when the environment variable [`PYTHONDUMPREFS`](../using/cmdline#envvar-PYTHONDUMPREFS) is set. **Inheritance:** These fields are not inherited by subtypes. `Py_ssize_t PyObject.ob_refcnt` This is the type object’s reference count, initialized to `1` by the `PyObject_HEAD_INIT` macro. Note that for statically allocated type objects, the type’s instances (objects whose `ob_type` points back to the type) do *not* count as references. But for dynamically allocated type objects, the instances *do* count as references. **Inheritance:** This field is not inherited by subtypes. `PyTypeObject* PyObject.ob_type` This is the type’s type, in other words its metatype. It is initialized by the argument to the `PyObject_HEAD_INIT` macro, and its value should normally be `&PyType_Type`. However, for dynamically loadable extension modules that must be usable on Windows (at least), the compiler complains that this is not a valid initializer. Therefore, the convention is to pass `NULL` to the `PyObject_HEAD_INIT` macro and to initialize this field explicitly at the start of the module’s initialization function, before doing anything else. This is typically done like this: ``` Foo_Type.ob_type = &PyType_Type; ``` This should be done before any instances of the type are created. [`PyType_Ready()`](type#c.PyType_Ready "PyType_Ready") checks if `ob_type` is `NULL`, and if so, initializes it to the `ob_type` field of the base class. [`PyType_Ready()`](type#c.PyType_Ready "PyType_Ready") will not change this field if it is non-zero. **Inheritance:** This field is inherited by subtypes. PyVarObject Slots ----------------- `Py_ssize_t PyVarObject.ob_size` For statically allocated type objects, this should be initialized to zero. For dynamically allocated type objects, this field has a special internal meaning. **Inheritance:** This field is not inherited by subtypes. PyTypeObject Slots ------------------ Each slot has a section describing inheritance. If [`PyType_Ready()`](type#c.PyType_Ready "PyType_Ready") may set a value when the field is set to `NULL` then there will also be a “Default” section. (Note that many fields set on `PyBaseObject_Type` and [`PyType_Type`](type#c.PyType_Type "PyType_Type") effectively act as defaults.) `const char* PyTypeObject.tp_name` Pointer to a NUL-terminated string containing the name of the type. For types that are accessible as module globals, the string should be the full module name, followed by a dot, followed by the type name; for built-in types, it should be just the type name. If the module is a submodule of a package, the full package name is part of the full module name. For example, a type named `T` defined in module `M` in subpackage `Q` in package `P` should have the [`tp_name`](#c.PyTypeObject.tp_name "PyTypeObject.tp_name") initializer `"P.Q.M.T"`. For dynamically allocated type objects, this should just be the type name, and the module name explicitly stored in the type dict as the value for key `'__module__'`. For statically allocated type objects, the tp\_name field should contain a dot. Everything before the last dot is made accessible as the `__module__` attribute, and everything after the last dot is made accessible as the [`__name__`](../library/stdtypes#definition.__name__ "definition.__name__") attribute. If no dot is present, the entire [`tp_name`](#c.PyTypeObject.tp_name "PyTypeObject.tp_name") field is made accessible as the [`__name__`](../library/stdtypes#definition.__name__ "definition.__name__") attribute, and the `__module__` attribute is undefined (unless explicitly set in the dictionary, as explained above). This means your type will be impossible to pickle. Additionally, it will not be listed in module documentations created with pydoc. This field must not be `NULL`. It is the only required field in [`PyTypeObject()`](type#c.PyTypeObject "PyTypeObject") (other than potentially [`tp_itemsize`](#c.PyTypeObject.tp_itemsize "PyTypeObject.tp_itemsize")). **Inheritance:** This field is not inherited by subtypes. `Py_ssize_t PyTypeObject.tp_basicsize` `Py_ssize_t PyTypeObject.tp_itemsize` These fields allow calculating the size in bytes of instances of the type. There are two kinds of types: types with fixed-length instances have a zero [`tp_itemsize`](#c.PyTypeObject.tp_itemsize "PyTypeObject.tp_itemsize") field, types with variable-length instances have a non-zero [`tp_itemsize`](#c.PyTypeObject.tp_itemsize "PyTypeObject.tp_itemsize") field. For a type with fixed-length instances, all instances have the same size, given in [`tp_basicsize`](#c.PyTypeObject.tp_basicsize "PyTypeObject.tp_basicsize"). For a type with variable-length instances, the instances must have an `ob_size` field, and the instance size is [`tp_basicsize`](#c.PyTypeObject.tp_basicsize "PyTypeObject.tp_basicsize") plus N times [`tp_itemsize`](#c.PyTypeObject.tp_itemsize "PyTypeObject.tp_itemsize"), where N is the “length” of the object. The value of N is typically stored in the instance’s `ob_size` field. There are exceptions: for example, ints use a negative `ob_size` to indicate a negative number, and N is `abs(ob_size)` there. Also, the presence of an `ob_size` field in the instance layout doesn’t mean that the instance structure is variable-length (for example, the structure for the list type has fixed-length instances, yet those instances have a meaningful `ob_size` field). The basic size includes the fields in the instance declared by the macro [`PyObject_HEAD`](structures#c.PyObject_HEAD "PyObject_HEAD") or [`PyObject_VAR_HEAD`](structures#c.PyObject_VAR_HEAD "PyObject_VAR_HEAD") (whichever is used to declare the instance struct) and this in turn includes the `_ob_prev` and `_ob_next` fields if they are present. This means that the only correct way to get an initializer for the [`tp_basicsize`](#c.PyTypeObject.tp_basicsize "PyTypeObject.tp_basicsize") is to use the `sizeof` operator on the struct used to declare the instance layout. The basic size does not include the GC header size. A note about alignment: if the variable items require a particular alignment, this should be taken care of by the value of [`tp_basicsize`](#c.PyTypeObject.tp_basicsize "PyTypeObject.tp_basicsize"). Example: suppose a type implements an array of `double`. [`tp_itemsize`](#c.PyTypeObject.tp_itemsize "PyTypeObject.tp_itemsize") is `sizeof(double)`. It is the programmer’s responsibility that [`tp_basicsize`](#c.PyTypeObject.tp_basicsize "PyTypeObject.tp_basicsize") is a multiple of `sizeof(double)` (assuming this is the alignment requirement for `double`). For any type with variable-length instances, this field must not be `NULL`. **Inheritance:** These fields are inherited separately by subtypes. If the base type has a non-zero [`tp_itemsize`](#c.PyTypeObject.tp_itemsize "PyTypeObject.tp_itemsize"), it is generally not safe to set [`tp_itemsize`](#c.PyTypeObject.tp_itemsize "PyTypeObject.tp_itemsize") to a different non-zero value in a subtype (though this depends on the implementation of the base type). `destructor PyTypeObject.tp_dealloc` A pointer to the instance destructor function. This function must be defined unless the type guarantees that its instances will never be deallocated (as is the case for the singletons `None` and `Ellipsis`). The function signature is: ``` void tp_dealloc(PyObject *self); ``` The destructor function is called by the [`Py_DECREF()`](refcounting#c.Py_DECREF "Py_DECREF") and [`Py_XDECREF()`](refcounting#c.Py_XDECREF "Py_XDECREF") macros when the new reference count is zero. At this point, the instance is still in existence, but there are no references to it. The destructor function should free all references which the instance owns, free all memory buffers owned by the instance (using the freeing function corresponding to the allocation function used to allocate the buffer), and call the type’s [`tp_free`](#c.PyTypeObject.tp_free "PyTypeObject.tp_free") function. If the type is not subtypable (doesn’t have the [`Py_TPFLAGS_BASETYPE`](#Py_TPFLAGS_BASETYPE "Py_TPFLAGS_BASETYPE") flag bit set), it is permissible to call the object deallocator directly instead of via [`tp_free`](#c.PyTypeObject.tp_free "PyTypeObject.tp_free"). The object deallocator should be the one used to allocate the instance; this is normally [`PyObject_Del()`](allocation#c.PyObject_Del "PyObject_Del") if the instance was allocated using [`PyObject_New()`](allocation#c.PyObject_New "PyObject_New") or `PyObject_VarNew()`, or [`PyObject_GC_Del()`](gcsupport#c.PyObject_GC_Del "PyObject_GC_Del") if the instance was allocated using [`PyObject_GC_New()`](gcsupport#c.PyObject_GC_New "PyObject_GC_New") or [`PyObject_GC_NewVar()`](gcsupport#c.PyObject_GC_NewVar "PyObject_GC_NewVar"). If the type supports garbage collection (has the [`Py_TPFLAGS_HAVE_GC`](#Py_TPFLAGS_HAVE_GC "Py_TPFLAGS_HAVE_GC") flag bit set), the destructor should call [`PyObject_GC_UnTrack()`](gcsupport#c.PyObject_GC_UnTrack "PyObject_GC_UnTrack") before clearing any member fields. ``` static void foo_dealloc(foo_object *self) { PyObject_GC_UnTrack(self); Py_CLEAR(self->ref); Py_TYPE(self)->tp_free((PyObject *)self); } ``` Finally, if the type is heap allocated ([`Py_TPFLAGS_HEAPTYPE`](#Py_TPFLAGS_HEAPTYPE "Py_TPFLAGS_HEAPTYPE")), the deallocator should decrement the reference count for its type object after calling the type deallocator. In order to avoid dangling pointers, the recommended way to achieve this is: ``` static void foo_dealloc(foo_object *self) { PyTypeObject *tp = Py_TYPE(self); // free references and buffers here tp->tp_free(self); Py_DECREF(tp); } ``` **Inheritance:** This field is inherited by subtypes. `Py_ssize_t PyTypeObject.tp_vectorcall_offset` An optional offset to a per-instance function that implements calling the object using the [vectorcall protocol](call#vectorcall), a more efficient alternative of the simpler [`tp_call`](#c.PyTypeObject.tp_call "PyTypeObject.tp_call"). This field is only used if the flag [`Py_TPFLAGS_HAVE_VECTORCALL`](#Py_TPFLAGS_HAVE_VECTORCALL "Py_TPFLAGS_HAVE_VECTORCALL") is set. If so, this must be a positive integer containing the offset in the instance of a [`vectorcallfunc`](call#c.vectorcallfunc "vectorcallfunc") pointer. The *vectorcallfunc* pointer may be `NULL`, in which case the instance behaves as if [`Py_TPFLAGS_HAVE_VECTORCALL`](#Py_TPFLAGS_HAVE_VECTORCALL "Py_TPFLAGS_HAVE_VECTORCALL") was not set: calling the instance falls back to [`tp_call`](#c.PyTypeObject.tp_call "PyTypeObject.tp_call"). Any class that sets `Py_TPFLAGS_HAVE_VECTORCALL` must also set [`tp_call`](#c.PyTypeObject.tp_call "PyTypeObject.tp_call") and make sure its behaviour is consistent with the *vectorcallfunc* function. This can be done by setting *tp\_call* to [`PyVectorcall_Call()`](call#c.PyVectorcall_Call "PyVectorcall_Call"). Warning It is not recommended for [heap types](#heap-types) to implement the vectorcall protocol. When a user sets [`__call__`](../reference/datamodel#object.__call__ "object.__call__") in Python code, only *tp\_call* is updated, likely making it inconsistent with the vectorcall function. Note The semantics of the `tp_vectorcall_offset` slot are provisional and expected to be finalized in Python 3.9. If you use vectorcall, plan for updating your code for Python 3.9. Changed in version 3.8: Before version 3.8, this slot was named `tp_print`. In Python 2.x, it was used for printing to a file. In Python 3.0 to 3.7, it was unused. **Inheritance:** This field is always inherited. However, the [`Py_TPFLAGS_HAVE_VECTORCALL`](#Py_TPFLAGS_HAVE_VECTORCALL "Py_TPFLAGS_HAVE_VECTORCALL") flag is not always inherited. If it’s not, then the subclass won’t use [vectorcall](call#vectorcall), except when [`PyVectorcall_Call()`](call#c.PyVectorcall_Call "PyVectorcall_Call") is explicitly called. This is in particular the case for [heap types](#id4) (including subclasses defined in Python). `getattrfunc PyTypeObject.tp_getattr` An optional pointer to the get-attribute-string function. This field is deprecated. When it is defined, it should point to a function that acts the same as the [`tp_getattro`](#c.PyTypeObject.tp_getattro "PyTypeObject.tp_getattro") function, but taking a C string instead of a Python string object to give the attribute name. **Inheritance:** Group: `tp_getattr`, `tp_getattro` This field is inherited by subtypes together with [`tp_getattro`](#c.PyTypeObject.tp_getattro "PyTypeObject.tp_getattro"): a subtype inherits both [`tp_getattr`](#c.PyTypeObject.tp_getattr "PyTypeObject.tp_getattr") and [`tp_getattro`](#c.PyTypeObject.tp_getattro "PyTypeObject.tp_getattro") from its base type when the subtype’s [`tp_getattr`](#c.PyTypeObject.tp_getattr "PyTypeObject.tp_getattr") and [`tp_getattro`](#c.PyTypeObject.tp_getattro "PyTypeObject.tp_getattro") are both `NULL`. `setattrfunc PyTypeObject.tp_setattr` An optional pointer to the function for setting and deleting attributes. This field is deprecated. When it is defined, it should point to a function that acts the same as the [`tp_setattro`](#c.PyTypeObject.tp_setattro "PyTypeObject.tp_setattro") function, but taking a C string instead of a Python string object to give the attribute name. **Inheritance:** Group: `tp_setattr`, `tp_setattro` This field is inherited by subtypes together with [`tp_setattro`](#c.PyTypeObject.tp_setattro "PyTypeObject.tp_setattro"): a subtype inherits both [`tp_setattr`](#c.PyTypeObject.tp_setattr "PyTypeObject.tp_setattr") and [`tp_setattro`](#c.PyTypeObject.tp_setattro "PyTypeObject.tp_setattro") from its base type when the subtype’s [`tp_setattr`](#c.PyTypeObject.tp_setattr "PyTypeObject.tp_setattr") and [`tp_setattro`](#c.PyTypeObject.tp_setattro "PyTypeObject.tp_setattro") are both `NULL`. `PyAsyncMethods* PyTypeObject.tp_as_async` Pointer to an additional structure that contains fields relevant only to objects which implement [awaitable](../glossary#term-awaitable) and [asynchronous iterator](../glossary#term-asynchronous-iterator) protocols at the C-level. See [Async Object Structures](#async-structs) for details. New in version 3.5: Formerly known as `tp_compare` and `tp_reserved`. **Inheritance:** The [`tp_as_async`](#c.PyTypeObject.tp_as_async "PyTypeObject.tp_as_async") field is not inherited, but the contained fields are inherited individually. `reprfunc PyTypeObject.tp_repr` An optional pointer to a function that implements the built-in function [`repr()`](../library/functions#repr "repr"). The signature is the same as for [`PyObject_Repr()`](object#c.PyObject_Repr "PyObject_Repr"): ``` PyObject *tp_repr(PyObject *self); ``` The function must return a string or a Unicode object. Ideally, this function should return a string that, when passed to [`eval()`](../library/functions#eval "eval"), given a suitable environment, returns an object with the same value. If this is not feasible, it should return a string starting with `'<'` and ending with `'>'` from which both the type and the value of the object can be deduced. **Inheritance:** This field is inherited by subtypes. **Default:** When this field is not set, a string of the form `<%s object at %p>` is returned, where `%s` is replaced by the type name, and `%p` by the object’s memory address. `PyNumberMethods* PyTypeObject.tp_as_number` Pointer to an additional structure that contains fields relevant only to objects which implement the number protocol. These fields are documented in [Number Object Structures](#number-structs). **Inheritance:** The [`tp_as_number`](#c.PyTypeObject.tp_as_number "PyTypeObject.tp_as_number") field is not inherited, but the contained fields are inherited individually. `PySequenceMethods* PyTypeObject.tp_as_sequence` Pointer to an additional structure that contains fields relevant only to objects which implement the sequence protocol. These fields are documented in [Sequence Object Structures](#sequence-structs). **Inheritance:** The [`tp_as_sequence`](#c.PyTypeObject.tp_as_sequence "PyTypeObject.tp_as_sequence") field is not inherited, but the contained fields are inherited individually. `PyMappingMethods* PyTypeObject.tp_as_mapping` Pointer to an additional structure that contains fields relevant only to objects which implement the mapping protocol. These fields are documented in [Mapping Object Structures](#mapping-structs). **Inheritance:** The [`tp_as_mapping`](#c.PyTypeObject.tp_as_mapping "PyTypeObject.tp_as_mapping") field is not inherited, but the contained fields are inherited individually. `hashfunc PyTypeObject.tp_hash` An optional pointer to a function that implements the built-in function [`hash()`](../library/functions#hash "hash"). The signature is the same as for [`PyObject_Hash()`](object#c.PyObject_Hash "PyObject_Hash"): ``` Py_hash_t tp_hash(PyObject *); ``` The value `-1` should not be returned as a normal return value; when an error occurs during the computation of the hash value, the function should set an exception and return `-1`. When this field is not set (*and* `tp_richcompare` is not set), an attempt to take the hash of the object raises [`TypeError`](../library/exceptions#TypeError "TypeError"). This is the same as setting it to [`PyObject_HashNotImplemented()`](object#c.PyObject_HashNotImplemented "PyObject_HashNotImplemented"). This field can be set explicitly to [`PyObject_HashNotImplemented()`](object#c.PyObject_HashNotImplemented "PyObject_HashNotImplemented") to block inheritance of the hash method from a parent type. This is interpreted as the equivalent of `__hash__ = None` at the Python level, causing `isinstance(o, collections.Hashable)` to correctly return `False`. Note that the converse is also true - setting `__hash__ = None` on a class at the Python level will result in the `tp_hash` slot being set to [`PyObject_HashNotImplemented()`](object#c.PyObject_HashNotImplemented "PyObject_HashNotImplemented"). **Inheritance:** Group: `tp_hash`, `tp_richcompare` This field is inherited by subtypes together with [`tp_richcompare`](#c.PyTypeObject.tp_richcompare "PyTypeObject.tp_richcompare"): a subtype inherits both of [`tp_richcompare`](#c.PyTypeObject.tp_richcompare "PyTypeObject.tp_richcompare") and [`tp_hash`](#c.PyTypeObject.tp_hash "PyTypeObject.tp_hash"), when the subtype’s [`tp_richcompare`](#c.PyTypeObject.tp_richcompare "PyTypeObject.tp_richcompare") and [`tp_hash`](#c.PyTypeObject.tp_hash "PyTypeObject.tp_hash") are both `NULL`. `ternaryfunc PyTypeObject.tp_call` An optional pointer to a function that implements calling the object. This should be `NULL` if the object is not callable. The signature is the same as for [`PyObject_Call()`](call#c.PyObject_Call "PyObject_Call"): ``` PyObject *tp_call(PyObject *self, PyObject *args, PyObject *kwargs); ``` **Inheritance:** This field is inherited by subtypes. `reprfunc PyTypeObject.tp_str` An optional pointer to a function that implements the built-in operation [`str()`](../library/stdtypes#str "str"). (Note that [`str`](../library/stdtypes#str "str") is a type now, and [`str()`](../library/stdtypes#str "str") calls the constructor for that type. This constructor calls [`PyObject_Str()`](object#c.PyObject_Str "PyObject_Str") to do the actual work, and [`PyObject_Str()`](object#c.PyObject_Str "PyObject_Str") will call this handler.) The signature is the same as for [`PyObject_Str()`](object#c.PyObject_Str "PyObject_Str"): ``` PyObject *tp_str(PyObject *self); ``` The function must return a string or a Unicode object. It should be a “friendly” string representation of the object, as this is the representation that will be used, among other things, by the [`print()`](../library/functions#print "print") function. **Inheritance:** This field is inherited by subtypes. **Default:** When this field is not set, [`PyObject_Repr()`](object#c.PyObject_Repr "PyObject_Repr") is called to return a string representation. `getattrofunc PyTypeObject.tp_getattro` An optional pointer to the get-attribute function. The signature is the same as for [`PyObject_GetAttr()`](object#c.PyObject_GetAttr "PyObject_GetAttr"): ``` PyObject *tp_getattro(PyObject *self, PyObject *attr); ``` It is usually convenient to set this field to [`PyObject_GenericGetAttr()`](object#c.PyObject_GenericGetAttr "PyObject_GenericGetAttr"), which implements the normal way of looking for object attributes. **Inheritance:** Group: `tp_getattr`, `tp_getattro` This field is inherited by subtypes together with [`tp_getattr`](#c.PyTypeObject.tp_getattr "PyTypeObject.tp_getattr"): a subtype inherits both [`tp_getattr`](#c.PyTypeObject.tp_getattr "PyTypeObject.tp_getattr") and [`tp_getattro`](#c.PyTypeObject.tp_getattro "PyTypeObject.tp_getattro") from its base type when the subtype’s [`tp_getattr`](#c.PyTypeObject.tp_getattr "PyTypeObject.tp_getattr") and [`tp_getattro`](#c.PyTypeObject.tp_getattro "PyTypeObject.tp_getattro") are both `NULL`. **Default:** `PyBaseObject_Type` uses [`PyObject_GenericGetAttr()`](object#c.PyObject_GenericGetAttr "PyObject_GenericGetAttr"). `setattrofunc PyTypeObject.tp_setattro` An optional pointer to the function for setting and deleting attributes. The signature is the same as for [`PyObject_SetAttr()`](object#c.PyObject_SetAttr "PyObject_SetAttr"): ``` int tp_setattro(PyObject *self, PyObject *attr, PyObject *value); ``` In addition, setting *value* to `NULL` to delete an attribute must be supported. It is usually convenient to set this field to [`PyObject_GenericSetAttr()`](object#c.PyObject_GenericSetAttr "PyObject_GenericSetAttr"), which implements the normal way of setting object attributes. **Inheritance:** Group: `tp_setattr`, `tp_setattro` This field is inherited by subtypes together with [`tp_setattr`](#c.PyTypeObject.tp_setattr "PyTypeObject.tp_setattr"): a subtype inherits both [`tp_setattr`](#c.PyTypeObject.tp_setattr "PyTypeObject.tp_setattr") and [`tp_setattro`](#c.PyTypeObject.tp_setattro "PyTypeObject.tp_setattro") from its base type when the subtype’s [`tp_setattr`](#c.PyTypeObject.tp_setattr "PyTypeObject.tp_setattr") and [`tp_setattro`](#c.PyTypeObject.tp_setattro "PyTypeObject.tp_setattro") are both `NULL`. **Default:** `PyBaseObject_Type` uses [`PyObject_GenericSetAttr()`](object#c.PyObject_GenericSetAttr "PyObject_GenericSetAttr"). `PyBufferProcs* PyTypeObject.tp_as_buffer` Pointer to an additional structure that contains fields relevant only to objects which implement the buffer interface. These fields are documented in [Buffer Object Structures](#buffer-structs). **Inheritance:** The [`tp_as_buffer`](#c.PyTypeObject.tp_as_buffer "PyTypeObject.tp_as_buffer") field is not inherited, but the contained fields are inherited individually. `unsigned long PyTypeObject.tp_flags` This field is a bit mask of various flags. Some flags indicate variant semantics for certain situations; others are used to indicate that certain fields in the type object (or in the extension structures referenced via [`tp_as_number`](#c.PyTypeObject.tp_as_number "PyTypeObject.tp_as_number"), [`tp_as_sequence`](#c.PyTypeObject.tp_as_sequence "PyTypeObject.tp_as_sequence"), [`tp_as_mapping`](#c.PyTypeObject.tp_as_mapping "PyTypeObject.tp_as_mapping"), and [`tp_as_buffer`](#c.PyTypeObject.tp_as_buffer "PyTypeObject.tp_as_buffer")) that were historically not always present are valid; if such a flag bit is clear, the type fields it guards must not be accessed and must be considered to have a zero or `NULL` value instead. **Inheritance:** Inheritance of this field is complicated. Most flag bits are inherited individually, i.e. if the base type has a flag bit set, the subtype inherits this flag bit. The flag bits that pertain to extension structures are strictly inherited if the extension structure is inherited, i.e. the base type’s value of the flag bit is copied into the subtype together with a pointer to the extension structure. The [`Py_TPFLAGS_HAVE_GC`](#Py_TPFLAGS_HAVE_GC "Py_TPFLAGS_HAVE_GC") flag bit is inherited together with the [`tp_traverse`](#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse") and [`tp_clear`](#c.PyTypeObject.tp_clear "PyTypeObject.tp_clear") fields, i.e. if the [`Py_TPFLAGS_HAVE_GC`](#Py_TPFLAGS_HAVE_GC "Py_TPFLAGS_HAVE_GC") flag bit is clear in the subtype and the [`tp_traverse`](#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse") and [`tp_clear`](#c.PyTypeObject.tp_clear "PyTypeObject.tp_clear") fields in the subtype exist and have `NULL` values. **Default:** `PyBaseObject_Type` uses `Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE`. **Bit Masks:** The following bit masks are currently defined; these can be ORed together using the `|` operator to form the value of the [`tp_flags`](#c.PyTypeObject.tp_flags "PyTypeObject.tp_flags") field. The macro [`PyType_HasFeature()`](type#c.PyType_HasFeature "PyType_HasFeature") takes a type and a flags value, *tp* and *f*, and checks whether `tp->tp_flags & f` is non-zero. `Py_TPFLAGS_HEAPTYPE` This bit is set when the type object itself is allocated on the heap, for example, types created dynamically using [`PyType_FromSpec()`](type#c.PyType_FromSpec "PyType_FromSpec"). In this case, the `ob_type` field of its instances is considered a reference to the type, and the type object is INCREF’ed when a new instance is created, and DECREF’ed when an instance is destroyed (this does not apply to instances of subtypes; only the type referenced by the instance’s ob\_type gets INCREF’ed or DECREF’ed). **Inheritance:** ??? `Py_TPFLAGS_BASETYPE` This bit is set when the type can be used as the base type of another type. If this bit is clear, the type cannot be subtyped (similar to a “final” class in Java). **Inheritance:** ??? `Py_TPFLAGS_READY` This bit is set when the type object has been fully initialized by [`PyType_Ready()`](type#c.PyType_Ready "PyType_Ready"). **Inheritance:** ??? `Py_TPFLAGS_READYING` This bit is set while [`PyType_Ready()`](type#c.PyType_Ready "PyType_Ready") is in the process of initializing the type object. **Inheritance:** ??? `Py_TPFLAGS_HAVE_GC` This bit is set when the object supports garbage collection. If this bit is set, instances must be created using [`PyObject_GC_New()`](gcsupport#c.PyObject_GC_New "PyObject_GC_New") and destroyed using [`PyObject_GC_Del()`](gcsupport#c.PyObject_GC_Del "PyObject_GC_Del"). More information in section [Supporting Cyclic Garbage Collection](gcsupport#supporting-cycle-detection). This bit also implies that the GC-related fields [`tp_traverse`](#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse") and [`tp_clear`](#c.PyTypeObject.tp_clear "PyTypeObject.tp_clear") are present in the type object. **Inheritance:** Group: [`Py_TPFLAGS_HAVE_GC`](#Py_TPFLAGS_HAVE_GC "Py_TPFLAGS_HAVE_GC"), `tp_traverse`, `tp_clear` The [`Py_TPFLAGS_HAVE_GC`](#Py_TPFLAGS_HAVE_GC "Py_TPFLAGS_HAVE_GC") flag bit is inherited together with the `tp_traverse` and `tp_clear` fields, i.e. if the [`Py_TPFLAGS_HAVE_GC`](#Py_TPFLAGS_HAVE_GC "Py_TPFLAGS_HAVE_GC") flag bit is clear in the subtype and the `tp_traverse` and `tp_clear` fields in the subtype exist and have `NULL` values. `Py_TPFLAGS_DEFAULT` This is a bitmask of all the bits that pertain to the existence of certain fields in the type object and its extension structures. Currently, it includes the following bits: `Py_TPFLAGS_HAVE_STACKLESS_EXTENSION`, `Py_TPFLAGS_HAVE_VERSION_TAG`. **Inheritance:** ??? `Py_TPFLAGS_METHOD_DESCRIPTOR` This bit indicates that objects behave like unbound methods. If this flag is set for `type(meth)`, then: * `meth.__get__(obj, cls)(*args, **kwds)` (with `obj` not None) must be equivalent to `meth(obj, *args, **kwds)`. * `meth.__get__(None, cls)(*args, **kwds)` must be equivalent to `meth(*args, **kwds)`. This flag enables an optimization for typical method calls like `obj.meth()`: it avoids creating a temporary “bound method” object for `obj.meth`. New in version 3.8. **Inheritance:** This flag is never inherited by heap types. For extension types, it is inherited whenever [`tp_descr_get`](#c.PyTypeObject.tp_descr_get "PyTypeObject.tp_descr_get") is inherited. `Py_TPFLAGS_LONG_SUBCLASS` `Py_TPFLAGS_LIST_SUBCLASS` `Py_TPFLAGS_TUPLE_SUBCLASS` `Py_TPFLAGS_BYTES_SUBCLASS` `Py_TPFLAGS_UNICODE_SUBCLASS` `Py_TPFLAGS_DICT_SUBCLASS` `Py_TPFLAGS_BASE_EXC_SUBCLASS` `Py_TPFLAGS_TYPE_SUBCLASS` These flags are used by functions such as [`PyLong_Check()`](long#c.PyLong_Check "PyLong_Check") to quickly determine if a type is a subclass of a built-in type; such specific checks are faster than a generic check, like [`PyObject_IsInstance()`](object#c.PyObject_IsInstance "PyObject_IsInstance"). Custom types that inherit from built-ins should have their [`tp_flags`](#c.PyTypeObject.tp_flags "PyTypeObject.tp_flags") set appropriately, or the code that interacts with such types will behave differently depending on what kind of check is used. `Py_TPFLAGS_HAVE_FINALIZE` This bit is set when the [`tp_finalize`](#c.PyTypeObject.tp_finalize "PyTypeObject.tp_finalize") slot is present in the type structure. New in version 3.4. Deprecated since version 3.8: This flag isn’t necessary anymore, as the interpreter assumes the [`tp_finalize`](#c.PyTypeObject.tp_finalize "PyTypeObject.tp_finalize") slot is always present in the type structure. `Py_TPFLAGS_HAVE_VECTORCALL` This bit is set when the class implements the [vectorcall protocol](call#vectorcall). See [`tp_vectorcall_offset`](#c.PyTypeObject.tp_vectorcall_offset "PyTypeObject.tp_vectorcall_offset") for details. **Inheritance:** This bit is inherited for *static* subtypes if [`tp_call`](#c.PyTypeObject.tp_call "PyTypeObject.tp_call") is also inherited. [Heap types](#id4) do not inherit `Py_TPFLAGS_HAVE_VECTORCALL`. New in version 3.9. `const char* PyTypeObject.tp_doc` An optional pointer to a NUL-terminated C string giving the docstring for this type object. This is exposed as the `__doc__` attribute on the type and instances of the type. **Inheritance:** This field is *not* inherited by subtypes. `traverseproc PyTypeObject.tp_traverse` An optional pointer to a traversal function for the garbage collector. This is only used if the [`Py_TPFLAGS_HAVE_GC`](#Py_TPFLAGS_HAVE_GC "Py_TPFLAGS_HAVE_GC") flag bit is set. The signature is: ``` int tp_traverse(PyObject *self, visitproc visit, void *arg); ``` More information about Python’s garbage collection scheme can be found in section [Supporting Cyclic Garbage Collection](gcsupport#supporting-cycle-detection). The [`tp_traverse`](#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse") pointer is used by the garbage collector to detect reference cycles. A typical implementation of a [`tp_traverse`](#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse") function simply calls [`Py_VISIT()`](gcsupport#c.Py_VISIT "Py_VISIT") on each of the instance’s members that are Python objects that the instance owns. For example, this is function `local_traverse()` from the [`_thread`](../library/_thread#module-_thread "_thread: Low-level threading API.") extension module: ``` static int local_traverse(localobject *self, visitproc visit, void *arg) { Py_VISIT(self->args); Py_VISIT(self->kw); Py_VISIT(self->dict); return 0; } ``` Note that [`Py_VISIT()`](gcsupport#c.Py_VISIT "Py_VISIT") is called only on those members that can participate in reference cycles. Although there is also a `self->key` member, it can only be `NULL` or a Python string and therefore cannot be part of a reference cycle. On the other hand, even if you know a member can never be part of a cycle, as a debugging aid you may want to visit it anyway just so the [`gc`](../library/gc#module-gc "gc: Interface to the cycle-detecting garbage collector.") module’s [`get_referents()`](../library/gc#gc.get_referents "gc.get_referents") function will include it. Warning When implementing [`tp_traverse`](#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse"), only the members that the instance *owns* (by having strong references to them) must be visited. For instance, if an object supports weak references via the [`tp_weaklist`](#c.PyTypeObject.tp_weaklist "PyTypeObject.tp_weaklist") slot, the pointer supporting the linked list (what *tp\_weaklist* points to) must **not** be visited as the instance does not directly own the weak references to itself (the weakreference list is there to support the weak reference machinery, but the instance has no strong reference to the elements inside it, as they are allowed to be removed even if the instance is still alive). Note that [`Py_VISIT()`](gcsupport#c.Py_VISIT "Py_VISIT") requires the *visit* and *arg* parameters to `local_traverse()` to have these specific names; don’t name them just anything. Heap-allocated types ([`Py_TPFLAGS_HEAPTYPE`](#Py_TPFLAGS_HEAPTYPE "Py_TPFLAGS_HEAPTYPE"), such as those created with [`PyType_FromSpec()`](type#c.PyType_FromSpec "PyType_FromSpec") and similar APIs) hold a reference to their type. Their traversal function must therefore either visit [`Py_TYPE(self)`](structures#c.Py_TYPE "Py_TYPE"), or delegate this responsibility by calling `tp_traverse` of another heap-allocated type (such as a heap-allocated superclass). If they do not, the type object may not be garbage-collected. Changed in version 3.9: Heap-allocated types are expected to visit `Py_TYPE(self)` in `tp_traverse`. In earlier versions of Python, due to [bug 40217](https://bugs.python.org/issue40217), doing this may lead to crashes in subclasses. **Inheritance:** Group: [`Py_TPFLAGS_HAVE_GC`](#Py_TPFLAGS_HAVE_GC "Py_TPFLAGS_HAVE_GC"), `tp_traverse`, `tp_clear` This field is inherited by subtypes together with [`tp_clear`](#c.PyTypeObject.tp_clear "PyTypeObject.tp_clear") and the [`Py_TPFLAGS_HAVE_GC`](#Py_TPFLAGS_HAVE_GC "Py_TPFLAGS_HAVE_GC") flag bit: the flag bit, [`tp_traverse`](#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse"), and [`tp_clear`](#c.PyTypeObject.tp_clear "PyTypeObject.tp_clear") are all inherited from the base type if they are all zero in the subtype. `inquiry PyTypeObject.tp_clear` An optional pointer to a clear function for the garbage collector. This is only used if the [`Py_TPFLAGS_HAVE_GC`](#Py_TPFLAGS_HAVE_GC "Py_TPFLAGS_HAVE_GC") flag bit is set. The signature is: ``` int tp_clear(PyObject *); ``` The [`tp_clear`](#c.PyTypeObject.tp_clear "PyTypeObject.tp_clear") member function is used to break reference cycles in cyclic garbage detected by the garbage collector. Taken together, all [`tp_clear`](#c.PyTypeObject.tp_clear "PyTypeObject.tp_clear") functions in the system must combine to break all reference cycles. This is subtle, and if in any doubt supply a [`tp_clear`](#c.PyTypeObject.tp_clear "PyTypeObject.tp_clear") function. For example, the tuple type does not implement a [`tp_clear`](#c.PyTypeObject.tp_clear "PyTypeObject.tp_clear") function, because it’s possible to prove that no reference cycle can be composed entirely of tuples. Therefore the [`tp_clear`](#c.PyTypeObject.tp_clear "PyTypeObject.tp_clear") functions of other types must be sufficient to break any cycle containing a tuple. This isn’t immediately obvious, and there’s rarely a good reason to avoid implementing [`tp_clear`](#c.PyTypeObject.tp_clear "PyTypeObject.tp_clear"). Implementations of [`tp_clear`](#c.PyTypeObject.tp_clear "PyTypeObject.tp_clear") should drop the instance’s references to those of its members that may be Python objects, and set its pointers to those members to `NULL`, as in the following example: ``` static int local_clear(localobject *self) { Py_CLEAR(self->key); Py_CLEAR(self->args); Py_CLEAR(self->kw); Py_CLEAR(self->dict); return 0; } ``` The [`Py_CLEAR()`](refcounting#c.Py_CLEAR "Py_CLEAR") macro should be used, because clearing references is delicate: the reference to the contained object must not be decremented until after the pointer to the contained object is set to `NULL`. This is because decrementing the reference count may cause the contained object to become trash, triggering a chain of reclamation activity that may include invoking arbitrary Python code (due to finalizers, or weakref callbacks, associated with the contained object). If it’s possible for such code to reference *self* again, it’s important that the pointer to the contained object be `NULL` at that time, so that *self* knows the contained object can no longer be used. The [`Py_CLEAR()`](refcounting#c.Py_CLEAR "Py_CLEAR") macro performs the operations in a safe order. Note that [`tp_clear`](#c.PyTypeObject.tp_clear "PyTypeObject.tp_clear") is not *always* called before an instance is deallocated. For example, when reference counting is enough to determine that an object is no longer used, the cyclic garbage collector is not involved and [`tp_dealloc`](#c.PyTypeObject.tp_dealloc "PyTypeObject.tp_dealloc") is called directly. Because the goal of [`tp_clear`](#c.PyTypeObject.tp_clear "PyTypeObject.tp_clear") functions is to break reference cycles, it’s not necessary to clear contained objects like Python strings or Python integers, which can’t participate in reference cycles. On the other hand, it may be convenient to clear all contained Python objects, and write the type’s [`tp_dealloc`](#c.PyTypeObject.tp_dealloc "PyTypeObject.tp_dealloc") function to invoke [`tp_clear`](#c.PyTypeObject.tp_clear "PyTypeObject.tp_clear"). More information about Python’s garbage collection scheme can be found in section [Supporting Cyclic Garbage Collection](gcsupport#supporting-cycle-detection). **Inheritance:** Group: [`Py_TPFLAGS_HAVE_GC`](#Py_TPFLAGS_HAVE_GC "Py_TPFLAGS_HAVE_GC"), `tp_traverse`, `tp_clear` This field is inherited by subtypes together with [`tp_traverse`](#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse") and the [`Py_TPFLAGS_HAVE_GC`](#Py_TPFLAGS_HAVE_GC "Py_TPFLAGS_HAVE_GC") flag bit: the flag bit, [`tp_traverse`](#c.PyTypeObject.tp_traverse "PyTypeObject.tp_traverse"), and [`tp_clear`](#c.PyTypeObject.tp_clear "PyTypeObject.tp_clear") are all inherited from the base type if they are all zero in the subtype. `richcmpfunc PyTypeObject.tp_richcompare` An optional pointer to the rich comparison function, whose signature is: ``` PyObject *tp_richcompare(PyObject *self, PyObject *other, int op); ``` The first parameter is guaranteed to be an instance of the type that is defined by [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject"). The function should return the result of the comparison (usually `Py_True` or `Py_False`). If the comparison is undefined, it must return `Py_NotImplemented`, if another error occurred it must return `NULL` and set an exception condition. The following constants are defined to be used as the third argument for [`tp_richcompare`](#c.PyTypeObject.tp_richcompare "PyTypeObject.tp_richcompare") and for [`PyObject_RichCompare()`](object#c.PyObject_RichCompare "PyObject_RichCompare"): | Constant | Comparison | | --- | --- | | `Py_LT` | `<` | | `Py_LE` | `<=` | | `Py_EQ` | `==` | | `Py_NE` | `!=` | | `Py_GT` | `>` | | `Py_GE` | `>=` | The following macro is defined to ease writing rich comparison functions: `Py_RETURN_RICHCOMPARE(VAL_A, VAL_B, op)` Return `Py_True` or `Py_False` from the function, depending on the result of a comparison. VAL\_A and VAL\_B must be orderable by C comparison operators (for example, they may be C ints or floats). The third argument specifies the requested operation, as for [`PyObject_RichCompare()`](object#c.PyObject_RichCompare "PyObject_RichCompare"). The return value’s reference count is properly incremented. On error, sets an exception and returns `NULL` from the function. New in version 3.7. **Inheritance:** Group: `tp_hash`, `tp_richcompare` This field is inherited by subtypes together with [`tp_hash`](#c.PyTypeObject.tp_hash "PyTypeObject.tp_hash"): a subtype inherits [`tp_richcompare`](#c.PyTypeObject.tp_richcompare "PyTypeObject.tp_richcompare") and [`tp_hash`](#c.PyTypeObject.tp_hash "PyTypeObject.tp_hash") when the subtype’s [`tp_richcompare`](#c.PyTypeObject.tp_richcompare "PyTypeObject.tp_richcompare") and [`tp_hash`](#c.PyTypeObject.tp_hash "PyTypeObject.tp_hash") are both `NULL`. **Default:** `PyBaseObject_Type` provides a `tp_richcompare` implementation, which may be inherited. However, if only `tp_hash` is defined, not even the inherited function is used and instances of the type will not be able to participate in any comparisons. `Py_ssize_t PyTypeObject.tp_weaklistoffset` If the instances of this type are weakly referenceable, this field is greater than zero and contains the offset in the instance structure of the weak reference list head (ignoring the GC header, if present); this offset is used by `PyObject_ClearWeakRefs()` and the `PyWeakref_*()` functions. The instance structure needs to include a field of type [`PyObject*`](structures#c.PyObject "PyObject") which is initialized to `NULL`. Do not confuse this field with [`tp_weaklist`](#c.PyTypeObject.tp_weaklist "PyTypeObject.tp_weaklist"); that is the list head for weak references to the type object itself. **Inheritance:** This field is inherited by subtypes, but see the rules listed below. A subtype may override this offset; this means that the subtype uses a different weak reference list head than the base type. Since the list head is always found via [`tp_weaklistoffset`](#c.PyTypeObject.tp_weaklistoffset "PyTypeObject.tp_weaklistoffset"), this should not be a problem. When a type defined by a class statement has no [`__slots__`](../reference/datamodel#object.__slots__ "object.__slots__") declaration, and none of its base types are weakly referenceable, the type is made weakly referenceable by adding a weak reference list head slot to the instance layout and setting the [`tp_weaklistoffset`](#c.PyTypeObject.tp_weaklistoffset "PyTypeObject.tp_weaklistoffset") of that slot’s offset. When a type’s [`__slots__`](../reference/datamodel#object.__slots__ "object.__slots__") declaration contains a slot named `__weakref__`, that slot becomes the weak reference list head for instances of the type, and the slot’s offset is stored in the type’s [`tp_weaklistoffset`](#c.PyTypeObject.tp_weaklistoffset "PyTypeObject.tp_weaklistoffset"). When a type’s [`__slots__`](../reference/datamodel#object.__slots__ "object.__slots__") declaration does not contain a slot named `__weakref__`, the type inherits its [`tp_weaklistoffset`](#c.PyTypeObject.tp_weaklistoffset "PyTypeObject.tp_weaklistoffset") from its base type. `getiterfunc PyTypeObject.tp_iter` An optional pointer to a function that returns an iterator for the object. Its presence normally signals that the instances of this type are iterable (although sequences may be iterable without this function). This function has the same signature as [`PyObject_GetIter()`](object#c.PyObject_GetIter "PyObject_GetIter"): ``` PyObject *tp_iter(PyObject *self); ``` **Inheritance:** This field is inherited by subtypes. `iternextfunc PyTypeObject.tp_iternext` An optional pointer to a function that returns the next item in an iterator. The signature is: ``` PyObject *tp_iternext(PyObject *self); ``` When the iterator is exhausted, it must return `NULL`; a [`StopIteration`](../library/exceptions#StopIteration "StopIteration") exception may or may not be set. When another error occurs, it must return `NULL` too. Its presence signals that the instances of this type are iterators. Iterator types should also define the [`tp_iter`](#c.PyTypeObject.tp_iter "PyTypeObject.tp_iter") function, and that function should return the iterator instance itself (not a new iterator instance). This function has the same signature as [`PyIter_Next()`](iter#c.PyIter_Next "PyIter_Next"). **Inheritance:** This field is inherited by subtypes. `struct PyMethodDef* PyTypeObject.tp_methods` An optional pointer to a static `NULL`-terminated array of [`PyMethodDef`](structures#c.PyMethodDef "PyMethodDef") structures, declaring regular methods of this type. For each entry in the array, an entry is added to the type’s dictionary (see [`tp_dict`](#c.PyTypeObject.tp_dict "PyTypeObject.tp_dict") below) containing a method descriptor. **Inheritance:** This field is not inherited by subtypes (methods are inherited through a different mechanism). `struct PyMemberDef* PyTypeObject.tp_members` An optional pointer to a static `NULL`-terminated array of [`PyMemberDef`](structures#c.PyMemberDef "PyMemberDef") structures, declaring regular data members (fields or slots) of instances of this type. For each entry in the array, an entry is added to the type’s dictionary (see [`tp_dict`](#c.PyTypeObject.tp_dict "PyTypeObject.tp_dict") below) containing a member descriptor. **Inheritance:** This field is not inherited by subtypes (members are inherited through a different mechanism). `struct PyGetSetDef* PyTypeObject.tp_getset` An optional pointer to a static `NULL`-terminated array of [`PyGetSetDef`](structures#c.PyGetSetDef "PyGetSetDef") structures, declaring computed attributes of instances of this type. For each entry in the array, an entry is added to the type’s dictionary (see [`tp_dict`](#c.PyTypeObject.tp_dict "PyTypeObject.tp_dict") below) containing a getset descriptor. **Inheritance:** This field is not inherited by subtypes (computed attributes are inherited through a different mechanism). `PyTypeObject* PyTypeObject.tp_base` An optional pointer to a base type from which type properties are inherited. At this level, only single inheritance is supported; multiple inheritance require dynamically creating a type object by calling the metatype. Note Slot initialization is subject to the rules of initializing globals. C99 requires the initializers to be “address constants”. Function designators like [`PyType_GenericNew()`](type#c.PyType_GenericNew "PyType_GenericNew"), with implicit conversion to a pointer, are valid C99 address constants. However, the unary ‘&’ operator applied to a non-static variable like `PyBaseObject_Type()` is not required to produce an address constant. Compilers may support this (gcc does), MSVC does not. Both compilers are strictly standard conforming in this particular behavior. Consequently, [`tp_base`](#c.PyTypeObject.tp_base "PyTypeObject.tp_base") should be set in the extension module’s init function. **Inheritance:** This field is not inherited by subtypes (obviously). **Default:** This field defaults to `&PyBaseObject_Type` (which to Python programmers is known as the type [`object`](../library/functions#object "object")). `PyObject* PyTypeObject.tp_dict` The type’s dictionary is stored here by [`PyType_Ready()`](type#c.PyType_Ready "PyType_Ready"). This field should normally be initialized to `NULL` before PyType\_Ready is called; it may also be initialized to a dictionary containing initial attributes for the type. Once [`PyType_Ready()`](type#c.PyType_Ready "PyType_Ready") has initialized the type, extra attributes for the type may be added to this dictionary only if they don’t correspond to overloaded operations (like [`__add__()`](../reference/datamodel#object.__add__ "object.__add__")). **Inheritance:** This field is not inherited by subtypes (though the attributes defined in here are inherited through a different mechanism). **Default:** If this field is `NULL`, [`PyType_Ready()`](type#c.PyType_Ready "PyType_Ready") will assign a new dictionary to it. Warning It is not safe to use [`PyDict_SetItem()`](dict#c.PyDict_SetItem "PyDict_SetItem") on or otherwise modify [`tp_dict`](#c.PyTypeObject.tp_dict "PyTypeObject.tp_dict") with the dictionary C-API. `descrgetfunc PyTypeObject.tp_descr_get` An optional pointer to a “descriptor get” function. The function signature is: ``` PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type); ``` **Inheritance:** This field is inherited by subtypes. `descrsetfunc PyTypeObject.tp_descr_set` An optional pointer to a function for setting and deleting a descriptor’s value. The function signature is: ``` int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value); ``` The *value* argument is set to `NULL` to delete the value. **Inheritance:** This field is inherited by subtypes. `Py_ssize_t PyTypeObject.tp_dictoffset` If the instances of this type have a dictionary containing instance variables, this field is non-zero and contains the offset in the instances of the type of the instance variable dictionary; this offset is used by [`PyObject_GenericGetAttr()`](object#c.PyObject_GenericGetAttr "PyObject_GenericGetAttr"). Do not confuse this field with [`tp_dict`](#c.PyTypeObject.tp_dict "PyTypeObject.tp_dict"); that is the dictionary for attributes of the type object itself. If the value of this field is greater than zero, it specifies the offset from the start of the instance structure. If the value is less than zero, it specifies the offset from the *end* of the instance structure. A negative offset is more expensive to use, and should only be used when the instance structure contains a variable-length part. This is used for example to add an instance variable dictionary to subtypes of [`str`](../library/stdtypes#str "str") or [`tuple`](../library/stdtypes#tuple "tuple"). Note that the [`tp_basicsize`](#c.PyTypeObject.tp_basicsize "PyTypeObject.tp_basicsize") field should account for the dictionary added to the end in that case, even though the dictionary is not included in the basic object layout. On a system with a pointer size of 4 bytes, [`tp_dictoffset`](#c.PyTypeObject.tp_dictoffset "PyTypeObject.tp_dictoffset") should be set to `-4` to indicate that the dictionary is at the very end of the structure. The real dictionary offset in an instance can be computed from a negative [`tp_dictoffset`](#c.PyTypeObject.tp_dictoffset "PyTypeObject.tp_dictoffset") as follows: ``` dictoffset = tp_basicsize + abs(ob_size)*tp_itemsize + tp_dictoffset if dictoffset is not aligned on sizeof(void*): round up to sizeof(void*) ``` where [`tp_basicsize`](#c.PyTypeObject.tp_basicsize "PyTypeObject.tp_basicsize"), [`tp_itemsize`](#c.PyTypeObject.tp_itemsize "PyTypeObject.tp_itemsize") and [`tp_dictoffset`](#c.PyTypeObject.tp_dictoffset "PyTypeObject.tp_dictoffset") are taken from the type object, and `ob_size` is taken from the instance. The absolute value is taken because ints use the sign of `ob_size` to store the sign of the number. (There’s never a need to do this calculation yourself; it is done for you by `_PyObject_GetDictPtr()`.) **Inheritance:** This field is inherited by subtypes, but see the rules listed below. A subtype may override this offset; this means that the subtype instances store the dictionary at a difference offset than the base type. Since the dictionary is always found via [`tp_dictoffset`](#c.PyTypeObject.tp_dictoffset "PyTypeObject.tp_dictoffset"), this should not be a problem. When a type defined by a class statement has no [`__slots__`](../reference/datamodel#object.__slots__ "object.__slots__") declaration, and none of its base types has an instance variable dictionary, a dictionary slot is added to the instance layout and the [`tp_dictoffset`](#c.PyTypeObject.tp_dictoffset "PyTypeObject.tp_dictoffset") is set to that slot’s offset. When a type defined by a class statement has a [`__slots__`](../reference/datamodel#object.__slots__ "object.__slots__") declaration, the type inherits its [`tp_dictoffset`](#c.PyTypeObject.tp_dictoffset "PyTypeObject.tp_dictoffset") from its base type. (Adding a slot named [`__dict__`](../library/stdtypes#object.__dict__ "object.__dict__") to the [`__slots__`](../reference/datamodel#object.__slots__ "object.__slots__") declaration does not have the expected effect, it just causes confusion. Maybe this should be added as a feature just like `__weakref__` though.) **Default:** This slot has no default. For static types, if the field is `NULL` then no [`__dict__`](../library/stdtypes#object.__dict__ "object.__dict__") gets created for instances. `initproc PyTypeObject.tp_init` An optional pointer to an instance initialization function. This function corresponds to the [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") method of classes. Like [`__init__()`](../reference/datamodel#object.__init__ "object.__init__"), it is possible to create an instance without calling [`__init__()`](../reference/datamodel#object.__init__ "object.__init__"), and it is possible to reinitialize an instance by calling its [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") method again. The function signature is: ``` int tp_init(PyObject *self, PyObject *args, PyObject *kwds); ``` The self argument is the instance to be initialized; the *args* and *kwds* arguments represent positional and keyword arguments of the call to [`__init__()`](../reference/datamodel#object.__init__ "object.__init__"). The [`tp_init`](#c.PyTypeObject.tp_init "PyTypeObject.tp_init") function, if not `NULL`, is called when an instance is created normally by calling its type, after the type’s [`tp_new`](#c.PyTypeObject.tp_new "PyTypeObject.tp_new") function has returned an instance of the type. If the [`tp_new`](#c.PyTypeObject.tp_new "PyTypeObject.tp_new") function returns an instance of some other type that is not a subtype of the original type, no [`tp_init`](#c.PyTypeObject.tp_init "PyTypeObject.tp_init") function is called; if [`tp_new`](#c.PyTypeObject.tp_new "PyTypeObject.tp_new") returns an instance of a subtype of the original type, the subtype’s [`tp_init`](#c.PyTypeObject.tp_init "PyTypeObject.tp_init") is called. Returns `0` on success, `-1` and sets an exception on error. **Inheritance:** This field is inherited by subtypes. **Default:** For static types this field does not have a default. `allocfunc PyTypeObject.tp_alloc` An optional pointer to an instance allocation function. The function signature is: ``` PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems); ``` **Inheritance:** This field is inherited by static subtypes, but not by dynamic subtypes (subtypes created by a class statement). **Default:** For dynamic subtypes, this field is always set to [`PyType_GenericAlloc()`](type#c.PyType_GenericAlloc "PyType_GenericAlloc"), to force a standard heap allocation strategy. For static subtypes, `PyBaseObject_Type` uses [`PyType_GenericAlloc()`](type#c.PyType_GenericAlloc "PyType_GenericAlloc"). That is the recommended value for all statically defined types. `newfunc PyTypeObject.tp_new` An optional pointer to an instance creation function. The function signature is: ``` PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds); ``` The *subtype* argument is the type of the object being created; the *args* and *kwds* arguments represent positional and keyword arguments of the call to the type. Note that *subtype* doesn’t have to equal the type whose [`tp_new`](#c.PyTypeObject.tp_new "PyTypeObject.tp_new") function is called; it may be a subtype of that type (but not an unrelated type). The [`tp_new`](#c.PyTypeObject.tp_new "PyTypeObject.tp_new") function should call `subtype->tp_alloc(subtype, nitems)` to allocate space for the object, and then do only as much further initialization as is absolutely necessary. Initialization that can safely be ignored or repeated should be placed in the [`tp_init`](#c.PyTypeObject.tp_init "PyTypeObject.tp_init") handler. A good rule of thumb is that for immutable types, all initialization should take place in [`tp_new`](#c.PyTypeObject.tp_new "PyTypeObject.tp_new"), while for mutable types, most initialization should be deferred to [`tp_init`](#c.PyTypeObject.tp_init "PyTypeObject.tp_init"). **Inheritance:** This field is inherited by subtypes, except it is not inherited by static types whose [`tp_base`](#c.PyTypeObject.tp_base "PyTypeObject.tp_base") is `NULL` or `&PyBaseObject_Type`. **Default:** For static types this field has no default. This means if the slot is defined as `NULL`, the type cannot be called to create new instances; presumably there is some other way to create instances, like a factory function. `freefunc PyTypeObject.tp_free` An optional pointer to an instance deallocation function. Its signature is: ``` void tp_free(void *self); ``` An initializer that is compatible with this signature is [`PyObject_Free()`](memory#c.PyObject_Free "PyObject_Free"). **Inheritance:** This field is inherited by static subtypes, but not by dynamic subtypes (subtypes created by a class statement) **Default:** In dynamic subtypes, this field is set to a deallocator suitable to match [`PyType_GenericAlloc()`](type#c.PyType_GenericAlloc "PyType_GenericAlloc") and the value of the [`Py_TPFLAGS_HAVE_GC`](#Py_TPFLAGS_HAVE_GC "Py_TPFLAGS_HAVE_GC") flag bit. For static subtypes, `PyBaseObject_Type` uses PyObject\_Del. `inquiry PyTypeObject.tp_is_gc` An optional pointer to a function called by the garbage collector. The garbage collector needs to know whether a particular object is collectible or not. Normally, it is sufficient to look at the object’s type’s [`tp_flags`](#c.PyTypeObject.tp_flags "PyTypeObject.tp_flags") field, and check the [`Py_TPFLAGS_HAVE_GC`](#Py_TPFLAGS_HAVE_GC "Py_TPFLAGS_HAVE_GC") flag bit. But some types have a mixture of statically and dynamically allocated instances, and the statically allocated instances are not collectible. Such types should define this function; it should return `1` for a collectible instance, and `0` for a non-collectible instance. The signature is: ``` int tp_is_gc(PyObject *self); ``` (The only example of this are types themselves. The metatype, [`PyType_Type`](type#c.PyType_Type "PyType_Type"), defines this function to distinguish between statically and dynamically allocated types.) **Inheritance:** This field is inherited by subtypes. **Default:** This slot has no default. If this field is `NULL`, [`Py_TPFLAGS_HAVE_GC`](#Py_TPFLAGS_HAVE_GC "Py_TPFLAGS_HAVE_GC") is used as the functional equivalent. `PyObject* PyTypeObject.tp_bases` Tuple of base types. This is set for types created by a class statement. It should be `NULL` for statically defined types. **Inheritance:** This field is not inherited. `PyObject* PyTypeObject.tp_mro` Tuple containing the expanded set of base types, starting with the type itself and ending with [`object`](../library/functions#object "object"), in Method Resolution Order. **Inheritance:** This field is not inherited; it is calculated fresh by [`PyType_Ready()`](type#c.PyType_Ready "PyType_Ready"). `PyObject* PyTypeObject.tp_cache` Unused. Internal use only. **Inheritance:** This field is not inherited. `PyObject* PyTypeObject.tp_subclasses` List of weak references to subclasses. Internal use only. **Inheritance:** This field is not inherited. `PyObject* PyTypeObject.tp_weaklist` Weak reference list head, for weak references to this type object. Not inherited. Internal use only. **Inheritance:** This field is not inherited. `destructor PyTypeObject.tp_del` This field is deprecated. Use [`tp_finalize`](#c.PyTypeObject.tp_finalize "PyTypeObject.tp_finalize") instead. `unsigned int PyTypeObject.tp_version_tag` Used to index into the method cache. Internal use only. **Inheritance:** This field is not inherited. `destructor PyTypeObject.tp_finalize` An optional pointer to an instance finalization function. Its signature is: ``` void tp_finalize(PyObject *self); ``` If [`tp_finalize`](#c.PyTypeObject.tp_finalize "PyTypeObject.tp_finalize") is set, the interpreter calls it once when finalizing an instance. It is called either from the garbage collector (if the instance is part of an isolated reference cycle) or just before the object is deallocated. Either way, it is guaranteed to be called before attempting to break reference cycles, ensuring that it finds the object in a sane state. [`tp_finalize`](#c.PyTypeObject.tp_finalize "PyTypeObject.tp_finalize") should not mutate the current exception status; therefore, a recommended way to write a non-trivial finalizer is: ``` static void local_finalize(PyObject *self) { PyObject *error_type, *error_value, *error_traceback; /* Save the current exception, if any. */ PyErr_Fetch(&error_type, &error_value, &error_traceback); /* ... */ /* Restore the saved exception. */ PyErr_Restore(error_type, error_value, error_traceback); } ``` For this field to be taken into account (even through inheritance), you must also set the [`Py_TPFLAGS_HAVE_FINALIZE`](#Py_TPFLAGS_HAVE_FINALIZE "Py_TPFLAGS_HAVE_FINALIZE") flags bit. Also, note that, in a garbage collected Python, [`tp_dealloc`](#c.PyTypeObject.tp_dealloc "PyTypeObject.tp_dealloc") may be called from any Python thread, not just the thread which created the object (if the object becomes part of a refcount cycle, that cycle might be collected by a garbage collection on any thread). This is not a problem for Python API calls, since the thread on which tp\_dealloc is called will own the Global Interpreter Lock (GIL). However, if the object being destroyed in turn destroys objects from some other C or C++ library, care should be taken to ensure that destroying those objects on the thread which called tp\_dealloc will not violate any assumptions of the library. **Inheritance:** This field is inherited by subtypes. New in version 3.4. See also “Safe object finalization” ([**PEP 442**](https://www.python.org/dev/peps/pep-0442)) `vectorcallfunc PyTypeObject.tp_vectorcall` Vectorcall function to use for calls of this type object. In other words, it is used to implement [vectorcall](call#vectorcall) for `type.__call__`. If `tp_vectorcall` is `NULL`, the default call implementation using [`__new__`](../reference/datamodel#object.__new__ "object.__new__") and [`__init__`](../reference/datamodel#object.__init__ "object.__init__") is used. **Inheritance:** This field is never inherited. New in version 3.9: (the field exists since 3.8 but it’s only used since 3.9) Heap Types ---------- Traditionally, types defined in C code are *static*, that is, a static [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject") structure is defined directly in code and initialized using [`PyType_Ready()`](type#c.PyType_Ready "PyType_Ready"). This results in types that are limited relative to types defined in Python: * Static types are limited to one base, i.e. they cannot use multiple inheritance. * Static type objects (but not necessarily their instances) are immutable. It is not possible to add or modify the type object’s attributes from Python. * Static type objects are shared across [sub-interpreters](init#sub-interpreter-support), so they should not include any subinterpreter-specific state. Also, since [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject") is not part of the [stable ABI](stable#stable), any extension modules using static types must be compiled for a specific Python minor version. An alternative to static types is *heap-allocated types*, or *heap types* for short, which correspond closely to classes created by Python’s `class` statement. This is done by filling a [`PyType_Spec`](type#c.PyType_Spec "PyType_Spec") structure and calling [`PyType_FromSpecWithBases()`](type#c.PyType_FromSpecWithBases "PyType_FromSpecWithBases").
programming_docs
python Iterator Objects Iterator Objects ================ Python provides two general-purpose iterator objects. The first, a sequence iterator, works with an arbitrary sequence supporting the [`__getitem__()`](../reference/datamodel#object.__getitem__ "object.__getitem__") method. The second works with a callable object and a sentinel value, calling the callable for each item in the sequence, and ending the iteration when the sentinel value is returned. `PyTypeObject PySeqIter_Type` Type object for iterator objects returned by [`PySeqIter_New()`](#c.PySeqIter_New "PySeqIter_New") and the one-argument form of the [`iter()`](../library/functions#iter "iter") built-in function for built-in sequence types. `int PySeqIter_Check(op)` Return true if the type of *op* is [`PySeqIter_Type`](#c.PySeqIter_Type "PySeqIter_Type"). This function always succeeds. `PyObject* PySeqIter_New(PyObject *seq)` *Return value: New reference.*Return an iterator that works with a general sequence object, *seq*. The iteration ends when the sequence raises [`IndexError`](../library/exceptions#IndexError "IndexError") for the subscripting operation. `PyTypeObject PyCallIter_Type` Type object for iterator objects returned by [`PyCallIter_New()`](#c.PyCallIter_New "PyCallIter_New") and the two-argument form of the [`iter()`](../library/functions#iter "iter") built-in function. `int PyCallIter_Check(op)` Return true if the type of *op* is [`PyCallIter_Type`](#c.PyCallIter_Type "PyCallIter_Type"). This function always succeeds. `PyObject* PyCallIter_New(PyObject *callable, PyObject *sentinel)` *Return value: New reference.*Return a new iterator. The first parameter, *callable*, can be any Python callable object that can be called with no parameters; each call to it should return the next item in the iteration. When *callable* returns a value equal to *sentinel*, the iteration will be terminated. python The Very High Level Layer The Very High Level Layer ========================= The functions in this chapter will let you execute Python source code given in a file or a buffer, but they will not let you interact in a more detailed way with the interpreter. Several of these functions accept a start symbol from the grammar as a parameter. The available start symbols are `Py_eval_input`, `Py_file_input`, and `Py_single_input`. These are described following the functions which accept them as parameters. Note also that several of these functions take `FILE*` parameters. One particular issue which needs to be handled carefully is that the `FILE` structure for different C libraries can be different and incompatible. Under Windows (at least), it is possible for dynamically linked extensions to actually use different libraries, so care should be taken that `FILE*` parameters are only passed to these functions if it is certain that they were created by the same library that the Python runtime is using. `int Py_Main(int argc, wchar_t **argv)` The main program for the standard interpreter. This is made available for programs which embed Python. The *argc* and *argv* parameters should be prepared exactly as those which are passed to a C program’s `main()` function (converted to wchar\_t according to the user’s locale). It is important to note that the argument list may be modified (but the contents of the strings pointed to by the argument list are not). The return value will be `0` if the interpreter exits normally (i.e., without an exception), `1` if the interpreter exits due to an exception, or `2` if the parameter list does not represent a valid Python command line. Note that if an otherwise unhandled [`SystemExit`](../library/exceptions#SystemExit "SystemExit") is raised, this function will not return `1`, but exit the process, as long as `Py_InspectFlag` is not set. `int Py_BytesMain(int argc, char **argv)` Similar to [`Py_Main()`](#c.Py_Main "Py_Main") but *argv* is an array of bytes strings. New in version 3.8. `int PyRun_AnyFile(FILE *fp, const char *filename)` This is a simplified interface to [`PyRun_AnyFileExFlags()`](#c.PyRun_AnyFileExFlags "PyRun_AnyFileExFlags") below, leaving *closeit* set to `0` and *flags* set to `NULL`. `int PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)` This is a simplified interface to [`PyRun_AnyFileExFlags()`](#c.PyRun_AnyFileExFlags "PyRun_AnyFileExFlags") below, leaving the *closeit* argument set to `0`. `int PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit)` This is a simplified interface to [`PyRun_AnyFileExFlags()`](#c.PyRun_AnyFileExFlags "PyRun_AnyFileExFlags") below, leaving the *flags* argument set to `NULL`. `int PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags)` If *fp* refers to a file associated with an interactive device (console or terminal input or Unix pseudo-terminal), return the value of [`PyRun_InteractiveLoop()`](#c.PyRun_InteractiveLoop "PyRun_InteractiveLoop"), otherwise return the result of [`PyRun_SimpleFile()`](#c.PyRun_SimpleFile "PyRun_SimpleFile"). *filename* is decoded from the filesystem encoding ([`sys.getfilesystemencoding()`](../library/sys#sys.getfilesystemencoding "sys.getfilesystemencoding")). If *filename* is `NULL`, this function uses `"???"` as the filename. If *closeit* is true, the file is closed before `PyRun_SimpleFileExFlags()` returns. `int PyRun_SimpleString(const char *command)` This is a simplified interface to [`PyRun_SimpleStringFlags()`](#c.PyRun_SimpleStringFlags "PyRun_SimpleStringFlags") below, leaving the [`PyCompilerFlags`](#c.PyCompilerFlags "PyCompilerFlags")\* argument set to `NULL`. `int PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)` Executes the Python source code from *command* in the [`__main__`](../library/__main__#module-__main__ "__main__: The environment where the top-level script is run.") module according to the *flags* argument. If [`__main__`](../library/__main__#module-__main__ "__main__: The environment where the top-level script is run.") does not already exist, it is created. Returns `0` on success or `-1` if an exception was raised. If there was an error, there is no way to get the exception information. For the meaning of *flags*, see below. Note that if an otherwise unhandled [`SystemExit`](../library/exceptions#SystemExit "SystemExit") is raised, this function will not return `-1`, but exit the process, as long as `Py_InspectFlag` is not set. `int PyRun_SimpleFile(FILE *fp, const char *filename)` This is a simplified interface to [`PyRun_SimpleFileExFlags()`](#c.PyRun_SimpleFileExFlags "PyRun_SimpleFileExFlags") below, leaving *closeit* set to `0` and *flags* set to `NULL`. `int PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit)` This is a simplified interface to [`PyRun_SimpleFileExFlags()`](#c.PyRun_SimpleFileExFlags "PyRun_SimpleFileExFlags") below, leaving *flags* set to `NULL`. `int PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags)` Similar to [`PyRun_SimpleStringFlags()`](#c.PyRun_SimpleStringFlags "PyRun_SimpleStringFlags"), but the Python source code is read from *fp* instead of an in-memory string. *filename* should be the name of the file, it is decoded from the filesystem encoding ([`sys.getfilesystemencoding()`](../library/sys#sys.getfilesystemencoding "sys.getfilesystemencoding")). If *closeit* is true, the file is closed before PyRun\_SimpleFileExFlags returns. Note On Windows, *fp* should be opened as binary mode (e.g. `fopen(filename, "rb")`). Otherwise, Python may not handle script file with LF line ending correctly. `int PyRun_InteractiveOne(FILE *fp, const char *filename)` This is a simplified interface to [`PyRun_InteractiveOneFlags()`](#c.PyRun_InteractiveOneFlags "PyRun_InteractiveOneFlags") below, leaving *flags* set to `NULL`. `int PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)` Read and execute a single statement from a file associated with an interactive device according to the *flags* argument. The user will be prompted using `sys.ps1` and `sys.ps2`. *filename* is decoded from the filesystem encoding ([`sys.getfilesystemencoding()`](../library/sys#sys.getfilesystemencoding "sys.getfilesystemencoding")). Returns `0` when the input was executed successfully, `-1` if there was an exception, or an error code from the `errcode.h` include file distributed as part of Python if there was a parse error. (Note that `errcode.h` is not included by `Python.h`, so must be included specifically if needed.) `int PyRun_InteractiveLoop(FILE *fp, const char *filename)` This is a simplified interface to [`PyRun_InteractiveLoopFlags()`](#c.PyRun_InteractiveLoopFlags "PyRun_InteractiveLoopFlags") below, leaving *flags* set to `NULL`. `int PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)` Read and execute statements from a file associated with an interactive device until EOF is reached. The user will be prompted using `sys.ps1` and `sys.ps2`. *filename* is decoded from the filesystem encoding ([`sys.getfilesystemencoding()`](../library/sys#sys.getfilesystemencoding "sys.getfilesystemencoding")). Returns `0` at EOF or a negative number upon failure. `int (*PyOS_InputHook)(void)` Can be set to point to a function with the prototype `int func(void)`. The function will be called when Python’s interpreter prompt is about to become idle and wait for user input from the terminal. The return value is ignored. Overriding this hook can be used to integrate the interpreter’s prompt with other event loops, as done in the `Modules/_tkinter.c` in the Python source code. `char* (*PyOS_ReadlineFunctionPointer)(FILE *, FILE *, const char *)` Can be set to point to a function with the prototype `char *func(FILE *stdin, FILE *stdout, char *prompt)`, overriding the default function used to read a single line of input at the interpreter’s prompt. The function is expected to output the string *prompt* if it’s not `NULL`, and then read a line of input from the provided standard input file, returning the resulting string. For example, The [`readline`](../library/readline#module-readline "readline: GNU readline support for Python. (Unix)") module sets this hook to provide line-editing and tab-completion features. The result must be a string allocated by [`PyMem_RawMalloc()`](memory#c.PyMem_RawMalloc "PyMem_RawMalloc") or [`PyMem_RawRealloc()`](memory#c.PyMem_RawRealloc "PyMem_RawRealloc"), or `NULL` if an error occurred. Changed in version 3.4: The result must be allocated by [`PyMem_RawMalloc()`](memory#c.PyMem_RawMalloc "PyMem_RawMalloc") or [`PyMem_RawRealloc()`](memory#c.PyMem_RawRealloc "PyMem_RawRealloc"), instead of being allocated by [`PyMem_Malloc()`](memory#c.PyMem_Malloc "PyMem_Malloc") or [`PyMem_Realloc()`](memory#c.PyMem_Realloc "PyMem_Realloc"). `struct _node* PyParser_SimpleParseString(const char *str, int start)` This is a simplified interface to [`PyParser_SimpleParseStringFlagsFilename()`](#c.PyParser_SimpleParseStringFlagsFilename "PyParser_SimpleParseStringFlagsFilename") below, leaving *filename* set to `NULL` and *flags* set to `0`. Deprecated since version 3.9, will be removed in version 3.10. `struct _node* PyParser_SimpleParseStringFlags(const char *str, int start, int flags)` This is a simplified interface to [`PyParser_SimpleParseStringFlagsFilename()`](#c.PyParser_SimpleParseStringFlagsFilename "PyParser_SimpleParseStringFlagsFilename") below, leaving *filename* set to `NULL`. Deprecated since version 3.9, will be removed in version 3.10. `struct _node* PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename, int start, int flags)` Parse Python source code from *str* using the start token *start* according to the *flags* argument. The result can be used to create a code object which can be evaluated efficiently. This is useful if a code fragment must be evaluated many times. *filename* is decoded from the filesystem encoding ([`sys.getfilesystemencoding()`](../library/sys#sys.getfilesystemencoding "sys.getfilesystemencoding")). Deprecated since version 3.9, will be removed in version 3.10. `struct _node* PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)` This is a simplified interface to [`PyParser_SimpleParseFileFlags()`](#c.PyParser_SimpleParseFileFlags "PyParser_SimpleParseFileFlags") below, leaving *flags* set to `0`. Deprecated since version 3.9, will be removed in version 3.10. `struct _node* PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)` Similar to [`PyParser_SimpleParseStringFlagsFilename()`](#c.PyParser_SimpleParseStringFlagsFilename "PyParser_SimpleParseStringFlagsFilename"), but the Python source code is read from *fp* instead of an in-memory string. Deprecated since version 3.9, will be removed in version 3.10. `PyObject* PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)` *Return value: New reference.*This is a simplified interface to [`PyRun_StringFlags()`](#c.PyRun_StringFlags "PyRun_StringFlags") below, leaving *flags* set to `NULL`. `PyObject* PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags)` *Return value: New reference.*Execute Python source code from *str* in the context specified by the objects *globals* and *locals* with the compiler flags specified by *flags*. *globals* must be a dictionary; *locals* can be any object that implements the mapping protocol. The parameter *start* specifies the start token that should be used to parse the source code. Returns the result of executing the code as a Python object, or `NULL` if an exception was raised. `PyObject* PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals)` *Return value: New reference.*This is a simplified interface to [`PyRun_FileExFlags()`](#c.PyRun_FileExFlags "PyRun_FileExFlags") below, leaving *closeit* set to `0` and *flags* set to `NULL`. `PyObject* PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int closeit)` *Return value: New reference.*This is a simplified interface to [`PyRun_FileExFlags()`](#c.PyRun_FileExFlags "PyRun_FileExFlags") below, leaving *flags* set to `NULL`. `PyObject* PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags)` *Return value: New reference.*This is a simplified interface to [`PyRun_FileExFlags()`](#c.PyRun_FileExFlags "PyRun_FileExFlags") below, leaving *closeit* set to `0`. `PyObject* PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int closeit, PyCompilerFlags *flags)` *Return value: New reference.*Similar to [`PyRun_StringFlags()`](#c.PyRun_StringFlags "PyRun_StringFlags"), but the Python source code is read from *fp* instead of an in-memory string. *filename* should be the name of the file, it is decoded from the filesystem encoding ([`sys.getfilesystemencoding()`](../library/sys#sys.getfilesystemencoding "sys.getfilesystemencoding")). If *closeit* is true, the file is closed before [`PyRun_FileExFlags()`](#c.PyRun_FileExFlags "PyRun_FileExFlags") returns. `PyObject* Py_CompileString(const char *str, const char *filename, int start)` *Return value: New reference.*This is a simplified interface to [`Py_CompileStringFlags()`](#c.Py_CompileStringFlags "Py_CompileStringFlags") below, leaving *flags* set to `NULL`. `PyObject* Py_CompileStringFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags)` *Return value: New reference.*This is a simplified interface to [`Py_CompileStringExFlags()`](#c.Py_CompileStringExFlags "Py_CompileStringExFlags") below, with *optimize* set to `-1`. `PyObject* Py_CompileStringObject(const char *str, PyObject *filename, int start, PyCompilerFlags *flags, int optimize)` *Return value: New reference.*Parse and compile the Python source code in *str*, returning the resulting code object. The start token is given by *start*; this can be used to constrain the code which can be compiled and should be `Py_eval_input`, `Py_file_input`, or `Py_single_input`. The filename specified by *filename* is used to construct the code object and may appear in tracebacks or [`SyntaxError`](../library/exceptions#SyntaxError "SyntaxError") exception messages. This returns `NULL` if the code cannot be parsed or compiled. The integer *optimize* specifies the optimization level of the compiler; a value of `-1` selects the optimization level of the interpreter as given by [`-O`](../using/cmdline#cmdoption-o) options. Explicit levels are `0` (no optimization; `__debug__` is true), `1` (asserts are removed, `__debug__` is false) or `2` (docstrings are removed too). New in version 3.4. `PyObject* Py_CompileStringExFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags, int optimize)` *Return value: New reference.*Like [`Py_CompileStringObject()`](#c.Py_CompileStringObject "Py_CompileStringObject"), but *filename* is a byte string decoded from the filesystem encoding ([`os.fsdecode()`](../library/os#os.fsdecode "os.fsdecode")). New in version 3.2. `PyObject* PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)` *Return value: New reference.*This is a simplified interface to [`PyEval_EvalCodeEx()`](#c.PyEval_EvalCodeEx "PyEval_EvalCodeEx"), with just the code object, and global and local variables. The other arguments are set to `NULL`. `PyObject* PyEval_EvalCodeEx(PyObject *co, PyObject *globals, PyObject *locals, PyObject *const *args, int argcount, PyObject *const *kws, int kwcount, PyObject *const *defs, int defcount, PyObject *kwdefs, PyObject *closure)` *Return value: New reference.*Evaluate a precompiled code object, given a particular environment for its evaluation. This environment consists of a dictionary of global variables, a mapping object of local variables, arrays of arguments, keywords and defaults, a dictionary of default values for [keyword-only](../glossary#keyword-only-parameter) arguments and a closure tuple of cells. `PyFrameObject` The C structure of the objects used to describe frame objects. The fields of this type are subject to change at any time. `PyObject* PyEval_EvalFrame(PyFrameObject *f)` *Return value: New reference.*Evaluate an execution frame. This is a simplified interface to [`PyEval_EvalFrameEx()`](#c.PyEval_EvalFrameEx "PyEval_EvalFrameEx"), for backward compatibility. `PyObject* PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)` *Return value: New reference.*This is the main, unvarnished function of Python interpretation. The code object associated with the execution frame *f* is executed, interpreting bytecode and executing calls as needed. The additional *throwflag* parameter can mostly be ignored - if true, then it causes an exception to immediately be thrown; this is used for the [`throw()`](../reference/expressions#generator.throw "generator.throw") methods of generator objects. Changed in version 3.4: This function now includes a debug assertion to help ensure that it does not silently discard an active exception. `int PyEval_MergeCompilerFlags(PyCompilerFlags *cf)` This function changes the flags of the current evaluation frame, and returns true on success, false on failure. `int Py_eval_input` The start symbol from the Python grammar for isolated expressions; for use with [`Py_CompileString()`](#c.Py_CompileString "Py_CompileString"). `int Py_file_input` The start symbol from the Python grammar for sequences of statements as read from a file or other source; for use with [`Py_CompileString()`](#c.Py_CompileString "Py_CompileString"). This is the symbol to use when compiling arbitrarily long Python source code. `int Py_single_input` The start symbol from the Python grammar for a single statement; for use with [`Py_CompileString()`](#c.Py_CompileString "Py_CompileString"). This is the symbol used for the interactive interpreter loop. `struct PyCompilerFlags` This is the structure used to hold compiler flags. In cases where code is only being compiled, it is passed as `int flags`, and in cases where code is being executed, it is passed as `PyCompilerFlags *flags`. In this case, `from __future__ import` can modify *flags*. Whenever `PyCompilerFlags *flags` is `NULL`, `cf_flags` is treated as equal to `0`, and any modification due to `from __future__ import` is discarded. `int cf_flags` Compiler flags. `int cf_feature_version` *cf\_feature\_version* is the minor Python version. It should be initialized to `PY_MINOR_VERSION`. The field is ignored by default, it is used if and only if `PyCF_ONLY_AST` flag is set in *cf\_flags*. Changed in version 3.8: Added *cf\_feature\_version* field. `int CO_FUTURE_DIVISION` This bit can be set in *flags* to cause division operator `/` to be interpreted as “true division” according to [**PEP 238**](https://www.python.org/dev/peps/pep-0238).
programming_docs
python File Objects File Objects ============ These APIs are a minimal emulation of the Python 2 C API for built-in file objects, which used to rely on the buffered I/O (`FILE*`) support from the C standard library. In Python 3, files and streams use the new [`io`](../library/io#module-io "io: Core tools for working with streams.") module, which defines several layers over the low-level unbuffered I/O of the operating system. The functions described below are convenience C wrappers over these new APIs, and meant mostly for internal error reporting in the interpreter; third-party code is advised to access the [`io`](../library/io#module-io "io: Core tools for working with streams.") APIs instead. `PyObject* PyFile_FromFd(int fd, const char *name, const char *mode, int buffering, const char *encoding, const char *errors, const char *newline, int closefd)` *Return value: New reference.*Create a Python file object from the file descriptor of an already opened file *fd*. The arguments *name*, *encoding*, *errors* and *newline* can be `NULL` to use the defaults; *buffering* can be *-1* to use the default. *name* is ignored and kept for backward compatibility. Return `NULL` on failure. For a more comprehensive description of the arguments, please refer to the [`io.open()`](../library/io#io.open "io.open") function documentation. Warning Since Python streams have their own buffering layer, mixing them with OS-level file descriptors can produce various issues (such as unexpected ordering of data). Changed in version 3.2: Ignore *name* attribute. `int PyObject_AsFileDescriptor(PyObject *p)` Return the file descriptor associated with *p* as an `int`. If the object is an integer, its value is returned. If not, the object’s [`fileno()`](../library/io#io.IOBase.fileno "io.IOBase.fileno") method is called if it exists; the method must return an integer, which is returned as the file descriptor value. Sets an exception and returns `-1` on failure. `PyObject* PyFile_GetLine(PyObject *p, int n)` *Return value: New reference.*Equivalent to `p.readline([n])`, this function reads one line from the object *p*. *p* may be a file object or any object with a [`readline()`](../library/io#io.IOBase.readline "io.IOBase.readline") method. If *n* is `0`, exactly one line is read, regardless of the length of the line. If *n* is greater than `0`, no more than *n* bytes will be read from the file; a partial line can be returned. In both cases, an empty string is returned if the end of the file is reached immediately. If *n* is less than `0`, however, one line is read regardless of length, but [`EOFError`](../library/exceptions#EOFError "EOFError") is raised if the end of the file is reached immediately. `int PyFile_SetOpenCodeHook(Py_OpenCodeHookFunction handler)` Overrides the normal behavior of [`io.open_code()`](../library/io#io.open_code "io.open_code") to pass its parameter through the provided handler. The handler is a function of type `PyObject *(*)(PyObject *path, void *userData)`, where *path* is guaranteed to be [`PyUnicodeObject`](unicode#c.PyUnicodeObject "PyUnicodeObject"). The *userData* pointer is passed into the hook function. Since hook functions may be called from different runtimes, this pointer should not refer directly to Python state. As this hook is intentionally used during import, avoid importing new modules during its execution unless they are known to be frozen or available in `sys.modules`. Once a hook has been set, it cannot be removed or replaced, and later calls to [`PyFile_SetOpenCodeHook()`](#c.PyFile_SetOpenCodeHook "PyFile_SetOpenCodeHook") will fail. On failure, the function returns -1 and sets an exception if the interpreter has been initialized. This function is safe to call before [`Py_Initialize()`](init#c.Py_Initialize "Py_Initialize"). Raises an [auditing event](../library/sys#auditing) `setopencodehook` with no arguments. New in version 3.8. `int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags)` Write object *obj* to file object *p*. The only supported flag for *flags* is `Py_PRINT_RAW`; if given, the [`str()`](../library/stdtypes#str "str") of the object is written instead of the [`repr()`](../library/functions#repr "repr"). Return `0` on success or `-1` on failure; the appropriate exception will be set. `int PyFile_WriteString(const char *s, PyObject *p)` Write string *s* to file object *p*. Return `0` on success or `-1` on failure; the appropriate exception will be set. python Common Object Structures Common Object Structures ======================== There are a large number of structures which are used in the definition of object types for Python. This section describes these structures and how they are used. Base object types and macros ---------------------------- All Python objects ultimately share a small number of fields at the beginning of the object’s representation in memory. These are represented by the [`PyObject`](#c.PyObject "PyObject") and [`PyVarObject`](#c.PyVarObject "PyVarObject") types, which are defined, in turn, by the expansions of some macros also used, whether directly or indirectly, in the definition of all other Python objects. `PyObject` All object types are extensions of this type. This is a type which contains the information Python needs to treat a pointer to an object as an object. In a normal “release” build, it contains only the object’s reference count and a pointer to the corresponding type object. Nothing is actually declared to be a [`PyObject`](#c.PyObject "PyObject"), but every pointer to a Python object can be cast to a [`PyObject*`](#c.PyObject "PyObject"). Access to the members must be done by using the macros [`Py_REFCNT`](#c.Py_REFCNT "Py_REFCNT") and [`Py_TYPE`](#c.Py_TYPE "Py_TYPE"). `PyVarObject` This is an extension of [`PyObject`](#c.PyObject "PyObject") that adds the `ob_size` field. This is only used for objects that have some notion of *length*. This type does not often appear in the Python/C API. Access to the members must be done by using the macros [`Py_REFCNT`](#c.Py_REFCNT "Py_REFCNT"), [`Py_TYPE`](#c.Py_TYPE "Py_TYPE"), and [`Py_SIZE`](#c.Py_SIZE "Py_SIZE"). `PyObject_HEAD` This is a macro used when declaring new types which represent objects without a varying length. The PyObject\_HEAD macro expands to: ``` PyObject ob_base; ``` See documentation of [`PyObject`](#c.PyObject "PyObject") above. `PyObject_VAR_HEAD` This is a macro used when declaring new types which represent objects with a length that varies from instance to instance. The PyObject\_VAR\_HEAD macro expands to: ``` PyVarObject ob_base; ``` See documentation of [`PyVarObject`](#c.PyVarObject "PyVarObject") above. `Py_TYPE(o)` This macro is used to access the `ob_type` member of a Python object. It expands to: ``` (((PyObject*)(o))->ob_type) ``` `int Py_IS_TYPE(PyObject *o, PyTypeObject *type)` Return non-zero if the object *o* type is *type*. Return zero otherwise. Equivalent to: `Py_TYPE(o) == type`. New in version 3.9. `void Py_SET_TYPE(PyObject *o, PyTypeObject *type)` Set the object *o* type to *type*. New in version 3.9. `Py_REFCNT(o)` This macro is used to access the `ob_refcnt` member of a Python object. It expands to: ``` (((PyObject*)(o))->ob_refcnt) ``` `void Py_SET_REFCNT(PyObject *o, Py_ssize_t refcnt)` Set the object *o* reference counter to *refcnt*. New in version 3.9. `Py_SIZE(o)` This macro is used to access the `ob_size` member of a Python object. It expands to: ``` (((PyVarObject*)(o))->ob_size) ``` `void Py_SET_SIZE(PyVarObject *o, Py_ssize_t size)` Set the object *o* size to *size*. New in version 3.9. `PyObject_HEAD_INIT(type)` This is a macro which expands to initialization values for a new [`PyObject`](#c.PyObject "PyObject") type. This macro expands to: ``` _PyObject_EXTRA_INIT 1, type, ``` `PyVarObject_HEAD_INIT(type, size)` This is a macro which expands to initialization values for a new [`PyVarObject`](#c.PyVarObject "PyVarObject") type, including the `ob_size` field. This macro expands to: ``` _PyObject_EXTRA_INIT 1, type, size, ``` Implementing functions and methods ---------------------------------- `PyCFunction` Type of the functions used to implement most Python callables in C. Functions of this type take two [`PyObject*`](#c.PyObject "PyObject") parameters and return one such value. If the return value is `NULL`, an exception shall have been set. If not `NULL`, the return value is interpreted as the return value of the function as exposed in Python. The function must return a new reference. The function signature is: ``` PyObject *PyCFunction(PyObject *self, PyObject *args); ``` `PyCFunctionWithKeywords` Type of the functions used to implement Python callables in C with signature `METH_VARARGS | METH_KEYWORDS`. The function signature is: ``` PyObject *PyCFunctionWithKeywords(PyObject *self, PyObject *args, PyObject *kwargs); ``` `_PyCFunctionFast` Type of the functions used to implement Python callables in C with signature [`METH_FASTCALL`](#METH_FASTCALL "METH_FASTCALL"). The function signature is: ``` PyObject *_PyCFunctionFast(PyObject *self, PyObject *const *args, Py_ssize_t nargs); ``` `_PyCFunctionFastWithKeywords` Type of the functions used to implement Python callables in C with signature `METH_FASTCALL | METH_KEYWORDS`. The function signature is: ``` PyObject *_PyCFunctionFastWithKeywords(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames); ``` `PyCMethod` Type of the functions used to implement Python callables in C with signature `METH_METHOD | METH_FASTCALL | METH_KEYWORDS`. The function signature is: ``` PyObject *PyCMethod(PyObject *self, PyTypeObject *defining_class, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) ``` New in version 3.9. `PyMethodDef` Structure used to describe a method of an extension type. This structure has four fields: | Field | C Type | Meaning | | --- | --- | --- | | `ml_name` | const char \* | name of the method | | `ml_meth` | PyCFunction | pointer to the C implementation | | `ml_flags` | int | flag bits indicating how the call should be constructed | | `ml_doc` | const char \* | points to the contents of the docstring | The `ml_meth` is a C function pointer. The functions may be of different types, but they always return [`PyObject*`](#c.PyObject "PyObject"). If the function is not of the [`PyCFunction`](#c.PyCFunction "PyCFunction"), the compiler will require a cast in the method table. Even though [`PyCFunction`](#c.PyCFunction "PyCFunction") defines the first parameter as [`PyObject*`](#c.PyObject "PyObject"), it is common that the method implementation uses the specific C type of the *self* object. The `ml_flags` field is a bitfield which can include the following flags. The individual flags indicate either a calling convention or a binding convention. There are these calling conventions: `METH_VARARGS` This is the typical calling convention, where the methods have the type [`PyCFunction`](#c.PyCFunction "PyCFunction"). The function expects two [`PyObject*`](#c.PyObject "PyObject") values. The first one is the *self* object for methods; for module functions, it is the module object. The second parameter (often called *args*) is a tuple object representing all arguments. This parameter is typically processed using [`PyArg_ParseTuple()`](arg#c.PyArg_ParseTuple "PyArg_ParseTuple") or [`PyArg_UnpackTuple()`](arg#c.PyArg_UnpackTuple "PyArg_UnpackTuple"). `METH_VARARGS | METH_KEYWORDS` Methods with these flags must be of type [`PyCFunctionWithKeywords`](#c.PyCFunctionWithKeywords "PyCFunctionWithKeywords"). The function expects three parameters: *self*, *args*, *kwargs* where *kwargs* is a dictionary of all the keyword arguments or possibly `NULL` if there are no keyword arguments. The parameters are typically processed using [`PyArg_ParseTupleAndKeywords()`](arg#c.PyArg_ParseTupleAndKeywords "PyArg_ParseTupleAndKeywords"). `METH_FASTCALL` Fast calling convention supporting only positional arguments. The methods have the type [`_PyCFunctionFast`](#c._PyCFunctionFast "_PyCFunctionFast"). The first parameter is *self*, the second parameter is a C array of [`PyObject*`](#c.PyObject "PyObject") values indicating the arguments and the third parameter is the number of arguments (the length of the array). This is not part of the [limited API](stable#stable). New in version 3.7. `METH_FASTCALL | METH_KEYWORDS` Extension of [`METH_FASTCALL`](#METH_FASTCALL "METH_FASTCALL") supporting also keyword arguments, with methods of type [`_PyCFunctionFastWithKeywords`](#c._PyCFunctionFastWithKeywords "_PyCFunctionFastWithKeywords"). Keyword arguments are passed the same way as in the [vectorcall protocol](call#vectorcall): there is an additional fourth [`PyObject*`](#c.PyObject "PyObject") parameter which is a tuple representing the names of the keyword arguments (which are guaranteed to be strings) or possibly `NULL` if there are no keywords. The values of the keyword arguments are stored in the *args* array, after the positional arguments. This is not part of the [limited API](stable#stable). New in version 3.7. `METH_METHOD | METH_FASTCALL | METH_KEYWORDS` Extension of `METH_FASTCALL | METH_KEYWORDS` supporting the *defining class*, that is, the class that contains the method in question. The defining class might be a superclass of `Py_TYPE(self)`. The method needs to be of type [`PyCMethod`](#c.PyCMethod "PyCMethod"), the same as for `METH_FASTCALL | METH_KEYWORDS` with `defining_class` argument added after `self`. New in version 3.9. `METH_NOARGS` Methods without parameters don’t need to check whether arguments are given if they are listed with the [`METH_NOARGS`](#METH_NOARGS "METH_NOARGS") flag. They need to be of type [`PyCFunction`](#c.PyCFunction "PyCFunction"). The first parameter is typically named *self* and will hold a reference to the module or object instance. In all cases the second parameter will be `NULL`. `METH_O` Methods with a single object argument can be listed with the [`METH_O`](#METH_O "METH_O") flag, instead of invoking [`PyArg_ParseTuple()`](arg#c.PyArg_ParseTuple "PyArg_ParseTuple") with a `"O"` argument. They have the type [`PyCFunction`](#c.PyCFunction "PyCFunction"), with the *self* parameter, and a [`PyObject*`](#c.PyObject "PyObject") parameter representing the single argument. These two constants are not used to indicate the calling convention but the binding when use with methods of classes. These may not be used for functions defined for modules. At most one of these flags may be set for any given method. `METH_CLASS` The method will be passed the type object as the first parameter rather than an instance of the type. This is used to create *class methods*, similar to what is created when using the [`classmethod()`](../library/functions#classmethod "classmethod") built-in function. `METH_STATIC` The method will be passed `NULL` as the first parameter rather than an instance of the type. This is used to create *static methods*, similar to what is created when using the [`staticmethod()`](../library/functions#staticmethod "staticmethod") built-in function. One other constant controls whether a method is loaded in place of another definition with the same method name. `METH_COEXIST` The method will be loaded in place of existing definitions. Without *METH\_COEXIST*, the default is to skip repeated definitions. Since slot wrappers are loaded before the method table, the existence of a *sq\_contains* slot, for example, would generate a wrapped method named [`__contains__()`](../reference/datamodel#object.__contains__ "object.__contains__") and preclude the loading of a corresponding PyCFunction with the same name. With the flag defined, the PyCFunction will be loaded in place of the wrapper object and will co-exist with the slot. This is helpful because calls to PyCFunctions are optimized more than wrapper object calls. Accessing attributes of extension types --------------------------------------- `PyMemberDef` Structure which describes an attribute of a type which corresponds to a C struct member. Its fields are: | Field | C Type | Meaning | | --- | --- | --- | | `name` | const char \* | name of the member | | `type` | int | the type of the member in the C struct | | `offset` | Py\_ssize\_t | the offset in bytes that the member is located on the type’s object struct | | `flags` | int | flag bits indicating if the field should be read-only or writable | | `doc` | const char \* | points to the contents of the docstring | `type` can be one of many `T_` macros corresponding to various C types. When the member is accessed in Python, it will be converted to the equivalent Python type. | Macro name | C type | | --- | --- | | T\_SHORT | short | | T\_INT | int | | T\_LONG | long | | T\_FLOAT | float | | T\_DOUBLE | double | | T\_STRING | const char \* | | T\_OBJECT | PyObject \* | | T\_OBJECT\_EX | PyObject \* | | T\_CHAR | char | | T\_BYTE | char | | T\_UBYTE | unsigned char | | T\_UINT | unsigned int | | T\_USHORT | unsigned short | | T\_ULONG | unsigned long | | T\_BOOL | char | | T\_LONGLONG | long long | | T\_ULONGLONG | unsigned long long | | T\_PYSSIZET | Py\_ssize\_t | `T_OBJECT` and `T_OBJECT_EX` differ in that `T_OBJECT` returns `None` if the member is `NULL` and `T_OBJECT_EX` raises an [`AttributeError`](../library/exceptions#AttributeError "AttributeError"). Try to use `T_OBJECT_EX` over `T_OBJECT` because `T_OBJECT_EX` handles use of the [`del`](../reference/simple_stmts#del) statement on that attribute more correctly than `T_OBJECT`. `flags` can be `0` for write and read access or `READONLY` for read-only access. Using `T_STRING` for [`type`](../library/functions#type "type") implies `READONLY`. `T_STRING` data is interpreted as UTF-8. Only `T_OBJECT` and `T_OBJECT_EX` members can be deleted. (They are set to `NULL`). Heap allocated types (created using [`PyType_FromSpec()`](type#c.PyType_FromSpec "PyType_FromSpec") or similar), `PyMemberDef` may contain definitions for the special members `__dictoffset__`, `__weaklistoffset__` and `__vectorcalloffset__`, corresponding to [`tp_dictoffset`](typeobj#c.PyTypeObject.tp_dictoffset "PyTypeObject.tp_dictoffset"), [`tp_weaklistoffset`](typeobj#c.PyTypeObject.tp_weaklistoffset "PyTypeObject.tp_weaklistoffset") and [`tp_vectorcall_offset`](typeobj#c.PyTypeObject.tp_vectorcall_offset "PyTypeObject.tp_vectorcall_offset") in type objects. These must be defined with `T_PYSSIZET` and `READONLY`, for example: ``` static PyMemberDef spam_type_members[] = { {"__dictoffset__", T_PYSSIZET, offsetof(Spam_object, dict), READONLY}, {NULL} /* Sentinel */ }; ``` `PyObject* PyMember_GetOne(const char *obj_addr, struct PyMemberDef *m)` Get an attribute belonging to the object at address *obj\_addr*. The attribute is described by `PyMemberDef` *m*. Returns `NULL` on error. `int PyMember_SetOne(char *obj_addr, struct PyMemberDef *m, PyObject *o)` Set an attribute belonging to the object at address *obj\_addr* to object *o*. The attribute to set is described by `PyMemberDef` *m*. Returns `0` if successful and a negative value on failure. `PyGetSetDef` Structure to define property-like access for a type. See also description of the [`PyTypeObject.tp_getset`](typeobj#c.PyTypeObject.tp_getset "PyTypeObject.tp_getset") slot. | Field | C Type | Meaning | | --- | --- | --- | | name | const char \* | attribute name | | get | getter | C function to get the attribute | | set | setter | optional C function to set or delete the attribute, if omitted the attribute is readonly | | doc | const char \* | optional docstring | | closure | void \* | optional function pointer, providing additional data for getter and setter | The `get` function takes one [`PyObject*`](#c.PyObject "PyObject") parameter (the instance) and a function pointer (the associated `closure`): ``` typedef PyObject *(*getter)(PyObject *, void *); ``` It should return a new reference on success or `NULL` with a set exception on failure. `set` functions take two [`PyObject*`](#c.PyObject "PyObject") parameters (the instance and the value to be set) and a function pointer (the associated `closure`): ``` typedef int (*setter)(PyObject *, PyObject *, void *); ``` In case the attribute should be deleted the second parameter is `NULL`. Should return `0` on success or `-1` with a set exception on failure.
programming_docs
python Importing Modules Importing Modules ================= `PyObject* PyImport_ImportModule(const char *name)` *Return value: New reference.*This is a simplified interface to [`PyImport_ImportModuleEx()`](#c.PyImport_ImportModuleEx "PyImport_ImportModuleEx") below, leaving the *globals* and *locals* arguments set to `NULL` and *level* set to 0. When the *name* argument contains a dot (when it specifies a submodule of a package), the *fromlist* argument is set to the list `['*']` so that the return value is the named module rather than the top-level package containing it as would otherwise be the case. (Unfortunately, this has an additional side effect when *name* in fact specifies a subpackage instead of a submodule: the submodules specified in the package’s `__all__` variable are loaded.) Return a new reference to the imported module, or `NULL` with an exception set on failure. A failing import of a module doesn’t leave the module in [`sys.modules`](../library/sys#sys.modules "sys.modules"). This function always uses absolute imports. `PyObject* PyImport_ImportModuleNoBlock(const char *name)` *Return value: New reference.*This function is a deprecated alias of [`PyImport_ImportModule()`](#c.PyImport_ImportModule "PyImport_ImportModule"). Changed in version 3.3: This function used to fail immediately when the import lock was held by another thread. In Python 3.3 though, the locking scheme switched to per-module locks for most purposes, so this function’s special behaviour isn’t needed anymore. `PyObject* PyImport_ImportModuleEx(const char *name, PyObject *globals, PyObject *locals, PyObject *fromlist)` *Return value: New reference.*Import a module. This is best described by referring to the built-in Python function [`__import__()`](../library/functions#__import__ "__import__"). The return value is a new reference to the imported module or top-level package, or `NULL` with an exception set on failure. Like for [`__import__()`](../library/functions#__import__ "__import__"), the return value when a submodule of a package was requested is normally the top-level package, unless a non-empty *fromlist* was given. Failing imports remove incomplete module objects, like with [`PyImport_ImportModule()`](#c.PyImport_ImportModule "PyImport_ImportModule"). `PyObject* PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level)` *Return value: New reference.*Import a module. This is best described by referring to the built-in Python function [`__import__()`](../library/functions#__import__ "__import__"), as the standard [`__import__()`](../library/functions#__import__ "__import__") function calls this function directly. The return value is a new reference to the imported module or top-level package, or `NULL` with an exception set on failure. Like for [`__import__()`](../library/functions#__import__ "__import__"), the return value when a submodule of a package was requested is normally the top-level package, unless a non-empty *fromlist* was given. New in version 3.3. `PyObject* PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level)` *Return value: New reference.*Similar to [`PyImport_ImportModuleLevelObject()`](#c.PyImport_ImportModuleLevelObject "PyImport_ImportModuleLevelObject"), but the name is a UTF-8 encoded string instead of a Unicode object. Changed in version 3.3: Negative values for *level* are no longer accepted. `PyObject* PyImport_Import(PyObject *name)` *Return value: New reference.*This is a higher-level interface that calls the current “import hook function” (with an explicit *level* of 0, meaning absolute import). It invokes the [`__import__()`](../library/functions#__import__ "__import__") function from the `__builtins__` of the current globals. This means that the import is done using whatever import hooks are installed in the current environment. This function always uses absolute imports. `PyObject* PyImport_ReloadModule(PyObject *m)` *Return value: New reference.*Reload a module. Return a new reference to the reloaded module, or `NULL` with an exception set on failure (the module still exists in this case). `PyObject* PyImport_AddModuleObject(PyObject *name)` *Return value: Borrowed reference.*Return the module object corresponding to a module name. The *name* argument may be of the form `package.module`. First check the modules dictionary if there’s one there, and if not, create a new one and insert it in the modules dictionary. Return `NULL` with an exception set on failure. Note This function does not load or import the module; if the module wasn’t already loaded, you will get an empty module object. Use [`PyImport_ImportModule()`](#c.PyImport_ImportModule "PyImport_ImportModule") or one of its variants to import a module. Package structures implied by a dotted name for *name* are not created if not already present. New in version 3.3. `PyObject* PyImport_AddModule(const char *name)` *Return value: Borrowed reference.*Similar to [`PyImport_AddModuleObject()`](#c.PyImport_AddModuleObject "PyImport_AddModuleObject"), but the name is a UTF-8 encoded string instead of a Unicode object. `PyObject* PyImport_ExecCodeModule(const char *name, PyObject *co)` *Return value: New reference.*Given a module name (possibly of the form `package.module`) and a code object read from a Python bytecode file or obtained from the built-in function [`compile()`](../library/functions#compile "compile"), load the module. Return a new reference to the module object, or `NULL` with an exception set if an error occurred. *name* is removed from [`sys.modules`](../library/sys#sys.modules "sys.modules") in error cases, even if *name* was already in [`sys.modules`](../library/sys#sys.modules "sys.modules") on entry to [`PyImport_ExecCodeModule()`](#c.PyImport_ExecCodeModule "PyImport_ExecCodeModule"). Leaving incompletely initialized modules in [`sys.modules`](../library/sys#sys.modules "sys.modules") is dangerous, as imports of such modules have no way to know that the module object is an unknown (and probably damaged with respect to the module author’s intents) state. The module’s [`__spec__`](../reference/import#__spec__ "__spec__") and [`__loader__`](../reference/import#__loader__ "__loader__") will be set, if not set already, with the appropriate values. The spec’s loader will be set to the module’s `__loader__` (if set) and to an instance of `SourceFileLoader` otherwise. The module’s [`__file__`](../reference/import#__file__ "__file__") attribute will be set to the code object’s `co_filename`. If applicable, [`__cached__`](../reference/import#__cached__ "__cached__") will also be set. This function will reload the module if it was already imported. See [`PyImport_ReloadModule()`](#c.PyImport_ReloadModule "PyImport_ReloadModule") for the intended way to reload a module. If *name* points to a dotted name of the form `package.module`, any package structures not already created will still not be created. See also [`PyImport_ExecCodeModuleEx()`](#c.PyImport_ExecCodeModuleEx "PyImport_ExecCodeModuleEx") and [`PyImport_ExecCodeModuleWithPathnames()`](#c.PyImport_ExecCodeModuleWithPathnames "PyImport_ExecCodeModuleWithPathnames"). `PyObject* PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)` *Return value: New reference.*Like [`PyImport_ExecCodeModule()`](#c.PyImport_ExecCodeModule "PyImport_ExecCodeModule"), but the [`__file__`](../reference/import#__file__ "__file__") attribute of the module object is set to *pathname* if it is non-`NULL`. See also [`PyImport_ExecCodeModuleWithPathnames()`](#c.PyImport_ExecCodeModuleWithPathnames "PyImport_ExecCodeModuleWithPathnames"). `PyObject* PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname, PyObject *cpathname)` *Return value: New reference.*Like [`PyImport_ExecCodeModuleEx()`](#c.PyImport_ExecCodeModuleEx "PyImport_ExecCodeModuleEx"), but the [`__cached__`](../reference/import#__cached__ "__cached__") attribute of the module object is set to *cpathname* if it is non-`NULL`. Of the three functions, this is the preferred one to use. New in version 3.3. `PyObject* PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co, const char *pathname, const char *cpathname)` *Return value: New reference.*Like [`PyImport_ExecCodeModuleObject()`](#c.PyImport_ExecCodeModuleObject "PyImport_ExecCodeModuleObject"), but *name*, *pathname* and *cpathname* are UTF-8 encoded strings. Attempts are also made to figure out what the value for *pathname* should be from *cpathname* if the former is set to `NULL`. New in version 3.2. Changed in version 3.3: Uses [`imp.source_from_cache()`](../library/imp#imp.source_from_cache "imp.source_from_cache") in calculating the source path if only the bytecode path is provided. `long PyImport_GetMagicNumber()` Return the magic number for Python bytecode files (a.k.a. `.pyc` file). The magic number should be present in the first four bytes of the bytecode file, in little-endian byte order. Returns `-1` on error. Changed in version 3.3: Return value of `-1` upon failure. `const char * PyImport_GetMagicTag()` Return the magic tag string for [**PEP 3147**](https://www.python.org/dev/peps/pep-3147) format Python bytecode file names. Keep in mind that the value at `sys.implementation.cache_tag` is authoritative and should be used instead of this function. New in version 3.2. `PyObject* PyImport_GetModuleDict()` *Return value: Borrowed reference.*Return the dictionary used for the module administration (a.k.a. `sys.modules`). Note that this is a per-interpreter variable. `PyObject* PyImport_GetModule(PyObject *name)` *Return value: New reference.*Return the already imported module with the given name. If the module has not been imported yet then returns `NULL` but does not set an error. Returns `NULL` and sets an error if the lookup failed. New in version 3.7. `PyObject* PyImport_GetImporter(PyObject *path)` *Return value: New reference.*Return a finder object for a [`sys.path`](../library/sys#sys.path "sys.path")/`pkg.__path__` item *path*, possibly by fetching it from the [`sys.path_importer_cache`](../library/sys#sys.path_importer_cache "sys.path_importer_cache") dict. If it wasn’t yet cached, traverse [`sys.path_hooks`](../library/sys#sys.path_hooks "sys.path_hooks") until a hook is found that can handle the path item. Return `None` if no hook could; this tells our caller that the [path based finder](../glossary#term-path-based-finder) could not find a finder for this path item. Cache the result in [`sys.path_importer_cache`](../library/sys#sys.path_importer_cache "sys.path_importer_cache"). Return a new reference to the finder object. `int PyImport_ImportFrozenModuleObject(PyObject *name)` *Return value: New reference.*Load a frozen module named *name*. Return `1` for success, `0` if the module is not found, and `-1` with an exception set if the initialization failed. To access the imported module on a successful load, use [`PyImport_ImportModule()`](#c.PyImport_ImportModule "PyImport_ImportModule"). (Note the misnomer — this function would reload the module if it was already imported.) New in version 3.3. Changed in version 3.4: The `__file__` attribute is no longer set on the module. `int PyImport_ImportFrozenModule(const char *name)` Similar to [`PyImport_ImportFrozenModuleObject()`](#c.PyImport_ImportFrozenModuleObject "PyImport_ImportFrozenModuleObject"), but the name is a UTF-8 encoded string instead of a Unicode object. `struct _frozen` This is the structure type definition for frozen module descriptors, as generated by the **freeze** utility (see `Tools/freeze/` in the Python source distribution). Its definition, found in `Include/import.h`, is: ``` struct _frozen { const char *name; const unsigned char *code; int size; }; ``` `const struct _frozen* PyImport_FrozenModules` This pointer is initialized to point to an array of `struct _frozen` records, terminated by one whose members are all `NULL` or zero. When a frozen module is imported, it is searched in this table. Third-party code could play tricks with this to provide a dynamically created collection of frozen modules. `int PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))` Add a single module to the existing table of built-in modules. This is a convenience wrapper around [`PyImport_ExtendInittab()`](#c.PyImport_ExtendInittab "PyImport_ExtendInittab"), returning `-1` if the table could not be extended. The new module can be imported by the name *name*, and uses the function *initfunc* as the initialization function called on the first attempted import. This should be called before [`Py_Initialize()`](init#c.Py_Initialize "Py_Initialize"). `struct _inittab` Structure describing a single entry in the list of built-in modules. Each of these structures gives the name and initialization function for a module built into the interpreter. The name is an ASCII encoded string. Programs which embed Python may use an array of these structures in conjunction with [`PyImport_ExtendInittab()`](#c.PyImport_ExtendInittab "PyImport_ExtendInittab") to provide additional built-in modules. The structure is defined in `Include/import.h` as: ``` struct _inittab { const char *name; /* ASCII encoded string */ PyObject* (*initfunc)(void); }; ``` `int PyImport_ExtendInittab(struct _inittab *newtab)` Add a collection of modules to the table of built-in modules. The *newtab* array must end with a sentinel entry which contains `NULL` for the `name` field; failure to provide the sentinel value can result in a memory fault. Returns `0` on success or `-1` if insufficient memory could be allocated to extend the internal table. In the event of failure, no modules are added to the internal table. This must be called before [`Py_Initialize()`](init#c.Py_Initialize "Py_Initialize"). If Python is initialized multiple times, [`PyImport_AppendInittab()`](#c.PyImport_AppendInittab "PyImport_AppendInittab") or [`PyImport_ExtendInittab()`](#c.PyImport_ExtendInittab "PyImport_ExtendInittab") must be called before each Python initialization. python MemoryView objects MemoryView objects ================== A [`memoryview`](../library/stdtypes#memoryview "memoryview") object exposes the C level [buffer interface](buffer#bufferobjects) as a Python object which can then be passed around like any other object. `PyObject *PyMemoryView_FromObject(PyObject *obj)` *Return value: New reference.*Create a memoryview object from an object that provides the buffer interface. If *obj* supports writable buffer exports, the memoryview object will be read/write, otherwise it may be either read-only or read/write at the discretion of the exporter. `PyObject *PyMemoryView_FromMemory(char *mem, Py_ssize_t size, int flags)` *Return value: New reference.*Create a memoryview object using *mem* as the underlying buffer. *flags* can be one of `PyBUF_READ` or `PyBUF_WRITE`. New in version 3.3. `PyObject *PyMemoryView_FromBuffer(Py_buffer *view)` *Return value: New reference.*Create a memoryview object wrapping the given buffer structure *view*. For simple byte buffers, [`PyMemoryView_FromMemory()`](#c.PyMemoryView_FromMemory "PyMemoryView_FromMemory") is the preferred function. `PyObject *PyMemoryView_GetContiguous(PyObject *obj, int buffertype, char order)` *Return value: New reference.*Create a memoryview object to a [contiguous](../glossary#term-contiguous) chunk of memory (in either ‘C’ or ‘F’ortran *order*) from an object that defines the buffer interface. If memory is contiguous, the memoryview object points to the original memory. Otherwise, a copy is made and the memoryview points to a new bytes object. `int PyMemoryView_Check(PyObject *obj)` Return true if the object *obj* is a memoryview object. It is not currently allowed to create subclasses of [`memoryview`](../library/stdtypes#memoryview "memoryview"). This function always succeeds. `Py_buffer *PyMemoryView_GET_BUFFER(PyObject *mview)` Return a pointer to the memoryview’s private copy of the exporter’s buffer. *mview* **must** be a memoryview instance; this macro doesn’t check its type, you must do it yourself or you will risk crashes. `Py_buffer *PyMemoryView_GET_BASE(PyObject *mview)` Return either a pointer to the exporting object that the memoryview is based on or `NULL` if the memoryview has been created by one of the functions [`PyMemoryView_FromMemory()`](#c.PyMemoryView_FromMemory "PyMemoryView_FromMemory") or [`PyMemoryView_FromBuffer()`](#c.PyMemoryView_FromBuffer "PyMemoryView_FromBuffer"). *mview* **must** be a memoryview instance. python Memory Management Memory Management ================= Overview -------- Memory management in Python involves a private heap containing all Python objects and data structures. The management of this private heap is ensured internally by the *Python memory manager*. The Python memory manager has different components which deal with various dynamic storage management aspects, like sharing, segmentation, preallocation or caching. At the lowest level, a raw memory allocator ensures that there is enough room in the private heap for storing all Python-related data by interacting with the memory manager of the operating system. On top of the raw memory allocator, several object-specific allocators operate on the same heap and implement distinct memory management policies adapted to the peculiarities of every object type. For example, integer objects are managed differently within the heap than strings, tuples or dictionaries because integers imply different storage requirements and speed/space tradeoffs. The Python memory manager thus delegates some of the work to the object-specific allocators, but ensures that the latter operate within the bounds of the private heap. It is important to understand that the management of the Python heap is performed by the interpreter itself and that the user has no control over it, even if they regularly manipulate object pointers to memory blocks inside that heap. The allocation of heap space for Python objects and other internal buffers is performed on demand by the Python memory manager through the Python/C API functions listed in this document. To avoid memory corruption, extension writers should never try to operate on Python objects with the functions exported by the C library: `malloc()`, `calloc()`, `realloc()` and `free()`. This will result in mixed calls between the C allocator and the Python memory manager with fatal consequences, because they implement different algorithms and operate on different heaps. However, one may safely allocate and release memory blocks with the C library allocator for individual purposes, as shown in the following example: ``` PyObject *res; char *buf = (char *) malloc(BUFSIZ); /* for I/O */ if (buf == NULL) return PyErr_NoMemory(); ...Do some I/O operation involving buf... res = PyBytes_FromString(buf); free(buf); /* malloc'ed */ return res; ``` In this example, the memory request for the I/O buffer is handled by the C library allocator. The Python memory manager is involved only in the allocation of the bytes object returned as a result. In most situations, however, it is recommended to allocate memory from the Python heap specifically because the latter is under control of the Python memory manager. For example, this is required when the interpreter is extended with new object types written in C. Another reason for using the Python heap is the desire to *inform* the Python memory manager about the memory needs of the extension module. Even when the requested memory is used exclusively for internal, highly-specific purposes, delegating all memory requests to the Python memory manager causes the interpreter to have a more accurate image of its memory footprint as a whole. Consequently, under certain circumstances, the Python memory manager may or may not trigger appropriate actions, like garbage collection, memory compaction or other preventive procedures. Note that by using the C library allocator as shown in the previous example, the allocated memory for the I/O buffer escapes completely the Python memory manager. See also The [`PYTHONMALLOC`](../using/cmdline#envvar-PYTHONMALLOC) environment variable can be used to configure the memory allocators used by Python. The [`PYTHONMALLOCSTATS`](../using/cmdline#envvar-PYTHONMALLOCSTATS) environment variable can be used to print statistics of the [pymalloc memory allocator](#pymalloc) every time a new pymalloc object arena is created, and on shutdown. Raw Memory Interface -------------------- The following function sets are wrappers to the system allocator. These functions are thread-safe, the [GIL](../glossary#term-global-interpreter-lock) does not need to be held. The [default raw memory allocator](#default-memory-allocators) uses the following functions: `malloc()`, `calloc()`, `realloc()` and `free()`; call `malloc(1)` (or `calloc(1, 1)`) when requesting zero bytes. New in version 3.4. `void* PyMem_RawMalloc(size_t n)` Allocates *n* bytes and returns a pointer of type `void*` to the allocated memory, or `NULL` if the request fails. Requesting zero bytes returns a distinct non-`NULL` pointer if possible, as if `PyMem_RawMalloc(1)` had been called instead. The memory will not have been initialized in any way. `void* PyMem_RawCalloc(size_t nelem, size_t elsize)` Allocates *nelem* elements each whose size in bytes is *elsize* and returns a pointer of type `void*` to the allocated memory, or `NULL` if the request fails. The memory is initialized to zeros. Requesting zero elements or elements of size zero bytes returns a distinct non-`NULL` pointer if possible, as if `PyMem_RawCalloc(1, 1)` had been called instead. New in version 3.5. `void* PyMem_RawRealloc(void *p, size_t n)` Resizes the memory block pointed to by *p* to *n* bytes. The contents will be unchanged to the minimum of the old and the new sizes. If *p* is `NULL`, the call is equivalent to `PyMem_RawMalloc(n)`; else if *n* is equal to zero, the memory block is resized but is not freed, and the returned pointer is non-`NULL`. Unless *p* is `NULL`, it must have been returned by a previous call to [`PyMem_RawMalloc()`](#c.PyMem_RawMalloc "PyMem_RawMalloc"), [`PyMem_RawRealloc()`](#c.PyMem_RawRealloc "PyMem_RawRealloc") or [`PyMem_RawCalloc()`](#c.PyMem_RawCalloc "PyMem_RawCalloc"). If the request fails, [`PyMem_RawRealloc()`](#c.PyMem_RawRealloc "PyMem_RawRealloc") returns `NULL` and *p* remains a valid pointer to the previous memory area. `void PyMem_RawFree(void *p)` Frees the memory block pointed to by *p*, which must have been returned by a previous call to [`PyMem_RawMalloc()`](#c.PyMem_RawMalloc "PyMem_RawMalloc"), [`PyMem_RawRealloc()`](#c.PyMem_RawRealloc "PyMem_RawRealloc") or [`PyMem_RawCalloc()`](#c.PyMem_RawCalloc "PyMem_RawCalloc"). Otherwise, or if `PyMem_RawFree(p)` has been called before, undefined behavior occurs. If *p* is `NULL`, no operation is performed. Memory Interface ---------------- The following function sets, modeled after the ANSI C standard, but specifying behavior when requesting zero bytes, are available for allocating and releasing memory from the Python heap. The [default memory allocator](#default-memory-allocators) uses the [pymalloc memory allocator](#pymalloc). Warning The [GIL](../glossary#term-global-interpreter-lock) must be held when using these functions. Changed in version 3.6: The default allocator is now pymalloc instead of system `malloc()`. `void* PyMem_Malloc(size_t n)` Allocates *n* bytes and returns a pointer of type `void*` to the allocated memory, or `NULL` if the request fails. Requesting zero bytes returns a distinct non-`NULL` pointer if possible, as if `PyMem_Malloc(1)` had been called instead. The memory will not have been initialized in any way. `void* PyMem_Calloc(size_t nelem, size_t elsize)` Allocates *nelem* elements each whose size in bytes is *elsize* and returns a pointer of type `void*` to the allocated memory, or `NULL` if the request fails. The memory is initialized to zeros. Requesting zero elements or elements of size zero bytes returns a distinct non-`NULL` pointer if possible, as if `PyMem_Calloc(1, 1)` had been called instead. New in version 3.5. `void* PyMem_Realloc(void *p, size_t n)` Resizes the memory block pointed to by *p* to *n* bytes. The contents will be unchanged to the minimum of the old and the new sizes. If *p* is `NULL`, the call is equivalent to `PyMem_Malloc(n)`; else if *n* is equal to zero, the memory block is resized but is not freed, and the returned pointer is non-`NULL`. Unless *p* is `NULL`, it must have been returned by a previous call to [`PyMem_Malloc()`](#c.PyMem_Malloc "PyMem_Malloc"), [`PyMem_Realloc()`](#c.PyMem_Realloc "PyMem_Realloc") or [`PyMem_Calloc()`](#c.PyMem_Calloc "PyMem_Calloc"). If the request fails, [`PyMem_Realloc()`](#c.PyMem_Realloc "PyMem_Realloc") returns `NULL` and *p* remains a valid pointer to the previous memory area. `void PyMem_Free(void *p)` Frees the memory block pointed to by *p*, which must have been returned by a previous call to [`PyMem_Malloc()`](#c.PyMem_Malloc "PyMem_Malloc"), [`PyMem_Realloc()`](#c.PyMem_Realloc "PyMem_Realloc") or [`PyMem_Calloc()`](#c.PyMem_Calloc "PyMem_Calloc"). Otherwise, or if `PyMem_Free(p)` has been called before, undefined behavior occurs. If *p* is `NULL`, no operation is performed. The following type-oriented macros are provided for convenience. Note that *TYPE* refers to any C type. `TYPE* PyMem_New(TYPE, size_t n)` Same as [`PyMem_Malloc()`](#c.PyMem_Malloc "PyMem_Malloc"), but allocates `(n * sizeof(TYPE))` bytes of memory. Returns a pointer cast to `TYPE*`. The memory will not have been initialized in any way. `TYPE* PyMem_Resize(void *p, TYPE, size_t n)` Same as [`PyMem_Realloc()`](#c.PyMem_Realloc "PyMem_Realloc"), but the memory block is resized to `(n * sizeof(TYPE))` bytes. Returns a pointer cast to `TYPE*`. On return, *p* will be a pointer to the new memory area, or `NULL` in the event of failure. This is a C preprocessor macro; *p* is always reassigned. Save the original value of *p* to avoid losing memory when handling errors. `void PyMem_Del(void *p)` Same as [`PyMem_Free()`](#c.PyMem_Free "PyMem_Free"). In addition, the following macro sets are provided for calling the Python memory allocator directly, without involving the C API functions listed above. However, note that their use does not preserve binary compatibility across Python versions and is therefore deprecated in extension modules. * `PyMem_MALLOC(size)` * `PyMem_NEW(type, size)` * `PyMem_REALLOC(ptr, size)` * `PyMem_RESIZE(ptr, type, size)` * `PyMem_FREE(ptr)` * `PyMem_DEL(ptr)` Object allocators ----------------- The following function sets, modeled after the ANSI C standard, but specifying behavior when requesting zero bytes, are available for allocating and releasing memory from the Python heap. The [default object allocator](#default-memory-allocators) uses the [pymalloc memory allocator](#pymalloc). Warning The [GIL](../glossary#term-global-interpreter-lock) must be held when using these functions. `void* PyObject_Malloc(size_t n)` Allocates *n* bytes and returns a pointer of type `void*` to the allocated memory, or `NULL` if the request fails. Requesting zero bytes returns a distinct non-`NULL` pointer if possible, as if `PyObject_Malloc(1)` had been called instead. The memory will not have been initialized in any way. `void* PyObject_Calloc(size_t nelem, size_t elsize)` Allocates *nelem* elements each whose size in bytes is *elsize* and returns a pointer of type `void*` to the allocated memory, or `NULL` if the request fails. The memory is initialized to zeros. Requesting zero elements or elements of size zero bytes returns a distinct non-`NULL` pointer if possible, as if `PyObject_Calloc(1, 1)` had been called instead. New in version 3.5. `void* PyObject_Realloc(void *p, size_t n)` Resizes the memory block pointed to by *p* to *n* bytes. The contents will be unchanged to the minimum of the old and the new sizes. If *p* is `NULL`, the call is equivalent to `PyObject_Malloc(n)`; else if *n* is equal to zero, the memory block is resized but is not freed, and the returned pointer is non-`NULL`. Unless *p* is `NULL`, it must have been returned by a previous call to [`PyObject_Malloc()`](#c.PyObject_Malloc "PyObject_Malloc"), [`PyObject_Realloc()`](#c.PyObject_Realloc "PyObject_Realloc") or [`PyObject_Calloc()`](#c.PyObject_Calloc "PyObject_Calloc"). If the request fails, [`PyObject_Realloc()`](#c.PyObject_Realloc "PyObject_Realloc") returns `NULL` and *p* remains a valid pointer to the previous memory area. `void PyObject_Free(void *p)` Frees the memory block pointed to by *p*, which must have been returned by a previous call to [`PyObject_Malloc()`](#c.PyObject_Malloc "PyObject_Malloc"), [`PyObject_Realloc()`](#c.PyObject_Realloc "PyObject_Realloc") or [`PyObject_Calloc()`](#c.PyObject_Calloc "PyObject_Calloc"). Otherwise, or if `PyObject_Free(p)` has been called before, undefined behavior occurs. If *p* is `NULL`, no operation is performed. Default Memory Allocators ------------------------- Default memory allocators: | Configuration | Name | PyMem\_RawMalloc | PyMem\_Malloc | PyObject\_Malloc | | --- | --- | --- | --- | --- | | Release build | `"pymalloc"` | `malloc` | `pymalloc` | `pymalloc` | | Debug build | `"pymalloc_debug"` | `malloc` + debug | `pymalloc` + debug | `pymalloc` + debug | | Release build, without pymalloc | `"malloc"` | `malloc` | `malloc` | `malloc` | | Debug build, without pymalloc | `"malloc_debug"` | `malloc` + debug | `malloc` + debug | `malloc` + debug | Legend: * Name: value for [`PYTHONMALLOC`](../using/cmdline#envvar-PYTHONMALLOC) environment variable * `malloc`: system allocators from the standard C library, C functions: `malloc()`, `calloc()`, `realloc()` and `free()` * `pymalloc`: [pymalloc memory allocator](#pymalloc) * “+ debug”: with debug hooks installed by [`PyMem_SetupDebugHooks()`](#c.PyMem_SetupDebugHooks "PyMem_SetupDebugHooks") Customize Memory Allocators --------------------------- New in version 3.4. `PyMemAllocatorEx` Structure used to describe a memory block allocator. The structure has the following fields: | Field | Meaning | | --- | --- | | `void *ctx` | user context passed as first argument | | `void* malloc(void *ctx, size_t size)` | allocate a memory block | | `void* calloc(void *ctx, size_t nelem, size_t elsize)` | allocate a memory block initialized with zeros | | `void* realloc(void *ctx, void *ptr, size_t new_size)` | allocate or resize a memory block | | `void free(void *ctx, void *ptr)` | free a memory block | Changed in version 3.5: The `PyMemAllocator` structure was renamed to [`PyMemAllocatorEx`](#c.PyMemAllocatorEx "PyMemAllocatorEx") and a new `calloc` field was added. `PyMemAllocatorDomain` Enum used to identify an allocator domain. Domains: `PYMEM_DOMAIN_RAW` Functions: * [`PyMem_RawMalloc()`](#c.PyMem_RawMalloc "PyMem_RawMalloc") * [`PyMem_RawRealloc()`](#c.PyMem_RawRealloc "PyMem_RawRealloc") * [`PyMem_RawCalloc()`](#c.PyMem_RawCalloc "PyMem_RawCalloc") * [`PyMem_RawFree()`](#c.PyMem_RawFree "PyMem_RawFree") `PYMEM_DOMAIN_MEM` Functions: * [`PyMem_Malloc()`](#c.PyMem_Malloc "PyMem_Malloc"), * [`PyMem_Realloc()`](#c.PyMem_Realloc "PyMem_Realloc") * [`PyMem_Calloc()`](#c.PyMem_Calloc "PyMem_Calloc") * [`PyMem_Free()`](#c.PyMem_Free "PyMem_Free") `PYMEM_DOMAIN_OBJ` Functions: * [`PyObject_Malloc()`](#c.PyObject_Malloc "PyObject_Malloc") * [`PyObject_Realloc()`](#c.PyObject_Realloc "PyObject_Realloc") * [`PyObject_Calloc()`](#c.PyObject_Calloc "PyObject_Calloc") * [`PyObject_Free()`](#c.PyObject_Free "PyObject_Free") `void PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)` Get the memory block allocator of the specified domain. `void PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)` Set the memory block allocator of the specified domain. The new allocator must return a distinct non-`NULL` pointer when requesting zero bytes. For the [`PYMEM_DOMAIN_RAW`](#c.PYMEM_DOMAIN_RAW "PYMEM_DOMAIN_RAW") domain, the allocator must be thread-safe: the [GIL](../glossary#term-global-interpreter-lock) is not held when the allocator is called. If the new allocator is not a hook (does not call the previous allocator), the [`PyMem_SetupDebugHooks()`](#c.PyMem_SetupDebugHooks "PyMem_SetupDebugHooks") function must be called to reinstall the debug hooks on top on the new allocator. `void PyMem_SetupDebugHooks(void)` Setup hooks to detect bugs in the Python memory allocator functions. Newly allocated memory is filled with the byte `0xCD` (`CLEANBYTE`), freed memory is filled with the byte `0xDD` (`DEADBYTE`). Memory blocks are surrounded by “forbidden bytes” (`FORBIDDENBYTE`: byte `0xFD`). Runtime checks: * Detect API violations, ex: [`PyObject_Free()`](#c.PyObject_Free "PyObject_Free") called on a buffer allocated by [`PyMem_Malloc()`](#c.PyMem_Malloc "PyMem_Malloc") * Detect write before the start of the buffer (buffer underflow) * Detect write after the end of the buffer (buffer overflow) * Check that the [GIL](../glossary#term-global-interpreter-lock) is held when allocator functions of [`PYMEM_DOMAIN_OBJ`](#c.PYMEM_DOMAIN_OBJ "PYMEM_DOMAIN_OBJ") (ex: [`PyObject_Malloc()`](#c.PyObject_Malloc "PyObject_Malloc")) and [`PYMEM_DOMAIN_MEM`](#c.PYMEM_DOMAIN_MEM "PYMEM_DOMAIN_MEM") (ex: [`PyMem_Malloc()`](#c.PyMem_Malloc "PyMem_Malloc")) domains are called On error, the debug hooks use the [`tracemalloc`](../library/tracemalloc#module-tracemalloc "tracemalloc: Trace memory allocations.") module to get the traceback where a memory block was allocated. The traceback is only displayed if [`tracemalloc`](../library/tracemalloc#module-tracemalloc "tracemalloc: Trace memory allocations.") is tracing Python memory allocations and the memory block was traced. These hooks are [installed by default](#default-memory-allocators) if Python is compiled in debug mode. The [`PYTHONMALLOC`](../using/cmdline#envvar-PYTHONMALLOC) environment variable can be used to install debug hooks on a Python compiled in release mode. Changed in version 3.6: This function now also works on Python compiled in release mode. On error, the debug hooks now use [`tracemalloc`](../library/tracemalloc#module-tracemalloc "tracemalloc: Trace memory allocations.") to get the traceback where a memory block was allocated. The debug hooks now also check if the GIL is held when functions of [`PYMEM_DOMAIN_OBJ`](#c.PYMEM_DOMAIN_OBJ "PYMEM_DOMAIN_OBJ") and [`PYMEM_DOMAIN_MEM`](#c.PYMEM_DOMAIN_MEM "PYMEM_DOMAIN_MEM") domains are called. Changed in version 3.8: Byte patterns `0xCB` (`CLEANBYTE`), `0xDB` (`DEADBYTE`) and `0xFB` (`FORBIDDENBYTE`) have been replaced with `0xCD`, `0xDD` and `0xFD` to use the same values than Windows CRT debug `malloc()` and `free()`. The pymalloc allocator ---------------------- Python has a *pymalloc* allocator optimized for small objects (smaller or equal to 512 bytes) with a short lifetime. It uses memory mappings called “arenas” with a fixed size of 256 KiB. It falls back to [`PyMem_RawMalloc()`](#c.PyMem_RawMalloc "PyMem_RawMalloc") and [`PyMem_RawRealloc()`](#c.PyMem_RawRealloc "PyMem_RawRealloc") for allocations larger than 512 bytes. *pymalloc* is the [default allocator](#default-memory-allocators) of the [`PYMEM_DOMAIN_MEM`](#c.PYMEM_DOMAIN_MEM "PYMEM_DOMAIN_MEM") (ex: [`PyMem_Malloc()`](#c.PyMem_Malloc "PyMem_Malloc")) and [`PYMEM_DOMAIN_OBJ`](#c.PYMEM_DOMAIN_OBJ "PYMEM_DOMAIN_OBJ") (ex: [`PyObject_Malloc()`](#c.PyObject_Malloc "PyObject_Malloc")) domains. The arena allocator uses the following functions: * `VirtualAlloc()` and `VirtualFree()` on Windows, * `mmap()` and `munmap()` if available, * `malloc()` and `free()` otherwise. ### Customize pymalloc Arena Allocator New in version 3.4. `PyObjectArenaAllocator` Structure used to describe an arena allocator. The structure has three fields: | Field | Meaning | | --- | --- | | `void *ctx` | user context passed as first argument | | `void* alloc(void *ctx, size_t size)` | allocate an arena of size bytes | | `void free(void *ctx, void *ptr, size_t size)` | free an arena | `void PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator)` Get the arena allocator. `void PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator)` Set the arena allocator. tracemalloc C API ----------------- New in version 3.7. `int PyTraceMalloc_Track(unsigned int domain, uintptr_t ptr, size_t size)` Track an allocated memory block in the [`tracemalloc`](../library/tracemalloc#module-tracemalloc "tracemalloc: Trace memory allocations.") module. Return `0` on success, return `-1` on error (failed to allocate memory to store the trace). Return `-2` if tracemalloc is disabled. If memory block is already tracked, update the existing trace. `int PyTraceMalloc_Untrack(unsigned int domain, uintptr_t ptr)` Untrack an allocated memory block in the [`tracemalloc`](../library/tracemalloc#module-tracemalloc "tracemalloc: Trace memory allocations.") module. Do nothing if the block was not tracked. Return `-2` if tracemalloc is disabled, otherwise return `0`. Examples -------- Here is the example from section [Overview](#memoryoverview), rewritten so that the I/O buffer is allocated from the Python heap by using the first function set: ``` PyObject *res; char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */ if (buf == NULL) return PyErr_NoMemory(); /* ...Do some I/O operation involving buf... */ res = PyBytes_FromString(buf); PyMem_Free(buf); /* allocated with PyMem_Malloc */ return res; ``` The same code using the type-oriented function set: ``` PyObject *res; char *buf = PyMem_New(char, BUFSIZ); /* for I/O */ if (buf == NULL) return PyErr_NoMemory(); /* ...Do some I/O operation involving buf... */ res = PyBytes_FromString(buf); PyMem_Del(buf); /* allocated with PyMem_New */ return res; ``` Note that in the two examples above, the buffer is always manipulated via functions belonging to the same set. Indeed, it is required to use the same memory API family for a given memory block, so that the risk of mixing different allocators is reduced to a minimum. The following code sequence contains two errors, one of which is labeled as *fatal* because it mixes two different allocators operating on different heaps. ``` char *buf1 = PyMem_New(char, BUFSIZ); char *buf2 = (char *) malloc(BUFSIZ); char *buf3 = (char *) PyMem_Malloc(BUFSIZ); ... PyMem_Del(buf3); /* Wrong -- should be PyMem_Free() */ free(buf2); /* Right -- allocated via malloc() */ free(buf1); /* Fatal -- should be PyMem_Del() */ ``` In addition to the functions aimed at handling raw memory blocks from the Python heap, objects in Python are allocated and released with [`PyObject_New()`](allocation#c.PyObject_New "PyObject_New"), [`PyObject_NewVar()`](allocation#c.PyObject_NewVar "PyObject_NewVar") and [`PyObject_Del()`](allocation#c.PyObject_Del "PyObject_Del"). These will be explained in the next chapter on defining and implementing new object types in C.
programming_docs
python Iterator Protocol Iterator Protocol ================= There are two functions specifically for working with iterators. `int PyIter_Check(PyObject *o)` Return true if the object *o* supports the iterator protocol. This function always succeeds. `PyObject* PyIter_Next(PyObject *o)` *Return value: New reference.*Return the next value from the iteration *o*. The object must be an iterator (it is up to the caller to check this). If there are no remaining values, returns `NULL` with no exception set. If an error occurs while retrieving the item, returns `NULL` and passes along the exception. To write a loop which iterates over an iterator, the C code should look something like this: ``` PyObject *iterator = PyObject_GetIter(obj); PyObject *item; if (iterator == NULL) { /* propagate error */ } while ((item = PyIter_Next(iterator))) { /* do something with item */ ... /* release reference when done */ Py_DECREF(item); } Py_DECREF(iterator); if (PyErr_Occurred()) { /* propagate error */ } else { /* continue doing useful work */ } ``` python The None Object The None Object =============== Note that the [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject") for `None` is not directly exposed in the Python/C API. Since `None` is a singleton, testing for object identity (using `==` in C) is sufficient. There is no `PyNone_Check()` function for the same reason. `PyObject* Py_None` The Python `None` object, denoting lack of value. This object has no methods. It needs to be treated just like any other object with respect to reference counts. `Py_RETURN_NONE` Properly handle returning [`Py_None`](#c.Py_None "Py_None") from within a C function (that is, increment the reference count of `None` and return it.) python Stable Application Binary Interface Stable Application Binary Interface =================================== Traditionally, the C API of Python will change with every release. Most changes will be source-compatible, typically by only adding API, rather than changing existing API or removing API (although some interfaces do get removed after being deprecated first). Unfortunately, the API compatibility does not extend to binary compatibility (the ABI). The reason is primarily the evolution of struct definitions, where addition of a new field, or changing the type of a field, might not break the API, but can break the ABI. As a consequence, extension modules need to be recompiled for every Python release (although an exception is possible on Unix when none of the affected interfaces are used). In addition, on Windows, extension modules link with a specific pythonXY.dll and need to be recompiled to link with a newer one. Since Python 3.2, a subset of the API has been declared to guarantee a stable ABI. Extension modules wishing to use this API (called “limited API”) need to define `Py_LIMITED_API`. A number of interpreter details then become hidden from the extension module; in return, a module is built that works on any 3.x version (x>=2) without recompilation. In some cases, the stable ABI needs to be extended with new functions. Extension modules wishing to use these new APIs need to set `Py_LIMITED_API` to the `PY_VERSION_HEX` value (see [API and ABI Versioning](apiabiversion#apiabiversion)) of the minimum Python version they want to support (e.g. `0x03030000` for Python 3.3). Such modules will work on all subsequent Python releases, but fail to load (because of missing symbols) on the older releases. As of Python 3.2, the set of functions available to the limited API is documented in [**PEP 384**](https://www.python.org/dev/peps/pep-0384). In the C API documentation, API elements that are not part of the limited API are marked as “Not part of the limited API.” python Code Objects Code Objects ============ Code objects are a low-level detail of the CPython implementation. Each one represents a chunk of executable code that hasn’t yet been bound into a function. `PyCodeObject` The C structure of the objects used to describe code objects. The fields of this type are subject to change at any time. `PyTypeObject PyCode_Type` This is an instance of [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject") representing the Python [`code`](../library/code#module-code "code: Facilities to implement read-eval-print loops.") type. `int PyCode_Check(PyObject *co)` Return true if *co* is a [`code`](../library/code#module-code "code: Facilities to implement read-eval-print loops.") object. This function always succeeds. `int PyCode_GetNumFree(PyCodeObject *co)` Return the number of free variables in *co*. `PyCodeObject* PyCode_New(int argcount, int kwonlyargcount, int nlocals, int stacksize, int flags, PyObject *code, PyObject *consts, PyObject *names, PyObject *varnames, PyObject *freevars, PyObject *cellvars, PyObject *filename, PyObject *name, int firstlineno, PyObject *lnotab)` *Return value: New reference.*Return a new code object. If you need a dummy code object to create a frame, use [`PyCode_NewEmpty()`](#c.PyCode_NewEmpty "PyCode_NewEmpty") instead. Calling [`PyCode_New()`](#c.PyCode_New "PyCode_New") directly can bind you to a precise Python version since the definition of the bytecode changes often. `PyCodeObject* PyCode_NewWithPosOnlyArgs(int argcount, int posonlyargcount, int kwonlyargcount, int nlocals, int stacksize, int flags, PyObject *code, PyObject *consts, PyObject *names, PyObject *varnames, PyObject *freevars, PyObject *cellvars, PyObject *filename, PyObject *name, int firstlineno, PyObject *lnotab)` *Return value: New reference.*Similar to [`PyCode_New()`](#c.PyCode_New "PyCode_New"), but with an extra “posonlyargcount” for positional-only arguments. New in version 3.8. `PyCodeObject* PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)` *Return value: New reference.*Return a new empty code object with the specified filename, function name, and first line number. It is illegal to [`exec()`](../library/functions#exec "exec") or [`eval()`](../library/functions#eval "eval") the resulting code object. python Data marshalling support Data marshalling support ======================== These routines allow C code to work with serialized objects using the same data format as the [`marshal`](../library/marshal#module-marshal "marshal: Convert Python objects to streams of bytes and back (with different constraints).") module. There are functions to write data into the serialization format, and additional functions that can be used to read the data back. Files used to store marshalled data must be opened in binary mode. Numeric values are stored with the least significant byte first. The module supports two versions of the data format: version 0 is the historical version, version 1 shares interned strings in the file, and upon unmarshalling. Version 2 uses a binary format for floating point numbers. `Py_MARSHAL_VERSION` indicates the current file format (currently 2). `void PyMarshal_WriteLongToFile(long value, FILE *file, int version)` Marshal a `long` integer, *value*, to *file*. This will only write the least-significant 32 bits of *value*; regardless of the size of the native `long` type. *version* indicates the file format. `void PyMarshal_WriteObjectToFile(PyObject *value, FILE *file, int version)` Marshal a Python object, *value*, to *file*. *version* indicates the file format. `PyObject* PyMarshal_WriteObjectToString(PyObject *value, int version)` *Return value: New reference.*Return a bytes object containing the marshalled representation of *value*. *version* indicates the file format. The following functions allow marshalled values to be read back in. `long PyMarshal_ReadLongFromFile(FILE *file)` Return a C `long` from the data stream in a `FILE*` opened for reading. Only a 32-bit value can be read in using this function, regardless of the native size of `long`. On error, sets the appropriate exception ([`EOFError`](../library/exceptions#EOFError "EOFError")) and returns `-1`. `int PyMarshal_ReadShortFromFile(FILE *file)` Return a C `short` from the data stream in a `FILE*` opened for reading. Only a 16-bit value can be read in using this function, regardless of the native size of `short`. On error, sets the appropriate exception ([`EOFError`](../library/exceptions#EOFError "EOFError")) and returns `-1`. `PyObject* PyMarshal_ReadObjectFromFile(FILE *file)` *Return value: New reference.*Return a Python object from the data stream in a `FILE*` opened for reading. On error, sets the appropriate exception ([`EOFError`](../library/exceptions#EOFError "EOFError"), [`ValueError`](../library/exceptions#ValueError "ValueError") or [`TypeError`](../library/exceptions#TypeError "TypeError")) and returns `NULL`. `PyObject* PyMarshal_ReadLastObjectFromFile(FILE *file)` *Return value: New reference.*Return a Python object from the data stream in a `FILE*` opened for reading. Unlike [`PyMarshal_ReadObjectFromFile()`](#c.PyMarshal_ReadObjectFromFile "PyMarshal_ReadObjectFromFile"), this function assumes that no further objects will be read from the file, allowing it to aggressively load file data into memory so that the de-serialization can operate from data in memory rather than reading a byte at a time from the file. Only use these variant if you are certain that you won’t be reading anything else from the file. On error, sets the appropriate exception ([`EOFError`](../library/exceptions#EOFError "EOFError"), [`ValueError`](../library/exceptions#ValueError "ValueError") or [`TypeError`](../library/exceptions#TypeError "TypeError")) and returns `NULL`. `PyObject* PyMarshal_ReadObjectFromString(const char *data, Py_ssize_t len)` *Return value: New reference.*Return a Python object from the data stream in a byte buffer containing *len* bytes pointed to by *data*. On error, sets the appropriate exception ([`EOFError`](../library/exceptions#EOFError "EOFError"), [`ValueError`](../library/exceptions#ValueError "ValueError") or [`TypeError`](../library/exceptions#TypeError "TypeError")) and returns `NULL`. python Boolean Objects Boolean Objects =============== Booleans in Python are implemented as a subclass of integers. There are only two booleans, `Py_False` and `Py_True`. As such, the normal creation and deletion functions don’t apply to booleans. The following macros are available, however. `int PyBool_Check(PyObject *o)` Return true if *o* is of type `PyBool_Type`. This function always succeeds. `PyObject* Py_False` The Python `False` object. This object has no methods. It needs to be treated just like any other object with respect to reference counts. `PyObject* Py_True` The Python `True` object. This object has no methods. It needs to be treated just like any other object with respect to reference counts. `Py_RETURN_FALSE` Return `Py_False` from a function, properly incrementing its reference count. `Py_RETURN_TRUE` Return `Py_True` from a function, properly incrementing its reference count. `PyObject* PyBool_FromLong(long v)` *Return value: New reference.*Return a new reference to `Py_True` or `Py_False` depending on the truth value of *v*. python Buffer Protocol Buffer Protocol =============== Certain objects available in Python wrap access to an underlying memory array or *buffer*. Such objects include the built-in [`bytes`](../library/stdtypes#bytes "bytes") and [`bytearray`](../library/stdtypes#bytearray "bytearray"), and some extension types like [`array.array`](../library/array#array.array "array.array"). Third-party libraries may define their own types for special purposes, such as image processing or numeric analysis. While each of these types have their own semantics, they share the common characteristic of being backed by a possibly large memory buffer. It is then desirable, in some situations, to access that buffer directly and without intermediate copying. Python provides such a facility at the C level in the form of the [buffer protocol](#bufferobjects). This protocol has two sides: * on the producer side, a type can export a “buffer interface” which allows objects of that type to expose information about their underlying buffer. This interface is described in the section [Buffer Object Structures](typeobj#buffer-structs); * on the consumer side, several means are available to obtain a pointer to the raw underlying data of an object (for example a method parameter). Simple objects such as [`bytes`](../library/stdtypes#bytes "bytes") and [`bytearray`](../library/stdtypes#bytearray "bytearray") expose their underlying buffer in byte-oriented form. Other forms are possible; for example, the elements exposed by an [`array.array`](../library/array#array.array "array.array") can be multi-byte values. An example consumer of the buffer interface is the [`write()`](../library/io#io.BufferedIOBase.write "io.BufferedIOBase.write") method of file objects: any object that can export a series of bytes through the buffer interface can be written to a file. While `write()` only needs read-only access to the internal contents of the object passed to it, other methods such as [`readinto()`](../library/io#io.BufferedIOBase.readinto "io.BufferedIOBase.readinto") need write access to the contents of their argument. The buffer interface allows objects to selectively allow or reject exporting of read-write and read-only buffers. There are two ways for a consumer of the buffer interface to acquire a buffer over a target object: * call [`PyObject_GetBuffer()`](#c.PyObject_GetBuffer "PyObject_GetBuffer") with the right parameters; * call [`PyArg_ParseTuple()`](arg#c.PyArg_ParseTuple "PyArg_ParseTuple") (or one of its siblings) with one of the `y*`, `w*` or `s*` [format codes](arg#arg-parsing). In both cases, [`PyBuffer_Release()`](#c.PyBuffer_Release "PyBuffer_Release") must be called when the buffer isn’t needed anymore. Failure to do so could lead to various issues such as resource leaks. Buffer structure ---------------- Buffer structures (or simply “buffers”) are useful as a way to expose the binary data from another object to the Python programmer. They can also be used as a zero-copy slicing mechanism. Using their ability to reference a block of memory, it is possible to expose any data to the Python programmer quite easily. The memory could be a large, constant array in a C extension, it could be a raw block of memory for manipulation before passing to an operating system library, or it could be used to pass around structured data in its native, in-memory format. Contrary to most data types exposed by the Python interpreter, buffers are not [`PyObject`](structures#c.PyObject "PyObject") pointers but rather simple C structures. This allows them to be created and copied very simply. When a generic wrapper around a buffer is needed, a [memoryview](memoryview#memoryview-objects) object can be created. For short instructions how to write an exporting object, see [Buffer Object Structures](typeobj#buffer-structs). For obtaining a buffer, see [`PyObject_GetBuffer()`](#c.PyObject_GetBuffer "PyObject_GetBuffer"). `Py_buffer` `void *buf` A pointer to the start of the logical structure described by the buffer fields. This can be any location within the underlying physical memory block of the exporter. For example, with negative [`strides`](#c.Py_buffer.strides "Py_buffer.strides") the value may point to the end of the memory block. For [contiguous](../glossary#term-contiguous) arrays, the value points to the beginning of the memory block. `void *obj` A new reference to the exporting object. The reference is owned by the consumer and automatically decremented and set to `NULL` by [`PyBuffer_Release()`](#c.PyBuffer_Release "PyBuffer_Release"). The field is the equivalent of the return value of any standard C-API function. As a special case, for *temporary* buffers that are wrapped by [`PyMemoryView_FromBuffer()`](memoryview#c.PyMemoryView_FromBuffer "PyMemoryView_FromBuffer") or [`PyBuffer_FillInfo()`](#c.PyBuffer_FillInfo "PyBuffer_FillInfo") this field is `NULL`. In general, exporting objects MUST NOT use this scheme. `Py_ssize_t len` `product(shape) * itemsize`. For contiguous arrays, this is the length of the underlying memory block. For non-contiguous arrays, it is the length that the logical structure would have if it were copied to a contiguous representation. Accessing `((char *)buf)[0] up to ((char *)buf)[len-1]` is only valid if the buffer has been obtained by a request that guarantees contiguity. In most cases such a request will be [`PyBUF_SIMPLE`](#c.PyBUF_SIMPLE "PyBUF_SIMPLE") or [`PyBUF_WRITABLE`](#c.PyBUF_WRITABLE "PyBUF_WRITABLE"). `int readonly` An indicator of whether the buffer is read-only. This field is controlled by the [`PyBUF_WRITABLE`](#c.PyBUF_WRITABLE "PyBUF_WRITABLE") flag. `Py_ssize_t itemsize` Item size in bytes of a single element. Same as the value of [`struct.calcsize()`](../library/struct#struct.calcsize "struct.calcsize") called on non-`NULL` [`format`](#c.Py_buffer.format "Py_buffer.format") values. Important exception: If a consumer requests a buffer without the [`PyBUF_FORMAT`](#c.PyBUF_FORMAT "PyBUF_FORMAT") flag, [`format`](#c.Py_buffer.format "Py_buffer.format") will be set to `NULL`, but [`itemsize`](#c.Py_buffer.itemsize "Py_buffer.itemsize") still has the value for the original format. If [`shape`](#c.Py_buffer.shape "Py_buffer.shape") is present, the equality `product(shape) * itemsize == len` still holds and the consumer can use [`itemsize`](#c.Py_buffer.itemsize "Py_buffer.itemsize") to navigate the buffer. If [`shape`](#c.Py_buffer.shape "Py_buffer.shape") is `NULL` as a result of a [`PyBUF_SIMPLE`](#c.PyBUF_SIMPLE "PyBUF_SIMPLE") or a [`PyBUF_WRITABLE`](#c.PyBUF_WRITABLE "PyBUF_WRITABLE") request, the consumer must disregard [`itemsize`](#c.Py_buffer.itemsize "Py_buffer.itemsize") and assume `itemsize == 1`. `const char *format` A *NUL* terminated string in [`struct`](../library/struct#module-struct "struct: Interpret bytes as packed binary data.") module style syntax describing the contents of a single item. If this is `NULL`, `"B"` (unsigned bytes) is assumed. This field is controlled by the [`PyBUF_FORMAT`](#c.PyBUF_FORMAT "PyBUF_FORMAT") flag. `int ndim` The number of dimensions the memory represents as an n-dimensional array. If it is `0`, [`buf`](#c.Py_buffer.buf "Py_buffer.buf") points to a single item representing a scalar. In this case, [`shape`](#c.Py_buffer.shape "Py_buffer.shape"), [`strides`](#c.Py_buffer.strides "Py_buffer.strides") and [`suboffsets`](#c.Py_buffer.suboffsets "Py_buffer.suboffsets") MUST be `NULL`. The macro `PyBUF_MAX_NDIM` limits the maximum number of dimensions to 64. Exporters MUST respect this limit, consumers of multi-dimensional buffers SHOULD be able to handle up to `PyBUF_MAX_NDIM` dimensions. `Py_ssize_t *shape` An array of [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t") of length [`ndim`](#c.Py_buffer.ndim "Py_buffer.ndim") indicating the shape of the memory as an n-dimensional array. Note that `shape[0] * ... * shape[ndim-1] * itemsize` MUST be equal to [`len`](#c.Py_buffer.len "Py_buffer.len"). Shape values are restricted to `shape[n] >= 0`. The case `shape[n] == 0` requires special attention. See [complex arrays](#complex-arrays) for further information. The shape array is read-only for the consumer. `Py_ssize_t *strides` An array of [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t") of length [`ndim`](#c.Py_buffer.ndim "Py_buffer.ndim") giving the number of bytes to skip to get to a new element in each dimension. Stride values can be any integer. For regular arrays, strides are usually positive, but a consumer MUST be able to handle the case `strides[n] <= 0`. See [complex arrays](#complex-arrays) for further information. The strides array is read-only for the consumer. `Py_ssize_t *suboffsets` An array of [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t") of length [`ndim`](#c.Py_buffer.ndim "Py_buffer.ndim"). If `suboffsets[n] >= 0`, the values stored along the nth dimension are pointers and the suboffset value dictates how many bytes to add to each pointer after de-referencing. A suboffset value that is negative indicates that no de-referencing should occur (striding in a contiguous memory block). If all suboffsets are negative (i.e. no de-referencing is needed), then this field must be `NULL` (the default value). This type of array representation is used by the Python Imaging Library (PIL). See [complex arrays](#complex-arrays) for further information how to access elements of such an array. The suboffsets array is read-only for the consumer. `void *internal` This is for use internally by the exporting object. For example, this might be re-cast as an integer by the exporter and used to store flags about whether or not the shape, strides, and suboffsets arrays must be freed when the buffer is released. The consumer MUST NOT alter this value. Buffer request types -------------------- Buffers are usually obtained by sending a buffer request to an exporting object via [`PyObject_GetBuffer()`](#c.PyObject_GetBuffer "PyObject_GetBuffer"). Since the complexity of the logical structure of the memory can vary drastically, the consumer uses the *flags* argument to specify the exact buffer type it can handle. All [`Py_buffer`](#c.Py_buffer "Py_buffer") fields are unambiguously defined by the request type. ### request-independent fields The following fields are not influenced by *flags* and must always be filled in with the correct values: [`obj`](#c.Py_buffer.obj "Py_buffer.obj"), [`buf`](#c.Py_buffer.buf "Py_buffer.buf"), [`len`](#c.Py_buffer.len "Py_buffer.len"), [`itemsize`](#c.Py_buffer.itemsize "Py_buffer.itemsize"), [`ndim`](#c.Py_buffer.ndim "Py_buffer.ndim"). ### readonly, format `PyBUF_WRITABLE` Controls the [`readonly`](#c.Py_buffer.readonly "Py_buffer.readonly") field. If set, the exporter MUST provide a writable buffer or else report failure. Otherwise, the exporter MAY provide either a read-only or writable buffer, but the choice MUST be consistent for all consumers. `PyBUF_FORMAT` Controls the [`format`](#c.Py_buffer.format "Py_buffer.format") field. If set, this field MUST be filled in correctly. Otherwise, this field MUST be `NULL`. [`PyBUF_WRITABLE`](#c.PyBUF_WRITABLE "PyBUF_WRITABLE") can be |’d to any of the flags in the next section. Since [`PyBUF_SIMPLE`](#c.PyBUF_SIMPLE "PyBUF_SIMPLE") is defined as 0, [`PyBUF_WRITABLE`](#c.PyBUF_WRITABLE "PyBUF_WRITABLE") can be used as a stand-alone flag to request a simple writable buffer. [`PyBUF_FORMAT`](#c.PyBUF_FORMAT "PyBUF_FORMAT") can be |’d to any of the flags except [`PyBUF_SIMPLE`](#c.PyBUF_SIMPLE "PyBUF_SIMPLE"). The latter already implies format `B` (unsigned bytes). ### shape, strides, suboffsets The flags that control the logical structure of the memory are listed in decreasing order of complexity. Note that each flag contains all bits of the flags below it. | Request | shape | strides | suboffsets | | --- | --- | --- | --- | | `PyBUF_INDIRECT` | yes | yes | if needed | | `PyBUF_STRIDES` | yes | yes | NULL | | `PyBUF_ND` | yes | NULL | NULL | | `PyBUF_SIMPLE` | NULL | NULL | NULL | ### contiguity requests C or Fortran [contiguity](../glossary#term-contiguous) can be explicitly requested, with and without stride information. Without stride information, the buffer must be C-contiguous. | Request | shape | strides | suboffsets | contig | | --- | --- | --- | --- | --- | | `PyBUF_C_CONTIGUOUS` | yes | yes | NULL | C | | `PyBUF_F_CONTIGUOUS` | yes | yes | NULL | F | | `PyBUF_ANY_CONTIGUOUS` | yes | yes | NULL | C or F | | [`PyBUF_ND`](#c.PyBUF_ND "PyBUF_ND") | yes | NULL | NULL | C | ### compound requests All possible requests are fully defined by some combination of the flags in the previous section. For convenience, the buffer protocol provides frequently used combinations as single flags. In the following table *U* stands for undefined contiguity. The consumer would have to call [`PyBuffer_IsContiguous()`](#c.PyBuffer_IsContiguous "PyBuffer_IsContiguous") to determine contiguity. | Request | shape | strides | suboffsets | contig | readonly | format | | --- | --- | --- | --- | --- | --- | --- | | `PyBUF_FULL` | yes | yes | if needed | U | 0 | yes | | `PyBUF_FULL_RO` | yes | yes | if needed | U | 1 or 0 | yes | | `PyBUF_RECORDS` | yes | yes | NULL | U | 0 | yes | | `PyBUF_RECORDS_RO` | yes | yes | NULL | U | 1 or 0 | yes | | `PyBUF_STRIDED` | yes | yes | NULL | U | 0 | NULL | | `PyBUF_STRIDED_RO` | yes | yes | NULL | U | 1 or 0 | NULL | | `PyBUF_CONTIG` | yes | NULL | NULL | C | 0 | NULL | | `PyBUF_CONTIG_RO` | yes | NULL | NULL | C | 1 or 0 | NULL | Complex arrays -------------- ### NumPy-style: shape and strides The logical structure of NumPy-style arrays is defined by [`itemsize`](#c.Py_buffer.itemsize "Py_buffer.itemsize"), [`ndim`](#c.Py_buffer.ndim "Py_buffer.ndim"), [`shape`](#c.Py_buffer.shape "Py_buffer.shape") and [`strides`](#c.Py_buffer.strides "Py_buffer.strides"). If `ndim == 0`, the memory location pointed to by [`buf`](#c.Py_buffer.buf "Py_buffer.buf") is interpreted as a scalar of size [`itemsize`](#c.Py_buffer.itemsize "Py_buffer.itemsize"). In that case, both [`shape`](#c.Py_buffer.shape "Py_buffer.shape") and [`strides`](#c.Py_buffer.strides "Py_buffer.strides") are `NULL`. If [`strides`](#c.Py_buffer.strides "Py_buffer.strides") is `NULL`, the array is interpreted as a standard n-dimensional C-array. Otherwise, the consumer must access an n-dimensional array as follows: ``` ptr = (char *)buf + indices[0] * strides[0] + ... + indices[n-1] * strides[n-1]; item = *((typeof(item) *)ptr); ``` As noted above, [`buf`](#c.Py_buffer.buf "Py_buffer.buf") can point to any location within the actual memory block. An exporter can check the validity of a buffer with this function: ``` def verify_structure(memlen, itemsize, ndim, shape, strides, offset): """Verify that the parameters represent a valid array within the bounds of the allocated memory: char *mem: start of the physical memory block memlen: length of the physical memory block offset: (char *)buf - mem """ if offset % itemsize: return False if offset < 0 or offset+itemsize > memlen: return False if any(v % itemsize for v in strides): return False if ndim <= 0: return ndim == 0 and not shape and not strides if 0 in shape: return True imin = sum(strides[j]*(shape[j]-1) for j in range(ndim) if strides[j] <= 0) imax = sum(strides[j]*(shape[j]-1) for j in range(ndim) if strides[j] > 0) return 0 <= offset+imin and offset+imax+itemsize <= memlen ``` ### PIL-style: shape, strides and suboffsets In addition to the regular items, PIL-style arrays can contain pointers that must be followed in order to get to the next element in a dimension. For example, the regular three-dimensional C-array `char v[2][2][3]` can also be viewed as an array of 2 pointers to 2 two-dimensional arrays: `char (*v[2])[2][3]`. In suboffsets representation, those two pointers can be embedded at the start of [`buf`](#c.Py_buffer.buf "Py_buffer.buf"), pointing to two `char x[2][3]` arrays that can be located anywhere in memory. Here is a function that returns a pointer to the element in an N-D array pointed to by an N-dimensional index when there are both non-`NULL` strides and suboffsets: ``` void *get_item_pointer(int ndim, void *buf, Py_ssize_t *strides, Py_ssize_t *suboffsets, Py_ssize_t *indices) { char *pointer = (char*)buf; int i; for (i = 0; i < ndim; i++) { pointer += strides[i] * indices[i]; if (suboffsets[i] >=0 ) { pointer = *((char**)pointer) + suboffsets[i]; } } return (void*)pointer; } ``` Buffer-related functions ------------------------ `int PyObject_CheckBuffer(PyObject *obj)` Return `1` if *obj* supports the buffer interface otherwise `0`. When `1` is returned, it doesn’t guarantee that [`PyObject_GetBuffer()`](#c.PyObject_GetBuffer "PyObject_GetBuffer") will succeed. This function always succeeds. `int PyObject_GetBuffer(PyObject *exporter, Py_buffer *view, int flags)` Send a request to *exporter* to fill in *view* as specified by *flags*. If the exporter cannot provide a buffer of the exact type, it MUST raise `PyExc_BufferError`, set `view->obj` to `NULL` and return `-1`. On success, fill in *view*, set `view->obj` to a new reference to *exporter* and return 0. In the case of chained buffer providers that redirect requests to a single object, `view->obj` MAY refer to this object instead of *exporter* (See [Buffer Object Structures](typeobj#buffer-structs)). Successful calls to [`PyObject_GetBuffer()`](#c.PyObject_GetBuffer "PyObject_GetBuffer") must be paired with calls to [`PyBuffer_Release()`](#c.PyBuffer_Release "PyBuffer_Release"), similar to `malloc()` and `free()`. Thus, after the consumer is done with the buffer, [`PyBuffer_Release()`](#c.PyBuffer_Release "PyBuffer_Release") must be called exactly once. `void PyBuffer_Release(Py_buffer *view)` Release the buffer *view* and decrement the reference count for `view->obj`. This function MUST be called when the buffer is no longer being used, otherwise reference leaks may occur. It is an error to call this function on a buffer that was not obtained via [`PyObject_GetBuffer()`](#c.PyObject_GetBuffer "PyObject_GetBuffer"). `Py_ssize_t PyBuffer_SizeFromFormat(const char *format)` Return the implied [`itemsize`](#c.Py_buffer.itemsize "Py_buffer.itemsize") from [`format`](#c.Py_buffer.format "Py_buffer.format"). On error, raise an exception and return -1. New in version 3.9. `int PyBuffer_IsContiguous(Py_buffer *view, char order)` Return `1` if the memory defined by the *view* is C-style (*order* is `'C'`) or Fortran-style (*order* is `'F'`) [contiguous](../glossary#term-contiguous) or either one (*order* is `'A'`). Return `0` otherwise. This function always succeeds. `void* PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices)` Get the memory area pointed to by the *indices* inside the given *view*. *indices* must point to an array of `view->ndim` indices. `int PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort)` Copy contiguous *len* bytes from *buf* to *view*. *fort* can be `'C'` or `'F'` (for C-style or Fortran-style ordering). `0` is returned on success, `-1` on error. `int PyBuffer_ToContiguous(void *buf, Py_buffer *src, Py_ssize_t len, char order)` Copy *len* bytes from *src* to its contiguous representation in *buf*. *order* can be `'C'` or `'F'` or `'A'` (for C-style or Fortran-style ordering or either one). `0` is returned on success, `-1` on error. This function fails if *len* != *src->len*. `void PyBuffer_FillContiguousStrides(int ndims, Py_ssize_t *shape, Py_ssize_t *strides, int itemsize, char order)` Fill the *strides* array with byte-strides of a [contiguous](../glossary#term-contiguous) (C-style if *order* is `'C'` or Fortran-style if *order* is `'F'`) array of the given shape with the given number of bytes per element. `int PyBuffer_FillInfo(Py_buffer *view, PyObject *exporter, void *buf, Py_ssize_t len, int readonly, int flags)` Handle buffer requests for an exporter that wants to expose *buf* of size *len* with writability set according to *readonly*. *buf* is interpreted as a sequence of unsigned bytes. The *flags* argument indicates the request type. This function always fills in *view* as specified by flags, unless *buf* has been designated as read-only and [`PyBUF_WRITABLE`](#c.PyBUF_WRITABLE "PyBUF_WRITABLE") is set in *flags*. On success, set `view->obj` to a new reference to *exporter* and return 0. Otherwise, raise `PyExc_BufferError`, set `view->obj` to `NULL` and return `-1`; If this function is used as part of a [getbufferproc](typeobj#buffer-structs), *exporter* MUST be set to the exporting object and *flags* must be passed unmodified. Otherwise, *exporter* MUST be `NULL`.
programming_docs
python Codec registry and support functions Codec registry and support functions ==================================== `int PyCodec_Register(PyObject *search_function)` Register a new codec search function. As side effect, this tries to load the `encodings` package, if not yet done, to make sure that it is always first in the list of search functions. `int PyCodec_KnownEncoding(const char *encoding)` Return `1` or `0` depending on whether there is a registered codec for the given *encoding*. This function always succeeds. `PyObject* PyCodec_Encode(PyObject *object, const char *encoding, const char *errors)` *Return value: New reference.*Generic codec based encoding API. *object* is passed through the encoder function found for the given *encoding* using the error handling method defined by *errors*. *errors* may be `NULL` to use the default method defined for the codec. Raises a [`LookupError`](../library/exceptions#LookupError "LookupError") if no encoder can be found. `PyObject* PyCodec_Decode(PyObject *object, const char *encoding, const char *errors)` *Return value: New reference.*Generic codec based decoding API. *object* is passed through the decoder function found for the given *encoding* using the error handling method defined by *errors*. *errors* may be `NULL` to use the default method defined for the codec. Raises a [`LookupError`](../library/exceptions#LookupError "LookupError") if no encoder can be found. Codec lookup API ---------------- In the following functions, the *encoding* string is looked up converted to all lower-case characters, which makes encodings looked up through this mechanism effectively case-insensitive. If no codec is found, a [`KeyError`](../library/exceptions#KeyError "KeyError") is set and `NULL` returned. `PyObject* PyCodec_Encoder(const char *encoding)` *Return value: New reference.*Get an encoder function for the given *encoding*. `PyObject* PyCodec_Decoder(const char *encoding)` *Return value: New reference.*Get a decoder function for the given *encoding*. `PyObject* PyCodec_IncrementalEncoder(const char *encoding, const char *errors)` *Return value: New reference.*Get an [`IncrementalEncoder`](../library/codecs#codecs.IncrementalEncoder "codecs.IncrementalEncoder") object for the given *encoding*. `PyObject* PyCodec_IncrementalDecoder(const char *encoding, const char *errors)` *Return value: New reference.*Get an [`IncrementalDecoder`](../library/codecs#codecs.IncrementalDecoder "codecs.IncrementalDecoder") object for the given *encoding*. `PyObject* PyCodec_StreamReader(const char *encoding, PyObject *stream, const char *errors)` *Return value: New reference.*Get a [`StreamReader`](../library/codecs#codecs.StreamReader "codecs.StreamReader") factory function for the given *encoding*. `PyObject* PyCodec_StreamWriter(const char *encoding, PyObject *stream, const char *errors)` *Return value: New reference.*Get a [`StreamWriter`](../library/codecs#codecs.StreamWriter "codecs.StreamWriter") factory function for the given *encoding*. Registry API for Unicode encoding error handlers ------------------------------------------------ `int PyCodec_RegisterError(const char *name, PyObject *error)` Register the error handling callback function *error* under the given *name*. This callback function will be called by a codec when it encounters unencodable characters/undecodable bytes and *name* is specified as the error parameter in the call to the encode/decode function. The callback gets a single argument, an instance of [`UnicodeEncodeError`](../library/exceptions#UnicodeEncodeError "UnicodeEncodeError"), [`UnicodeDecodeError`](../library/exceptions#UnicodeDecodeError "UnicodeDecodeError") or [`UnicodeTranslateError`](../library/exceptions#UnicodeTranslateError "UnicodeTranslateError") that holds information about the problematic sequence of characters or bytes and their offset in the original string (see [Unicode Exception Objects](exceptions#unicodeexceptions) for functions to extract this information). The callback must either raise the given exception, or return a two-item tuple containing the replacement for the problematic sequence, and an integer giving the offset in the original string at which encoding/decoding should be resumed. Return `0` on success, `-1` on error. `PyObject* PyCodec_LookupError(const char *name)` *Return value: New reference.*Lookup the error handling callback function registered under *name*. As a special case `NULL` can be passed, in which case the error handling callback for “strict” will be returned. `PyObject* PyCodec_StrictErrors(PyObject *exc)` *Return value: Always NULL.*Raise *exc* as an exception. `PyObject* PyCodec_IgnoreErrors(PyObject *exc)` *Return value: New reference.*Ignore the unicode error, skipping the faulty input. `PyObject* PyCodec_ReplaceErrors(PyObject *exc)` *Return value: New reference.*Replace the unicode encode error with `?` or `U+FFFD`. `PyObject* PyCodec_XMLCharRefReplaceErrors(PyObject *exc)` *Return value: New reference.*Replace the unicode encode error with XML character references. `PyObject* PyCodec_BackslashReplaceErrors(PyObject *exc)` *Return value: New reference.*Replace the unicode encode error with backslash escapes (`\x`, `\u` and `\U`). `PyObject* PyCodec_NameReplaceErrors(PyObject *exc)` *Return value: New reference.*Replace the unicode encode error with `\N{...}` escapes. New in version 3.5. python Byte Array Objects Byte Array Objects ================== `PyByteArrayObject` This subtype of [`PyObject`](structures#c.PyObject "PyObject") represents a Python bytearray object. `PyTypeObject PyByteArray_Type` This instance of [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject") represents the Python bytearray type; it is the same object as [`bytearray`](../library/stdtypes#bytearray "bytearray") in the Python layer. Type check macros ----------------- `int PyByteArray_Check(PyObject *o)` Return true if the object *o* is a bytearray object or an instance of a subtype of the bytearray type. This function always succeeds. `int PyByteArray_CheckExact(PyObject *o)` Return true if the object *o* is a bytearray object, but not an instance of a subtype of the bytearray type. This function always succeeds. Direct API functions -------------------- `PyObject* PyByteArray_FromObject(PyObject *o)` *Return value: New reference.*Return a new bytearray object from any object, *o*, that implements the [buffer protocol](buffer#bufferobjects). `PyObject* PyByteArray_FromStringAndSize(const char *string, Py_ssize_t len)` *Return value: New reference.*Create a new bytearray object from *string* and its length, *len*. On failure, `NULL` is returned. `PyObject* PyByteArray_Concat(PyObject *a, PyObject *b)` *Return value: New reference.*Concat bytearrays *a* and *b* and return a new bytearray with the result. `Py_ssize_t PyByteArray_Size(PyObject *bytearray)` Return the size of *bytearray* after checking for a `NULL` pointer. `char* PyByteArray_AsString(PyObject *bytearray)` Return the contents of *bytearray* as a char array after checking for a `NULL` pointer. The returned array always has an extra null byte appended. `int PyByteArray_Resize(PyObject *bytearray, Py_ssize_t len)` Resize the internal buffer of *bytearray* to *len*. Macros ------ These macros trade safety for speed and they don’t check pointers. `char* PyByteArray_AS_STRING(PyObject *bytearray)` Macro version of [`PyByteArray_AsString()`](#c.PyByteArray_AsString "PyByteArray_AsString"). `Py_ssize_t PyByteArray_GET_SIZE(PyObject *bytearray)` Macro version of [`PyByteArray_Size()`](#c.PyByteArray_Size "PyByteArray_Size"). python DateTime Objects DateTime Objects ================ Various date and time objects are supplied by the [`datetime`](../library/datetime#module-datetime "datetime: Basic date and time types.") module. Before using any of these functions, the header file `datetime.h` must be included in your source (note that this is not included by `Python.h`), and the macro `PyDateTime_IMPORT` must be invoked, usually as part of the module initialisation function. The macro puts a pointer to a C structure into a static variable, `PyDateTimeAPI`, that is used by the following macros. Macro for access to the UTC singleton: `PyObject* PyDateTime_TimeZone_UTC` Returns the time zone singleton representing UTC, the same object as [`datetime.timezone.utc`](../library/datetime#datetime.timezone.utc "datetime.timezone.utc"). New in version 3.7. Type-check macros: `int PyDate_Check(PyObject *ob)` Return true if *ob* is of type `PyDateTime_DateType` or a subtype of `PyDateTime_DateType`. *ob* must not be `NULL`. This function always succeeds. `int PyDate_CheckExact(PyObject *ob)` Return true if *ob* is of type `PyDateTime_DateType`. *ob* must not be `NULL`. This function always succeeds. `int PyDateTime_Check(PyObject *ob)` Return true if *ob* is of type `PyDateTime_DateTimeType` or a subtype of `PyDateTime_DateTimeType`. *ob* must not be `NULL`. This function always succeeds. `int PyDateTime_CheckExact(PyObject *ob)` Return true if *ob* is of type `PyDateTime_DateTimeType`. *ob* must not be `NULL`. This function always succeeds. `int PyTime_Check(PyObject *ob)` Return true if *ob* is of type `PyDateTime_TimeType` or a subtype of `PyDateTime_TimeType`. *ob* must not be `NULL`. This function always succeeds. `int PyTime_CheckExact(PyObject *ob)` Return true if *ob* is of type `PyDateTime_TimeType`. *ob* must not be `NULL`. This function always succeeds. `int PyDelta_Check(PyObject *ob)` Return true if *ob* is of type `PyDateTime_DeltaType` or a subtype of `PyDateTime_DeltaType`. *ob* must not be `NULL`. This function always succeeds. `int PyDelta_CheckExact(PyObject *ob)` Return true if *ob* is of type `PyDateTime_DeltaType`. *ob* must not be `NULL`. This function always succeeds. `int PyTZInfo_Check(PyObject *ob)` Return true if *ob* is of type `PyDateTime_TZInfoType` or a subtype of `PyDateTime_TZInfoType`. *ob* must not be `NULL`. This function always succeeds. `int PyTZInfo_CheckExact(PyObject *ob)` Return true if *ob* is of type `PyDateTime_TZInfoType`. *ob* must not be `NULL`. This function always succeeds. Macros to create objects: `PyObject* PyDate_FromDate(int year, int month, int day)` *Return value: New reference.*Return a [`datetime.date`](../library/datetime#datetime.date "datetime.date") object with the specified year, month and day. `PyObject* PyDateTime_FromDateAndTime(int year, int month, int day, int hour, int minute, int second, int usecond)` *Return value: New reference.*Return a [`datetime.datetime`](../library/datetime#datetime.datetime "datetime.datetime") object with the specified year, month, day, hour, minute, second and microsecond. `PyObject* PyDateTime_FromDateAndTimeAndFold(int year, int month, int day, int hour, int minute, int second, int usecond, int fold)` *Return value: New reference.*Return a [`datetime.datetime`](../library/datetime#datetime.datetime "datetime.datetime") object with the specified year, month, day, hour, minute, second, microsecond and fold. New in version 3.6. `PyObject* PyTime_FromTime(int hour, int minute, int second, int usecond)` *Return value: New reference.*Return a [`datetime.time`](../library/datetime#datetime.time "datetime.time") object with the specified hour, minute, second and microsecond. `PyObject* PyTime_FromTimeAndFold(int hour, int minute, int second, int usecond, int fold)` *Return value: New reference.*Return a [`datetime.time`](../library/datetime#datetime.time "datetime.time") object with the specified hour, minute, second, microsecond and fold. New in version 3.6. `PyObject* PyDelta_FromDSU(int days, int seconds, int useconds)` *Return value: New reference.*Return a [`datetime.timedelta`](../library/datetime#datetime.timedelta "datetime.timedelta") object representing the given number of days, seconds and microseconds. Normalization is performed so that the resulting number of microseconds and seconds lie in the ranges documented for [`datetime.timedelta`](../library/datetime#datetime.timedelta "datetime.timedelta") objects. `PyObject* PyTimeZone_FromOffset(PyDateTime_DeltaType* offset)` *Return value: New reference.*Return a [`datetime.timezone`](../library/datetime#datetime.timezone "datetime.timezone") object with an unnamed fixed offset represented by the *offset* argument. New in version 3.7. `PyObject* PyTimeZone_FromOffsetAndName(PyDateTime_DeltaType* offset, PyUnicode* name)` *Return value: New reference.*Return a [`datetime.timezone`](../library/datetime#datetime.timezone "datetime.timezone") object with a fixed offset represented by the *offset* argument and with tzname *name*. New in version 3.7. Macros to extract fields from date objects. The argument must be an instance of `PyDateTime_Date`, including subclasses (such as `PyDateTime_DateTime`). The argument must not be `NULL`, and the type is not checked: `int PyDateTime_GET_YEAR(PyDateTime_Date *o)` Return the year, as a positive int. `int PyDateTime_GET_MONTH(PyDateTime_Date *o)` Return the month, as an int from 1 through 12. `int PyDateTime_GET_DAY(PyDateTime_Date *o)` Return the day, as an int from 1 through 31. Macros to extract fields from datetime objects. The argument must be an instance of `PyDateTime_DateTime`, including subclasses. The argument must not be `NULL`, and the type is not checked: `int PyDateTime_DATE_GET_HOUR(PyDateTime_DateTime *o)` Return the hour, as an int from 0 through 23. `int PyDateTime_DATE_GET_MINUTE(PyDateTime_DateTime *o)` Return the minute, as an int from 0 through 59. `int PyDateTime_DATE_GET_SECOND(PyDateTime_DateTime *o)` Return the second, as an int from 0 through 59. `int PyDateTime_DATE_GET_MICROSECOND(PyDateTime_DateTime *o)` Return the microsecond, as an int from 0 through 999999. `int PyDateTime_DATE_GET_FOLD(PyDateTime_DateTime *o)` Return the fold, as an int from 0 through 1. New in version 3.6. Macros to extract fields from time objects. The argument must be an instance of `PyDateTime_Time`, including subclasses. The argument must not be `NULL`, and the type is not checked: `int PyDateTime_TIME_GET_HOUR(PyDateTime_Time *o)` Return the hour, as an int from 0 through 23. `int PyDateTime_TIME_GET_MINUTE(PyDateTime_Time *o)` Return the minute, as an int from 0 through 59. `int PyDateTime_TIME_GET_SECOND(PyDateTime_Time *o)` Return the second, as an int from 0 through 59. `int PyDateTime_TIME_GET_MICROSECOND(PyDateTime_Time *o)` Return the microsecond, as an int from 0 through 999999. `int PyDateTime_TIME_GET_FOLD(PyDateTime_Time *o)` Return the fold, as an int from 0 through 1. New in version 3.6. Macros to extract fields from time delta objects. The argument must be an instance of `PyDateTime_Delta`, including subclasses. The argument must not be `NULL`, and the type is not checked: `int PyDateTime_DELTA_GET_DAYS(PyDateTime_Delta *o)` Return the number of days, as an int from -999999999 to 999999999. New in version 3.3. `int PyDateTime_DELTA_GET_SECONDS(PyDateTime_Delta *o)` Return the number of seconds, as an int from 0 through 86399. New in version 3.3. `int PyDateTime_DELTA_GET_MICROSECONDS(PyDateTime_Delta *o)` Return the number of microseconds, as an int from 0 through 999999. New in version 3.3. Macros for the convenience of modules implementing the DB API: `PyObject* PyDateTime_FromTimestamp(PyObject *args)` *Return value: New reference.*Create and return a new [`datetime.datetime`](../library/datetime#datetime.datetime "datetime.datetime") object given an argument tuple suitable for passing to [`datetime.datetime.fromtimestamp()`](../library/datetime#datetime.datetime.fromtimestamp "datetime.datetime.fromtimestamp"). `PyObject* PyDate_FromTimestamp(PyObject *args)` *Return value: New reference.*Create and return a new [`datetime.date`](../library/datetime#datetime.date "datetime.date") object given an argument tuple suitable for passing to [`datetime.date.fromtimestamp()`](../library/datetime#datetime.date.fromtimestamp "datetime.date.fromtimestamp"). python Set Objects Set Objects =========== This section details the public API for [`set`](../library/stdtypes#set "set") and [`frozenset`](../library/stdtypes#frozenset "frozenset") objects. Any functionality not listed below is best accessed using either the abstract object protocol (including [`PyObject_CallMethod()`](call#c.PyObject_CallMethod "PyObject_CallMethod"), [`PyObject_RichCompareBool()`](object#c.PyObject_RichCompareBool "PyObject_RichCompareBool"), [`PyObject_Hash()`](object#c.PyObject_Hash "PyObject_Hash"), [`PyObject_Repr()`](object#c.PyObject_Repr "PyObject_Repr"), [`PyObject_IsTrue()`](object#c.PyObject_IsTrue "PyObject_IsTrue"), [`PyObject_Print()`](object#c.PyObject_Print "PyObject_Print"), and [`PyObject_GetIter()`](object#c.PyObject_GetIter "PyObject_GetIter")) or the abstract number protocol (including [`PyNumber_And()`](number#c.PyNumber_And "PyNumber_And"), [`PyNumber_Subtract()`](number#c.PyNumber_Subtract "PyNumber_Subtract"), [`PyNumber_Or()`](number#c.PyNumber_Or "PyNumber_Or"), [`PyNumber_Xor()`](number#c.PyNumber_Xor "PyNumber_Xor"), [`PyNumber_InPlaceAnd()`](number#c.PyNumber_InPlaceAnd "PyNumber_InPlaceAnd"), [`PyNumber_InPlaceSubtract()`](number#c.PyNumber_InPlaceSubtract "PyNumber_InPlaceSubtract"), [`PyNumber_InPlaceOr()`](number#c.PyNumber_InPlaceOr "PyNumber_InPlaceOr"), and [`PyNumber_InPlaceXor()`](number#c.PyNumber_InPlaceXor "PyNumber_InPlaceXor")). `PySetObject` This subtype of [`PyObject`](structures#c.PyObject "PyObject") is used to hold the internal data for both [`set`](../library/stdtypes#set "set") and [`frozenset`](../library/stdtypes#frozenset "frozenset") objects. It is like a [`PyDictObject`](dict#c.PyDictObject "PyDictObject") in that it is a fixed size for small sets (much like tuple storage) and will point to a separate, variable sized block of memory for medium and large sized sets (much like list storage). None of the fields of this structure should be considered public and all are subject to change. All access should be done through the documented API rather than by manipulating the values in the structure. `PyTypeObject PySet_Type` This is an instance of [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject") representing the Python [`set`](../library/stdtypes#set "set") type. `PyTypeObject PyFrozenSet_Type` This is an instance of [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject") representing the Python [`frozenset`](../library/stdtypes#frozenset "frozenset") type. The following type check macros work on pointers to any Python object. Likewise, the constructor functions work with any iterable Python object. `int PySet_Check(PyObject *p)` Return true if *p* is a [`set`](../library/stdtypes#set "set") object or an instance of a subtype. This function always succeeds. `int PyFrozenSet_Check(PyObject *p)` Return true if *p* is a [`frozenset`](../library/stdtypes#frozenset "frozenset") object or an instance of a subtype. This function always succeeds. `int PyAnySet_Check(PyObject *p)` Return true if *p* is a [`set`](../library/stdtypes#set "set") object, a [`frozenset`](../library/stdtypes#frozenset "frozenset") object, or an instance of a subtype. This function always succeeds. `int PyAnySet_CheckExact(PyObject *p)` Return true if *p* is a [`set`](../library/stdtypes#set "set") object or a [`frozenset`](../library/stdtypes#frozenset "frozenset") object but not an instance of a subtype. This function always succeeds. `int PyFrozenSet_CheckExact(PyObject *p)` Return true if *p* is a [`frozenset`](../library/stdtypes#frozenset "frozenset") object but not an instance of a subtype. This function always succeeds. `PyObject* PySet_New(PyObject *iterable)` *Return value: New reference.*Return a new [`set`](../library/stdtypes#set "set") containing objects returned by the *iterable*. The *iterable* may be `NULL` to create a new empty set. Return the new set on success or `NULL` on failure. Raise [`TypeError`](../library/exceptions#TypeError "TypeError") if *iterable* is not actually iterable. The constructor is also useful for copying a set (`c=set(s)`). `PyObject* PyFrozenSet_New(PyObject *iterable)` *Return value: New reference.*Return a new [`frozenset`](../library/stdtypes#frozenset "frozenset") containing objects returned by the *iterable*. The *iterable* may be `NULL` to create a new empty frozenset. Return the new set on success or `NULL` on failure. Raise [`TypeError`](../library/exceptions#TypeError "TypeError") if *iterable* is not actually iterable. The following functions and macros are available for instances of [`set`](../library/stdtypes#set "set") or [`frozenset`](../library/stdtypes#frozenset "frozenset") or instances of their subtypes. `Py_ssize_t PySet_Size(PyObject *anyset)` Return the length of a [`set`](../library/stdtypes#set "set") or [`frozenset`](../library/stdtypes#frozenset "frozenset") object. Equivalent to `len(anyset)`. Raises a `PyExc_SystemError` if *anyset* is not a [`set`](../library/stdtypes#set "set"), [`frozenset`](../library/stdtypes#frozenset "frozenset"), or an instance of a subtype. `Py_ssize_t PySet_GET_SIZE(PyObject *anyset)` Macro form of [`PySet_Size()`](#c.PySet_Size "PySet_Size") without error checking. `int PySet_Contains(PyObject *anyset, PyObject *key)` Return `1` if found, `0` if not found, and `-1` if an error is encountered. Unlike the Python [`__contains__()`](../reference/datamodel#object.__contains__ "object.__contains__") method, this function does not automatically convert unhashable sets into temporary frozensets. Raise a [`TypeError`](../library/exceptions#TypeError "TypeError") if the *key* is unhashable. Raise `PyExc_SystemError` if *anyset* is not a [`set`](../library/stdtypes#set "set"), [`frozenset`](../library/stdtypes#frozenset "frozenset"), or an instance of a subtype. `int PySet_Add(PyObject *set, PyObject *key)` Add *key* to a [`set`](../library/stdtypes#set "set") instance. Also works with [`frozenset`](../library/stdtypes#frozenset "frozenset") instances (like [`PyTuple_SetItem()`](tuple#c.PyTuple_SetItem "PyTuple_SetItem") it can be used to fill in the values of brand new frozensets before they are exposed to other code). Return `0` on success or `-1` on failure. Raise a [`TypeError`](../library/exceptions#TypeError "TypeError") if the *key* is unhashable. Raise a [`MemoryError`](../library/exceptions#MemoryError "MemoryError") if there is no room to grow. Raise a [`SystemError`](../library/exceptions#SystemError "SystemError") if *set* is not an instance of [`set`](../library/stdtypes#set "set") or its subtype. The following functions are available for instances of [`set`](../library/stdtypes#set "set") or its subtypes but not for instances of [`frozenset`](../library/stdtypes#frozenset "frozenset") or its subtypes. `int PySet_Discard(PyObject *set, PyObject *key)` Return `1` if found and removed, `0` if not found (no action taken), and `-1` if an error is encountered. Does not raise [`KeyError`](../library/exceptions#KeyError "KeyError") for missing keys. Raise a [`TypeError`](../library/exceptions#TypeError "TypeError") if the *key* is unhashable. Unlike the Python `discard()` method, this function does not automatically convert unhashable sets into temporary frozensets. Raise `PyExc_SystemError` if *set* is not an instance of [`set`](../library/stdtypes#set "set") or its subtype. `PyObject* PySet_Pop(PyObject *set)` *Return value: New reference.*Return a new reference to an arbitrary object in the *set*, and removes the object from the *set*. Return `NULL` on failure. Raise [`KeyError`](../library/exceptions#KeyError "KeyError") if the set is empty. Raise a [`SystemError`](../library/exceptions#SystemError "SystemError") if *set* is not an instance of [`set`](../library/stdtypes#set "set") or its subtype. `int PySet_Clear(PyObject *set)` Empty an existing set of all elements.
programming_docs
python Dictionary Objects Dictionary Objects ================== `PyDictObject` This subtype of [`PyObject`](structures#c.PyObject "PyObject") represents a Python dictionary object. `PyTypeObject PyDict_Type` This instance of [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject") represents the Python dictionary type. This is the same object as [`dict`](../library/stdtypes#dict "dict") in the Python layer. `int PyDict_Check(PyObject *p)` Return true if *p* is a dict object or an instance of a subtype of the dict type. This function always succeeds. `int PyDict_CheckExact(PyObject *p)` Return true if *p* is a dict object, but not an instance of a subtype of the dict type. This function always succeeds. `PyObject* PyDict_New()` *Return value: New reference.*Return a new empty dictionary, or `NULL` on failure. `PyObject* PyDictProxy_New(PyObject *mapping)` *Return value: New reference.*Return a [`types.MappingProxyType`](../library/types#types.MappingProxyType "types.MappingProxyType") object for a mapping which enforces read-only behavior. This is normally used to create a view to prevent modification of the dictionary for non-dynamic class types. `void PyDict_Clear(PyObject *p)` Empty an existing dictionary of all key-value pairs. `int PyDict_Contains(PyObject *p, PyObject *key)` Determine if dictionary *p* contains *key*. If an item in *p* is matches *key*, return `1`, otherwise return `0`. On error, return `-1`. This is equivalent to the Python expression `key in p`. `PyObject* PyDict_Copy(PyObject *p)` *Return value: New reference.*Return a new dictionary that contains the same key-value pairs as *p*. `int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val)` Insert *val* into the dictionary *p* with a key of *key*. *key* must be [hashable](../glossary#term-hashable); if it isn’t, [`TypeError`](../library/exceptions#TypeError "TypeError") will be raised. Return `0` on success or `-1` on failure. This function *does not* steal a reference to *val*. `int PyDict_SetItemString(PyObject *p, const char *key, PyObject *val)` Insert *val* into the dictionary *p* using *key* as a key. *key* should be a `const char*`. The key object is created using `PyUnicode_FromString(key)`. Return `0` on success or `-1` on failure. This function *does not* steal a reference to *val*. `int PyDict_DelItem(PyObject *p, PyObject *key)` Remove the entry in dictionary *p* with key *key*. *key* must be hashable; if it isn’t, [`TypeError`](../library/exceptions#TypeError "TypeError") is raised. If *key* is not in the dictionary, [`KeyError`](../library/exceptions#KeyError "KeyError") is raised. Return `0` on success or `-1` on failure. `int PyDict_DelItemString(PyObject *p, const char *key)` Remove the entry in dictionary *p* which has a key specified by the string *key*. If *key* is not in the dictionary, [`KeyError`](../library/exceptions#KeyError "KeyError") is raised. Return `0` on success or `-1` on failure. `PyObject* PyDict_GetItem(PyObject *p, PyObject *key)` *Return value: Borrowed reference.*Return the object from dictionary *p* which has a key *key*. Return `NULL` if the key *key* is not present, but *without* setting an exception. Note that exceptions which occur while calling [`__hash__()`](../reference/datamodel#object.__hash__ "object.__hash__") and [`__eq__()`](../reference/datamodel#object.__eq__ "object.__eq__") methods will get suppressed. To get error reporting use [`PyDict_GetItemWithError()`](#c.PyDict_GetItemWithError "PyDict_GetItemWithError") instead. `PyObject* PyDict_GetItemWithError(PyObject *p, PyObject *key)` *Return value: Borrowed reference.*Variant of [`PyDict_GetItem()`](#c.PyDict_GetItem "PyDict_GetItem") that does not suppress exceptions. Return `NULL` **with** an exception set if an exception occurred. Return `NULL` **without** an exception set if the key wasn’t present. `PyObject* PyDict_GetItemString(PyObject *p, const char *key)` *Return value: Borrowed reference.*This is the same as [`PyDict_GetItem()`](#c.PyDict_GetItem "PyDict_GetItem"), but *key* is specified as a `const char*`, rather than a [`PyObject*`](structures#c.PyObject "PyObject"). Note that exceptions which occur while calling [`__hash__()`](../reference/datamodel#object.__hash__ "object.__hash__") and [`__eq__()`](../reference/datamodel#object.__eq__ "object.__eq__") methods and creating a temporary string object will get suppressed. To get error reporting use [`PyDict_GetItemWithError()`](#c.PyDict_GetItemWithError "PyDict_GetItemWithError") instead. `PyObject* PyDict_SetDefault(PyObject *p, PyObject *key, PyObject *defaultobj)` *Return value: Borrowed reference.*This is the same as the Python-level [`dict.setdefault()`](../library/stdtypes#dict.setdefault "dict.setdefault"). If present, it returns the value corresponding to *key* from the dictionary *p*. If the key is not in the dict, it is inserted with value *defaultobj* and *defaultobj* is returned. This function evaluates the hash function of *key* only once, instead of evaluating it independently for the lookup and the insertion. New in version 3.4. `PyObject* PyDict_Items(PyObject *p)` *Return value: New reference.*Return a [`PyListObject`](list#c.PyListObject "PyListObject") containing all the items from the dictionary. `PyObject* PyDict_Keys(PyObject *p)` *Return value: New reference.*Return a [`PyListObject`](list#c.PyListObject "PyListObject") containing all the keys from the dictionary. `PyObject* PyDict_Values(PyObject *p)` *Return value: New reference.*Return a [`PyListObject`](list#c.PyListObject "PyListObject") containing all the values from the dictionary *p*. `Py_ssize_t PyDict_Size(PyObject *p)` Return the number of items in the dictionary. This is equivalent to `len(p)` on a dictionary. `int PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)` Iterate over all key-value pairs in the dictionary *p*. The [`Py_ssize_t`](intro#c.Py_ssize_t "Py_ssize_t") referred to by *ppos* must be initialized to `0` prior to the first call to this function to start the iteration; the function returns true for each pair in the dictionary, and false once all pairs have been reported. The parameters *pkey* and *pvalue* should either point to [`PyObject*`](structures#c.PyObject "PyObject") variables that will be filled in with each key and value, respectively, or may be `NULL`. Any references returned through them are borrowed. *ppos* should not be altered during iteration. Its value represents offsets within the internal dictionary structure, and since the structure is sparse, the offsets are not consecutive. For example: ``` PyObject *key, *value; Py_ssize_t pos = 0; while (PyDict_Next(self->dict, &pos, &key, &value)) { /* do something interesting with the values... */ ... } ``` The dictionary *p* should not be mutated during iteration. It is safe to modify the values of the keys as you iterate over the dictionary, but only so long as the set of keys does not change. For example: ``` PyObject *key, *value; Py_ssize_t pos = 0; while (PyDict_Next(self->dict, &pos, &key, &value)) { long i = PyLong_AsLong(value); if (i == -1 && PyErr_Occurred()) { return -1; } PyObject *o = PyLong_FromLong(i + 1); if (o == NULL) return -1; if (PyDict_SetItem(self->dict, key, o) < 0) { Py_DECREF(o); return -1; } Py_DECREF(o); } ``` `int PyDict_Merge(PyObject *a, PyObject *b, int override)` Iterate over mapping object *b* adding key-value pairs to dictionary *a*. *b* may be a dictionary, or any object supporting [`PyMapping_Keys()`](mapping#c.PyMapping_Keys "PyMapping_Keys") and [`PyObject_GetItem()`](object#c.PyObject_GetItem "PyObject_GetItem"). If *override* is true, existing pairs in *a* will be replaced if a matching key is found in *b*, otherwise pairs will only be added if there is not a matching key in *a*. Return `0` on success or `-1` if an exception was raised. `int PyDict_Update(PyObject *a, PyObject *b)` This is the same as `PyDict_Merge(a, b, 1)` in C, and is similar to `a.update(b)` in Python except that [`PyDict_Update()`](#c.PyDict_Update "PyDict_Update") doesn’t fall back to the iterating over a sequence of key value pairs if the second argument has no “keys” attribute. Return `0` on success or `-1` if an exception was raised. `int PyDict_MergeFromSeq2(PyObject *a, PyObject *seq2, int override)` Update or merge into dictionary *a*, from the key-value pairs in *seq2*. *seq2* must be an iterable object producing iterable objects of length 2, viewed as key-value pairs. In case of duplicate keys, the last wins if *override* is true, else the first wins. Return `0` on success or `-1` if an exception was raised. Equivalent Python (except for the return value): ``` def PyDict_MergeFromSeq2(a, seq2, override): for key, value in seq2: if override or key not in a: a[key] = value ``` python Complex Number Objects Complex Number Objects ====================== Python’s complex number objects are implemented as two distinct types when viewed from the C API: one is the Python object exposed to Python programs, and the other is a C structure which represents the actual complex number value. The API provides functions for working with both. Complex Numbers as C Structures ------------------------------- Note that the functions which accept these structures as parameters and return them as results do so *by value* rather than dereferencing them through pointers. This is consistent throughout the API. `Py_complex` The C structure which corresponds to the value portion of a Python complex number object. Most of the functions for dealing with complex number objects use structures of this type as input or output values, as appropriate. It is defined as: ``` typedef struct { double real; double imag; } Py_complex; ``` `Py_complex _Py_c_sum(Py_complex left, Py_complex right)` Return the sum of two complex numbers, using the C [`Py_complex`](#c.Py_complex "Py_complex") representation. `Py_complex _Py_c_diff(Py_complex left, Py_complex right)` Return the difference between two complex numbers, using the C [`Py_complex`](#c.Py_complex "Py_complex") representation. `Py_complex _Py_c_neg(Py_complex num)` Return the negation of the complex number *num*, using the C [`Py_complex`](#c.Py_complex "Py_complex") representation. `Py_complex _Py_c_prod(Py_complex left, Py_complex right)` Return the product of two complex numbers, using the C [`Py_complex`](#c.Py_complex "Py_complex") representation. `Py_complex _Py_c_quot(Py_complex dividend, Py_complex divisor)` Return the quotient of two complex numbers, using the C [`Py_complex`](#c.Py_complex "Py_complex") representation. If *divisor* is null, this method returns zero and sets `errno` to `EDOM`. `Py_complex _Py_c_pow(Py_complex num, Py_complex exp)` Return the exponentiation of *num* by *exp*, using the C [`Py_complex`](#c.Py_complex "Py_complex") representation. If *num* is null and *exp* is not a positive real number, this method returns zero and sets `errno` to `EDOM`. Complex Numbers as Python Objects --------------------------------- `PyComplexObject` This subtype of [`PyObject`](structures#c.PyObject "PyObject") represents a Python complex number object. `PyTypeObject PyComplex_Type` This instance of [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject") represents the Python complex number type. It is the same object as [`complex`](../library/functions#complex "complex") in the Python layer. `int PyComplex_Check(PyObject *p)` Return true if its argument is a [`PyComplexObject`](#c.PyComplexObject "PyComplexObject") or a subtype of [`PyComplexObject`](#c.PyComplexObject "PyComplexObject"). This function always succeeds. `int PyComplex_CheckExact(PyObject *p)` Return true if its argument is a [`PyComplexObject`](#c.PyComplexObject "PyComplexObject"), but not a subtype of [`PyComplexObject`](#c.PyComplexObject "PyComplexObject"). This function always succeeds. `PyObject* PyComplex_FromCComplex(Py_complex v)` *Return value: New reference.*Create a new Python complex number object from a C [`Py_complex`](#c.Py_complex "Py_complex") value. `PyObject* PyComplex_FromDoubles(double real, double imag)` *Return value: New reference.*Return a new [`PyComplexObject`](#c.PyComplexObject "PyComplexObject") object from *real* and *imag*. `double PyComplex_RealAsDouble(PyObject *op)` Return the real part of *op* as a C `double`. `double PyComplex_ImagAsDouble(PyObject *op)` Return the imaginary part of *op* as a C `double`. `Py_complex PyComplex_AsCComplex(PyObject *op)` Return the [`Py_complex`](#c.Py_complex "Py_complex") value of the complex number *op*. If *op* is not a Python complex number object but has a [`__complex__()`](../reference/datamodel#object.__complex__ "object.__complex__") method, this method will first be called to convert *op* to a Python complex number object. If `__complex__()` is not defined then it falls back to [`__float__()`](../reference/datamodel#object.__float__ "object.__float__"). If `__float__()` is not defined then it falls back to [`__index__()`](../reference/datamodel#object.__index__ "object.__index__"). Upon failure, this method returns `-1.0` as a real value. Changed in version 3.8: Use [`__index__()`](../reference/datamodel#object.__index__ "object.__index__") if available. python Cell Objects Cell Objects ============ “Cell” objects are used to implement variables referenced by multiple scopes. For each such variable, a cell object is created to store the value; the local variables of each stack frame that references the value contains a reference to the cells from outer scopes which also use that variable. When the value is accessed, the value contained in the cell is used instead of the cell object itself. This de-referencing of the cell object requires support from the generated byte-code; these are not automatically de-referenced when accessed. Cell objects are not likely to be useful elsewhere. `PyCellObject` The C structure used for cell objects. `PyTypeObject PyCell_Type` The type object corresponding to cell objects. `int PyCell_Check(ob)` Return true if *ob* is a cell object; *ob* must not be `NULL`. This function always succeeds. `PyObject* PyCell_New(PyObject *ob)` *Return value: New reference.*Create and return a new cell object containing the value *ob*. The parameter may be `NULL`. `PyObject* PyCell_Get(PyObject *cell)` *Return value: New reference.*Return the contents of the cell *cell*. `PyObject* PyCell_GET(PyObject *cell)` *Return value: Borrowed reference.*Return the contents of the cell *cell*, but without checking that *cell* is non-`NULL` and a cell object. `int PyCell_Set(PyObject *cell, PyObject *value)` Set the contents of the cell object *cell* to *value*. This releases the reference to any current content of the cell. *value* may be `NULL`. *cell* must be non-`NULL`; if it is not a cell object, `-1` will be returned. On success, `0` will be returned. `void PyCell_SET(PyObject *cell, PyObject *value)` Sets the value of the cell object *cell* to *value*. No reference counts are adjusted, and no checks are made for safety; *cell* must be non-`NULL` and must be a cell object. python Function Objects Function Objects ================ There are a few functions specific to Python functions. `PyFunctionObject` The C structure used for functions. `PyTypeObject PyFunction_Type` This is an instance of [`PyTypeObject`](type#c.PyTypeObject "PyTypeObject") and represents the Python function type. It is exposed to Python programmers as `types.FunctionType`. `int PyFunction_Check(PyObject *o)` Return true if *o* is a function object (has type [`PyFunction_Type`](#c.PyFunction_Type "PyFunction_Type")). The parameter must not be `NULL`. This function always succeeds. `PyObject* PyFunction_New(PyObject *code, PyObject *globals)` *Return value: New reference.*Return a new function object associated with the code object *code*. *globals* must be a dictionary with the global variables accessible to the function. The function’s docstring and name are retrieved from the code object. *\_\_module\_\_* is retrieved from *globals*. The argument defaults, annotations and closure are set to `NULL`. *\_\_qualname\_\_* is set to the same value as the function’s name. `PyObject* PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname)` *Return value: New reference.*As [`PyFunction_New()`](#c.PyFunction_New "PyFunction_New"), but also allows setting the function object’s `__qualname__` attribute. *qualname* should be a unicode object or `NULL`; if `NULL`, the `__qualname__` attribute is set to the same value as its `__name__` attribute. New in version 3.3. `PyObject* PyFunction_GetCode(PyObject *op)` *Return value: Borrowed reference.*Return the code object associated with the function object *op*. `PyObject* PyFunction_GetGlobals(PyObject *op)` *Return value: Borrowed reference.*Return the globals dictionary associated with the function object *op*. `PyObject* PyFunction_GetModule(PyObject *op)` *Return value: Borrowed reference.*Return the *\_\_module\_\_* attribute of the function object *op*. This is normally a string containing the module name, but can be set to any other object by Python code. `PyObject* PyFunction_GetDefaults(PyObject *op)` *Return value: Borrowed reference.*Return the argument default values of the function object *op*. This can be a tuple of arguments or `NULL`. `int PyFunction_SetDefaults(PyObject *op, PyObject *defaults)` Set the argument default values for the function object *op*. *defaults* must be `Py_None` or a tuple. Raises [`SystemError`](../library/exceptions#SystemError "SystemError") and returns `-1` on failure. `PyObject* PyFunction_GetClosure(PyObject *op)` *Return value: Borrowed reference.*Return the closure associated with the function object *op*. This can be `NULL` or a tuple of cell objects. `int PyFunction_SetClosure(PyObject *op, PyObject *closure)` Set the closure associated with the function object *op*. *closure* must be `Py_None` or a tuple of cell objects. Raises [`SystemError`](../library/exceptions#SystemError "SystemError") and returns `-1` on failure. `PyObject *PyFunction_GetAnnotations(PyObject *op)` *Return value: Borrowed reference.*Return the annotations of the function object *op*. This can be a mutable dictionary or `NULL`. `int PyFunction_SetAnnotations(PyObject *op, PyObject *annotations)` Set the annotations for the function object *op*. *annotations* must be a dictionary or `Py_None`. Raises [`SystemError`](../library/exceptions#SystemError "SystemError") and returns `-1` on failure. python Operating System Utilities Operating System Utilities ========================== `PyObject* PyOS_FSPath(PyObject *path)` *Return value: New reference.*Return the file system representation for *path*. If the object is a [`str`](../library/stdtypes#str "str") or [`bytes`](../library/stdtypes#bytes "bytes") object, then its reference count is incremented. If the object implements the [`os.PathLike`](../library/os#os.PathLike "os.PathLike") interface, then [`__fspath__()`](../library/os#os.PathLike.__fspath__ "os.PathLike.__fspath__") is returned as long as it is a [`str`](../library/stdtypes#str "str") or [`bytes`](../library/stdtypes#bytes "bytes") object. Otherwise [`TypeError`](../library/exceptions#TypeError "TypeError") is raised and `NULL` is returned. New in version 3.6. `int Py_FdIsInteractive(FILE *fp, const char *filename)` Return true (nonzero) if the standard I/O file *fp* with name *filename* is deemed interactive. This is the case for files for which `isatty(fileno(fp))` is true. If the global flag [`Py_InteractiveFlag`](init#c.Py_InteractiveFlag "Py_InteractiveFlag") is true, this function also returns true if the *filename* pointer is `NULL` or if the name is equal to one of the strings `'<stdin>'` or `'???'`. `void PyOS_BeforeFork()` Function to prepare some internal state before a process fork. This should be called before calling `fork()` or any similar function that clones the current process. Only available on systems where `fork()` is defined. Warning The C `fork()` call should only be made from the [“main” thread](init#fork-and-threads) (of the [“main” interpreter](init#sub-interpreter-support)). The same is true for `PyOS_BeforeFork()`. New in version 3.7. `void PyOS_AfterFork_Parent()` Function to update some internal state after a process fork. This should be called from the parent process after calling `fork()` or any similar function that clones the current process, regardless of whether process cloning was successful. Only available on systems where `fork()` is defined. Warning The C `fork()` call should only be made from the [“main” thread](init#fork-and-threads) (of the [“main” interpreter](init#sub-interpreter-support)). The same is true for `PyOS_AfterFork_Parent()`. New in version 3.7. `void PyOS_AfterFork_Child()` Function to update internal interpreter state after a process fork. This must be called from the child process after calling `fork()`, or any similar function that clones the current process, if there is any chance the process will call back into the Python interpreter. Only available on systems where `fork()` is defined. Warning The C `fork()` call should only be made from the [“main” thread](init#fork-and-threads) (of the [“main” interpreter](init#sub-interpreter-support)). The same is true for `PyOS_AfterFork_Child()`. New in version 3.7. See also [`os.register_at_fork()`](../library/os#os.register_at_fork "os.register_at_fork") allows registering custom Python functions to be called by [`PyOS_BeforeFork()`](#c.PyOS_BeforeFork "PyOS_BeforeFork"), [`PyOS_AfterFork_Parent()`](#c.PyOS_AfterFork_Parent "PyOS_AfterFork_Parent") and [`PyOS_AfterFork_Child()`](#c.PyOS_AfterFork_Child "PyOS_AfterFork_Child"). `void PyOS_AfterFork()` Function to update some internal state after a process fork; this should be called in the new process if the Python interpreter will continue to be used. If a new executable is loaded into the new process, this function does not need to be called. Deprecated since version 3.7: This function is superseded by [`PyOS_AfterFork_Child()`](#c.PyOS_AfterFork_Child "PyOS_AfterFork_Child"). `int PyOS_CheckStack()` Return true when the interpreter runs out of stack space. This is a reliable check, but is only available when `USE_STACKCHECK` is defined (currently on Windows using the Microsoft Visual C++ compiler). `USE_STACKCHECK` will be defined automatically; you should never change the definition in your own code. `PyOS_sighandler_t PyOS_getsig(int i)` Return the current signal handler for signal *i*. This is a thin wrapper around either `sigaction()` or `signal()`. Do not call those functions directly! `PyOS_sighandler_t` is a typedef alias for `void (*)(int)`. `PyOS_sighandler_t PyOS_setsig(int i, PyOS_sighandler_t h)` Set the signal handler for signal *i* to be *h*; return the old signal handler. This is a thin wrapper around either `sigaction()` or `signal()`. Do not call those functions directly! `PyOS_sighandler_t` is a typedef alias for `void (*)(int)`. `wchar_t* Py_DecodeLocale(const char* arg, size_t *size)` Decode a byte string from the locale encoding with the [surrogateescape error handler](../library/codecs#surrogateescape): undecodable bytes are decoded as characters in range U+DC80..U+DCFF. If a byte sequence can be decoded as a surrogate character, escape the bytes using the surrogateescape error handler instead of decoding them. Encoding, highest priority to lowest priority: * `UTF-8` on macOS, Android, and VxWorks; * `UTF-8` on Windows if [`Py_LegacyWindowsFSEncodingFlag`](init#c.Py_LegacyWindowsFSEncodingFlag "Py_LegacyWindowsFSEncodingFlag") is zero; * `UTF-8` if the Python UTF-8 mode is enabled; * `ASCII` if the `LC_CTYPE` locale is `"C"`, `nl_langinfo(CODESET)` returns the `ASCII` encoding (or an alias), and `mbstowcs()` and `wcstombs()` functions uses the `ISO-8859-1` encoding. * the current locale encoding. Return a pointer to a newly allocated wide character string, use [`PyMem_RawFree()`](memory#c.PyMem_RawFree "PyMem_RawFree") to free the memory. If size is not `NULL`, write the number of wide characters excluding the null character into `*size` Return `NULL` on decoding error or memory allocation error. If *size* is not `NULL`, `*size` is set to `(size_t)-1` on memory error or set to `(size_t)-2` on decoding error. Decoding errors should never happen, unless there is a bug in the C library. Use the [`Py_EncodeLocale()`](#c.Py_EncodeLocale "Py_EncodeLocale") function to encode the character string back to a byte string. See also The [`PyUnicode_DecodeFSDefaultAndSize()`](unicode#c.PyUnicode_DecodeFSDefaultAndSize "PyUnicode_DecodeFSDefaultAndSize") and [`PyUnicode_DecodeLocaleAndSize()`](unicode#c.PyUnicode_DecodeLocaleAndSize "PyUnicode_DecodeLocaleAndSize") functions. New in version 3.5. Changed in version 3.7: The function now uses the UTF-8 encoding in the UTF-8 mode. Changed in version 3.8: The function now uses the UTF-8 encoding on Windows if [`Py_LegacyWindowsFSEncodingFlag`](init#c.Py_LegacyWindowsFSEncodingFlag "Py_LegacyWindowsFSEncodingFlag") is zero; `char* Py_EncodeLocale(const wchar_t *text, size_t *error_pos)` Encode a wide character string to the locale encoding with the [surrogateescape error handler](../library/codecs#surrogateescape): surrogate characters in the range U+DC80..U+DCFF are converted to bytes 0x80..0xFF. Encoding, highest priority to lowest priority: * `UTF-8` on macOS, Android, and VxWorks; * `UTF-8` on Windows if [`Py_LegacyWindowsFSEncodingFlag`](init#c.Py_LegacyWindowsFSEncodingFlag "Py_LegacyWindowsFSEncodingFlag") is zero; * `UTF-8` if the Python UTF-8 mode is enabled; * `ASCII` if the `LC_CTYPE` locale is `"C"`, `nl_langinfo(CODESET)` returns the `ASCII` encoding (or an alias), and `mbstowcs()` and `wcstombs()` functions uses the `ISO-8859-1` encoding. * the current locale encoding. The function uses the UTF-8 encoding in the Python UTF-8 mode. Return a pointer to a newly allocated byte string, use [`PyMem_Free()`](memory#c.PyMem_Free "PyMem_Free") to free the memory. Return `NULL` on encoding error or memory allocation error. If error\_pos is not `NULL`, `*error_pos` is set to `(size_t)-1` on success, or set to the index of the invalid character on encoding error. Use the [`Py_DecodeLocale()`](#c.Py_DecodeLocale "Py_DecodeLocale") function to decode the bytes string back to a wide character string. See also The [`PyUnicode_EncodeFSDefault()`](unicode#c.PyUnicode_EncodeFSDefault "PyUnicode_EncodeFSDefault") and [`PyUnicode_EncodeLocale()`](unicode#c.PyUnicode_EncodeLocale "PyUnicode_EncodeLocale") functions. New in version 3.5. Changed in version 3.7: The function now uses the UTF-8 encoding in the UTF-8 mode. Changed in version 3.8: The function now uses the UTF-8 encoding on Windows if [`Py_LegacyWindowsFSEncodingFlag`](init#c.Py_LegacyWindowsFSEncodingFlag "Py_LegacyWindowsFSEncodingFlag") is zero.
programming_docs
python The Python Language Reference The Python Language Reference ============================= This reference manual describes the syntax and “core semantics” of the language. It is terse, but attempts to be exact and complete. The semantics of non-essential built-in object types and of the built-in functions and modules are described in [The Python Standard Library](../library/index#library-index). For an informal introduction to the language, see [The Python Tutorial](../tutorial/index#tutorial-index). For C or C++ programmers, two additional manuals exist: [Extending and Embedding the Python Interpreter](../extending/index#extending-index) describes the high-level picture of how to write a Python extension module, and the [Python/C API Reference Manual](../c-api/index#c-api-index) describes the interfaces available to C/C++ programmers in detail. * [1. Introduction](introduction) + [1.1. Alternate Implementations](introduction#alternate-implementations) + [1.2. Notation](introduction#notation) * [2. Lexical analysis](lexical_analysis) + [2.1. Line structure](lexical_analysis#line-structure) + [2.2. Other tokens](lexical_analysis#other-tokens) + [2.3. Identifiers and keywords](lexical_analysis#identifiers) + [2.4. Literals](lexical_analysis#literals) + [2.5. Operators](lexical_analysis#operators) + [2.6. Delimiters](lexical_analysis#delimiters) * [3. Data model](datamodel) + [3.1. Objects, values and types](datamodel#objects-values-and-types) + [3.2. The standard type hierarchy](datamodel#the-standard-type-hierarchy) + [3.3. Special method names](datamodel#special-method-names) + [3.4. Coroutines](datamodel#coroutines) * [4. Execution model](executionmodel) + [4.1. Structure of a program](executionmodel#structure-of-a-program) + [4.2. Naming and binding](executionmodel#naming-and-binding) + [4.3. Exceptions](executionmodel#exceptions) * [5. The import system](import) + [5.1. `importlib`](import#importlib) + [5.2. Packages](import#packages) + [5.3. Searching](import#searching) + [5.4. Loading](import#loading) + [5.5. The Path Based Finder](import#the-path-based-finder) + [5.6. Replacing the standard import system](import#replacing-the-standard-import-system) + [5.7. Package Relative Imports](import#package-relative-imports) + [5.8. Special considerations for \_\_main\_\_](import#special-considerations-for-main) + [5.9. Open issues](import#open-issues) + [5.10. References](import#references) * [6. Expressions](expressions) + [6.1. Arithmetic conversions](expressions#arithmetic-conversions) + [6.2. Atoms](expressions#atoms) + [6.3. Primaries](expressions#primaries) + [6.4. Await expression](expressions#await-expression) + [6.5. The power operator](expressions#the-power-operator) + [6.6. Unary arithmetic and bitwise operations](expressions#unary-arithmetic-and-bitwise-operations) + [6.7. Binary arithmetic operations](expressions#binary-arithmetic-operations) + [6.8. Shifting operations](expressions#shifting-operations) + [6.9. Binary bitwise operations](expressions#binary-bitwise-operations) + [6.10. Comparisons](expressions#comparisons) + [6.11. Boolean operations](expressions#boolean-operations) + [6.12. Assignment expressions](expressions#assignment-expressions) + [6.13. Conditional expressions](expressions#conditional-expressions) + [6.14. Lambdas](expressions#lambda) + [6.15. Expression lists](expressions#expression-lists) + [6.16. Evaluation order](expressions#evaluation-order) + [6.17. Operator precedence](expressions#operator-precedence) * [7. Simple statements](simple_stmts) + [7.1. Expression statements](simple_stmts#expression-statements) + [7.2. Assignment statements](simple_stmts#assignment-statements) + [7.3. The `assert` statement](simple_stmts#the-assert-statement) + [7.4. The `pass` statement](simple_stmts#the-pass-statement) + [7.5. The `del` statement](simple_stmts#the-del-statement) + [7.6. The `return` statement](simple_stmts#the-return-statement) + [7.7. The `yield` statement](simple_stmts#the-yield-statement) + [7.8. The `raise` statement](simple_stmts#the-raise-statement) + [7.9. The `break` statement](simple_stmts#the-break-statement) + [7.10. The `continue` statement](simple_stmts#the-continue-statement) + [7.11. The `import` statement](simple_stmts#the-import-statement) + [7.12. The `global` statement](simple_stmts#the-global-statement) + [7.13. The `nonlocal` statement](simple_stmts#the-nonlocal-statement) * [8. Compound statements](compound_stmts) + [8.1. The `if` statement](compound_stmts#the-if-statement) + [8.2. The `while` statement](compound_stmts#the-while-statement) + [8.3. The `for` statement](compound_stmts#the-for-statement) + [8.4. The `try` statement](compound_stmts#the-try-statement) + [8.5. The `with` statement](compound_stmts#the-with-statement) + [8.6. Function definitions](compound_stmts#function-definitions) + [8.7. Class definitions](compound_stmts#class-definitions) + [8.8. Coroutines](compound_stmts#coroutines) * [9. Top-level components](toplevel_components) + [9.1. Complete Python programs](toplevel_components#complete-python-programs) + [9.2. File input](toplevel_components#file-input) + [9.3. Interactive input](toplevel_components#interactive-input) + [9.4. Expression input](toplevel_components#expression-input) * [10. Full Grammar specification](grammar) python Full Grammar specification Full Grammar specification =========================== This is the full Python grammar, derived directly from the grammar used to generate the CPython parser (see [Grammar/python.gram](https://github.com/python/cpython/tree/3.9/Grammar/python.gram)). The version here omits details related to code generation and error recovery. The notation is a mixture of [EBNF](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form) and [PEG](https://en.wikipedia.org/wiki/Parsing_expression_grammar). In particular, `&` followed by a symbol, token or parenthesized group indicates a positive lookahead (i.e., is required to match but not consumed), while `!` indicates a negative lookahead (i.e., is required \_not\_ to match). We use the `|` separator to mean PEG’s “ordered choice” (written as `/` in traditional PEG grammars). ``` # PEG grammar for Python file: [statements] ENDMARKER interactive: statement_newline eval: expressions NEWLINE* ENDMARKER func_type: '(' [type_expressions] ')' '->' expression NEWLINE* ENDMARKER fstring: star_expressions # type_expressions allow */** but ignore them type_expressions: | ','.expression+ ',' '*' expression ',' '**' expression | ','.expression+ ',' '*' expression | ','.expression+ ',' '**' expression | '*' expression ',' '**' expression | '*' expression | '**' expression | ','.expression+ statements: statement+ statement: compound_stmt | simple_stmt statement_newline: | compound_stmt NEWLINE | simple_stmt | NEWLINE | ENDMARKER simple_stmt: | small_stmt !';' NEWLINE # Not needed, there for speedup | ';'.small_stmt+ [';'] NEWLINE # NOTE: assignment MUST precede expression, else parsing a simple assignment # will throw a SyntaxError. small_stmt: | assignment | star_expressions | return_stmt | import_stmt | raise_stmt | 'pass' | del_stmt | yield_stmt | assert_stmt | 'break' | 'continue' | global_stmt | nonlocal_stmt compound_stmt: | function_def | if_stmt | class_def | with_stmt | for_stmt | try_stmt | while_stmt # NOTE: annotated_rhs may start with 'yield'; yield_expr must start with 'yield' assignment: | NAME ':' expression ['=' annotated_rhs ] | ('(' single_target ')' | single_subscript_attribute_target) ':' expression ['=' annotated_rhs ] | (star_targets '=' )+ (yield_expr | star_expressions) !'=' [TYPE_COMMENT] | single_target augassign ~ (yield_expr | star_expressions) augassign: | '+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' | '<<=' | '>>=' | '**=' | '//=' global_stmt: 'global' ','.NAME+ nonlocal_stmt: 'nonlocal' ','.NAME+ yield_stmt: yield_expr assert_stmt: 'assert' expression [',' expression ] del_stmt: | 'del' del_targets &(';' | NEWLINE) import_stmt: import_name | import_from import_name: 'import' dotted_as_names # note below: the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS import_from: | 'from' ('.' | '...')* dotted_name 'import' import_from_targets | 'from' ('.' | '...')+ 'import' import_from_targets import_from_targets: | '(' import_from_as_names [','] ')' | import_from_as_names !',' | '*' import_from_as_names: | ','.import_from_as_name+ import_from_as_name: | NAME ['as' NAME ] dotted_as_names: | ','.dotted_as_name+ dotted_as_name: | dotted_name ['as' NAME ] dotted_name: | dotted_name '.' NAME | NAME if_stmt: | 'if' named_expression ':' block elif_stmt | 'if' named_expression ':' block [else_block] elif_stmt: | 'elif' named_expression ':' block elif_stmt | 'elif' named_expression ':' block [else_block] else_block: 'else' ':' block while_stmt: | 'while' named_expression ':' block [else_block] for_stmt: | 'for' star_targets 'in' ~ star_expressions ':' [TYPE_COMMENT] block [else_block] | ASYNC 'for' star_targets 'in' ~ star_expressions ':' [TYPE_COMMENT] block [else_block] with_stmt: | 'with' '(' ','.with_item+ ','? ')' ':' block | 'with' ','.with_item+ ':' [TYPE_COMMENT] block | ASYNC 'with' '(' ','.with_item+ ','? ')' ':' block | ASYNC 'with' ','.with_item+ ':' [TYPE_COMMENT] block with_item: | expression 'as' star_target &(',' | ')' | ':') | expression try_stmt: | 'try' ':' block finally_block | 'try' ':' block except_block+ [else_block] [finally_block] except_block: | 'except' expression ['as' NAME ] ':' block | 'except' ':' block finally_block: 'finally' ':' block return_stmt: | 'return' [star_expressions] raise_stmt: | 'raise' expression ['from' expression ] | 'raise' function_def: | decorators function_def_raw | function_def_raw function_def_raw: | 'def' NAME '(' [params] ')' ['->' expression ] ':' [func_type_comment] block | ASYNC 'def' NAME '(' [params] ')' ['->' expression ] ':' [func_type_comment] block func_type_comment: | NEWLINE TYPE_COMMENT &(NEWLINE INDENT) # Must be followed by indented block | TYPE_COMMENT params: | parameters parameters: | slash_no_default param_no_default* param_with_default* [star_etc] | slash_with_default param_with_default* [star_etc] | param_no_default+ param_with_default* [star_etc] | param_with_default+ [star_etc] | star_etc # Some duplication here because we can't write (',' | &')'), # which is because we don't support empty alternatives (yet). # slash_no_default: | param_no_default+ '/' ',' | param_no_default+ '/' &')' slash_with_default: | param_no_default* param_with_default+ '/' ',' | param_no_default* param_with_default+ '/' &')' star_etc: | '*' param_no_default param_maybe_default* [kwds] | '*' ',' param_maybe_default+ [kwds] | kwds kwds: '**' param_no_default # One parameter. This *includes* a following comma and type comment. # # There are three styles: # - No default # - With default # - Maybe with default # # There are two alternative forms of each, to deal with type comments: # - Ends in a comma followed by an optional type comment # - No comma, optional type comment, must be followed by close paren # The latter form is for a final parameter without trailing comma. # param_no_default: | param ',' TYPE_COMMENT? | param TYPE_COMMENT? &')' param_with_default: | param default ',' TYPE_COMMENT? | param default TYPE_COMMENT? &')' param_maybe_default: | param default? ',' TYPE_COMMENT? | param default? TYPE_COMMENT? &')' param: NAME annotation? annotation: ':' expression default: '=' expression decorators: ('@' named_expression NEWLINE )+ class_def: | decorators class_def_raw | class_def_raw class_def_raw: | 'class' NAME ['(' [arguments] ')' ] ':' block block: | NEWLINE INDENT statements DEDENT | simple_stmt star_expressions: | star_expression (',' star_expression )+ [','] | star_expression ',' | star_expression star_expression: | '*' bitwise_or | expression star_named_expressions: ','.star_named_expression+ [','] star_named_expression: | '*' bitwise_or | named_expression named_expression: | NAME ':=' ~ expression | expression !':=' annotated_rhs: yield_expr | star_expressions expressions: | expression (',' expression )+ [','] | expression ',' | expression expression: | disjunction 'if' disjunction 'else' expression | disjunction | lambdef lambdef: | 'lambda' [lambda_params] ':' expression lambda_params: | lambda_parameters # lambda_parameters etc. duplicates parameters but without annotations # or type comments, and if there's no comma after a parameter, we expect # a colon, not a close parenthesis. (For more, see parameters above.) # lambda_parameters: | lambda_slash_no_default lambda_param_no_default* lambda_param_with_default* [lambda_star_etc] | lambda_slash_with_default lambda_param_with_default* [lambda_star_etc] | lambda_param_no_default+ lambda_param_with_default* [lambda_star_etc] | lambda_param_with_default+ [lambda_star_etc] | lambda_star_etc lambda_slash_no_default: | lambda_param_no_default+ '/' ',' | lambda_param_no_default+ '/' &':' lambda_slash_with_default: | lambda_param_no_default* lambda_param_with_default+ '/' ',' | lambda_param_no_default* lambda_param_with_default+ '/' &':' lambda_star_etc: | '*' lambda_param_no_default lambda_param_maybe_default* [lambda_kwds] | '*' ',' lambda_param_maybe_default+ [lambda_kwds] | lambda_kwds lambda_kwds: '**' lambda_param_no_default lambda_param_no_default: | lambda_param ',' | lambda_param &':' lambda_param_with_default: | lambda_param default ',' | lambda_param default &':' lambda_param_maybe_default: | lambda_param default? ',' | lambda_param default? &':' lambda_param: NAME disjunction: | conjunction ('or' conjunction )+ | conjunction conjunction: | inversion ('and' inversion )+ | inversion inversion: | 'not' inversion | comparison comparison: | bitwise_or compare_op_bitwise_or_pair+ | bitwise_or compare_op_bitwise_or_pair: | eq_bitwise_or | noteq_bitwise_or | lte_bitwise_or | lt_bitwise_or | gte_bitwise_or | gt_bitwise_or | notin_bitwise_or | in_bitwise_or | isnot_bitwise_or | is_bitwise_or eq_bitwise_or: '==' bitwise_or noteq_bitwise_or: | ('!=' ) bitwise_or lte_bitwise_or: '<=' bitwise_or lt_bitwise_or: '<' bitwise_or gte_bitwise_or: '>=' bitwise_or gt_bitwise_or: '>' bitwise_or notin_bitwise_or: 'not' 'in' bitwise_or in_bitwise_or: 'in' bitwise_or isnot_bitwise_or: 'is' 'not' bitwise_or is_bitwise_or: 'is' bitwise_or bitwise_or: | bitwise_or '|' bitwise_xor | bitwise_xor bitwise_xor: | bitwise_xor '^' bitwise_and | bitwise_and bitwise_and: | bitwise_and '&' shift_expr | shift_expr shift_expr: | shift_expr '<<' sum | shift_expr '>>' sum | sum sum: | sum '+' term | sum '-' term | term term: | term '*' factor | term '/' factor | term '//' factor | term '%' factor | term '@' factor | factor factor: | '+' factor | '-' factor | '~' factor | power power: | await_primary '**' factor | await_primary await_primary: | AWAIT primary | primary primary: | primary '.' NAME | primary genexp | primary '(' [arguments] ')' | primary '[' slices ']' | atom slices: | slice !',' | ','.slice+ [','] slice: | [expression] ':' [expression] [':' [expression] ] | expression atom: | NAME | 'True' | 'False' | 'None' | '__peg_parser__' | strings | NUMBER | (tuple | group | genexp) | (list | listcomp) | (dict | set | dictcomp | setcomp) | '...' strings: STRING+ list: | '[' [star_named_expressions] ']' listcomp: | '[' named_expression ~ for_if_clauses ']' tuple: | '(' [star_named_expression ',' [star_named_expressions] ] ')' group: | '(' (yield_expr | named_expression) ')' genexp: | '(' named_expression ~ for_if_clauses ')' set: '{' star_named_expressions '}' setcomp: | '{' named_expression ~ for_if_clauses '}' dict: | '{' [double_starred_kvpairs] '}' dictcomp: | '{' kvpair for_if_clauses '}' double_starred_kvpairs: ','.double_starred_kvpair+ [','] double_starred_kvpair: | '**' bitwise_or | kvpair kvpair: expression ':' expression for_if_clauses: | for_if_clause+ for_if_clause: | ASYNC 'for' star_targets 'in' ~ disjunction ('if' disjunction )* | 'for' star_targets 'in' ~ disjunction ('if' disjunction )* yield_expr: | 'yield' 'from' expression | 'yield' [star_expressions] arguments: | args [','] &')' args: | ','.(starred_expression | named_expression !'=')+ [',' kwargs ] | kwargs kwargs: | ','.kwarg_or_starred+ ',' ','.kwarg_or_double_starred+ | ','.kwarg_or_starred+ | ','.kwarg_or_double_starred+ starred_expression: | '*' expression kwarg_or_starred: | NAME '=' expression | starred_expression kwarg_or_double_starred: | NAME '=' expression | '**' expression # NOTE: star_targets may contain *bitwise_or, targets may not. star_targets: | star_target !',' | star_target (',' star_target )* [','] star_targets_list_seq: ','.star_target+ [','] star_targets_tuple_seq: | star_target (',' star_target )+ [','] | star_target ',' star_target: | '*' (!'*' star_target) | target_with_star_atom target_with_star_atom: | t_primary '.' NAME !t_lookahead | t_primary '[' slices ']' !t_lookahead | star_atom star_atom: | NAME | '(' target_with_star_atom ')' | '(' [star_targets_tuple_seq] ')' | '[' [star_targets_list_seq] ']' single_target: | single_subscript_attribute_target | NAME | '(' single_target ')' single_subscript_attribute_target: | t_primary '.' NAME !t_lookahead | t_primary '[' slices ']' !t_lookahead del_targets: ','.del_target+ [','] del_target: | t_primary '.' NAME !t_lookahead | t_primary '[' slices ']' !t_lookahead | del_t_atom del_t_atom: | NAME | '(' del_target ')' | '(' [del_targets] ')' | '[' [del_targets] ']' t_primary: | t_primary '.' NAME &t_lookahead | t_primary '[' slices ']' &t_lookahead | t_primary genexp &t_lookahead | t_primary '(' [arguments] ')' &t_lookahead | atom &t_lookahead t_lookahead: '(' | '[' | '.' ``` python Lexical analysis Lexical analysis ================= A Python program is read by a *parser*. Input to the parser is a stream of *tokens*, generated by the *lexical analyzer*. This chapter describes how the lexical analyzer breaks a file into tokens. Python reads program text as Unicode code points; the encoding of a source file can be given by an encoding declaration and defaults to UTF-8, see [**PEP 3120**](https://www.python.org/dev/peps/pep-3120) for details. If the source file cannot be decoded, a [`SyntaxError`](../library/exceptions#SyntaxError "SyntaxError") is raised. 2.1. Line structure -------------------- A Python program is divided into a number of *logical lines*. ### 2.1.1. Logical lines The end of a logical line is represented by the token NEWLINE. Statements cannot cross logical line boundaries except where NEWLINE is allowed by the syntax (e.g., between statements in compound statements). A logical line is constructed from one or more *physical lines* by following the explicit or implicit *line joining* rules. ### 2.1.2. Physical lines A physical line is a sequence of characters terminated by an end-of-line sequence. In source files and strings, any of the standard platform line termination sequences can be used - the Unix form using ASCII LF (linefeed), the Windows form using the ASCII sequence CR LF (return followed by linefeed), or the old Macintosh form using the ASCII CR (return) character. All of these forms can be used equally, regardless of platform. The end of input also serves as an implicit terminator for the final physical line. When embedding Python, source code strings should be passed to Python APIs using the standard C conventions for newline characters (the `\n` character, representing ASCII LF, is the line terminator). ### 2.1.3. Comments A comment starts with a hash character (`#`) that is not part of a string literal, and ends at the end of the physical line. A comment signifies the end of the logical line unless the implicit line joining rules are invoked. Comments are ignored by the syntax. ### 2.1.4. Encoding declarations If a comment in the first or second line of the Python script matches the regular expression `coding[=:]\s*([-\w.]+)`, this comment is processed as an encoding declaration; the first group of this expression names the encoding of the source code file. The encoding declaration must appear on a line of its own. If it is the second line, the first line must also be a comment-only line. The recommended forms of an encoding expression are ``` # -*- coding: <encoding-name> -*- ``` which is recognized also by GNU Emacs, and ``` # vim:fileencoding=<encoding-name> ``` which is recognized by Bram Moolenaar’s VIM. If no encoding declaration is found, the default encoding is UTF-8. In addition, if the first bytes of the file are the UTF-8 byte-order mark (`b'\xef\xbb\xbf'`), the declared file encoding is UTF-8 (this is supported, among others, by Microsoft’s **notepad**). If an encoding is declared, the encoding name must be recognized by Python (see [Standard Encodings](../library/codecs#standard-encodings)). The encoding is used for all lexical analysis, including string literals, comments and identifiers. ### 2.1.5. Explicit line joining Two or more physical lines may be joined into logical lines using backslash characters (`\`), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character. For example: ``` if 1900 < year < 2100 and 1 <= month <= 12 \ and 1 <= day <= 31 and 0 <= hour < 24 \ and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date return 1 ``` A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal. ### 2.1.6. Implicit line joining Expressions in parentheses, square brackets or curly braces can be split over more than one physical line without using backslashes. For example: ``` month_names = ['Januari', 'Februari', 'Maart', # These are the 'April', 'Mei', 'Juni', # Dutch names 'Juli', 'Augustus', 'September', # for the months 'Oktober', 'November', 'December'] # of the year ``` Implicitly continued lines can carry comments. The indentation of the continuation lines is not important. Blank continuation lines are allowed. There is no NEWLINE token between implicit continuation lines. Implicitly continued lines can also occur within triple-quoted strings (see below); in that case they cannot carry comments. ### 2.1.7. Blank lines A logical line that contains only spaces, tabs, formfeeds and possibly a comment, is ignored (i.e., no NEWLINE token is generated). During interactive input of statements, handling of a blank line may differ depending on the implementation of the read-eval-print loop. In the standard interactive interpreter, an entirely blank logical line (i.e. one containing not even whitespace or a comment) terminates a multi-line statement. ### 2.1.8. Indentation Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements. Tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight (this is intended to be the same rule as used by Unix). The total number of spaces preceding the first non-blank character then determines the line’s indentation. Indentation cannot be split over multiple physical lines using backslashes; the whitespace up to the first backslash determines the indentation. Indentation is rejected as inconsistent if a source file mixes tabs and spaces in a way that makes the meaning dependent on the worth of a tab in spaces; a [`TabError`](../library/exceptions#TabError "TabError") is raised in that case. **Cross-platform compatibility note:** because of the nature of text editors on non-UNIX platforms, it is unwise to use a mixture of spaces and tabs for the indentation in a single source file. It should also be noted that different platforms may explicitly limit the maximum indentation level. A formfeed character may be present at the start of the line; it will be ignored for the indentation calculations above. Formfeed characters occurring elsewhere in the leading whitespace have an undefined effect (for instance, they may reset the space count to zero). The indentation levels of consecutive lines are used to generate INDENT and DEDENT tokens, using a stack, as follows. Before the first line of the file is read, a single zero is pushed on the stack; this will never be popped off again. The numbers pushed on the stack will always be strictly increasing from bottom to top. At the beginning of each logical line, the line’s indentation level is compared to the top of the stack. If it is equal, nothing happens. If it is larger, it is pushed on the stack, and one INDENT token is generated. If it is smaller, it *must* be one of the numbers occurring on the stack; all numbers on the stack that are larger are popped off, and for each number popped off a DEDENT token is generated. At the end of the file, a DEDENT token is generated for each number remaining on the stack that is larger than zero. Here is an example of a correctly (though confusingly) indented piece of Python code: ``` def perm(l): # Compute the list of all permutations of l if len(l) <= 1: return [l] r = [] for i in range(len(l)): s = l[:i] + l[i+1:] p = perm(s) for x in p: r.append(l[i:i+1] + x) return r ``` The following example shows various indentation errors: ``` def perm(l): # error: first line indented for i in range(len(l)): # error: not indented s = l[:i] + l[i+1:] p = perm(l[:i] + l[i+1:]) # error: unexpected indent for x in p: r.append(l[i:i+1] + x) return r # error: inconsistent dedent ``` (Actually, the first three errors are detected by the parser; only the last error is found by the lexical analyzer — the indentation of `return r` does not match a level popped off the stack.) ### 2.1.9. Whitespace between tokens Except at the beginning of a logical line or in string literals, the whitespace characters space, tab and formfeed can be used interchangeably to separate tokens. Whitespace is needed between two tokens only if their concatenation could otherwise be interpreted as a different token (e.g., ab is one token, but a b is two tokens). 2.2. Other tokens ------------------ Besides NEWLINE, INDENT and DEDENT, the following categories of tokens exist: *identifiers*, *keywords*, *literals*, *operators*, and *delimiters*. Whitespace characters (other than line terminators, discussed earlier) are not tokens, but serve to delimit tokens. Where ambiguity exists, a token comprises the longest possible string that forms a legal token, when read from left to right. 2.3. Identifiers and keywords ------------------------------ Identifiers (also referred to as *names*) are described by the following lexical definitions. The syntax of identifiers in Python is based on the Unicode standard annex UAX-31, with elaboration and changes as defined below; see also [**PEP 3131**](https://www.python.org/dev/peps/pep-3131) for further details. Within the ASCII range (U+0001..U+007F), the valid characters for identifiers are the same as in Python 2.x: the uppercase and lowercase letters `A` through `Z`, the underscore `_` and, except for the first character, the digits `0` through `9`. Python 3.0 introduces additional characters from outside the ASCII range (see [**PEP 3131**](https://www.python.org/dev/peps/pep-3131)). For these characters, the classification uses the version of the Unicode Character Database as included in the [`unicodedata`](../library/unicodedata#module-unicodedata "unicodedata: Access the Unicode Database.") module. Identifiers are unlimited in length. Case is significant. ``` **identifier** ::= [xid\_start](#grammar-token-xid-start) [xid\_continue](#grammar-token-xid-continue)* **id\_start** ::= <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property> **id\_continue** ::= <all characters in [id\_start](#grammar-token-id-start), plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property> **xid\_start** ::= <all characters in [id\_start](#grammar-token-id-start) whose NFKC normalization is in "id_start xid_continue*"> **xid\_continue** ::= <all characters in [id\_continue](#grammar-token-id-continue) whose NFKC normalization is in "id_continue*"> ``` The Unicode category codes mentioned above stand for: * *Lu* - uppercase letters * *Ll* - lowercase letters * *Lt* - titlecase letters * *Lm* - modifier letters * *Lo* - other letters * *Nl* - letter numbers * *Mn* - nonspacing marks * *Mc* - spacing combining marks * *Nd* - decimal numbers * *Pc* - connector punctuations * *Other\_ID\_Start* - explicit list of characters in [PropList.txt](https://www.unicode.org/Public/13.0.0/ucd/PropList.txt) to support backwards compatibility * *Other\_ID\_Continue* - likewise All identifiers are converted into the normal form NFKC while parsing; comparison of identifiers is based on NFKC. A non-normative HTML file listing all valid identifier characters for Unicode 4.1 can be found at <https://www.unicode.org/Public/13.0.0/ucd/DerivedCoreProperties.txt> ### 2.3.1. Keywords The following identifiers are used as reserved words, or *keywords* of the language, and cannot be used as ordinary identifiers. They must be spelled exactly as written here: ``` False await else import pass None break except in raise True class finally is return and continue for lambda try as def from nonlocal while assert del global not with async elif if or yield ``` ### 2.3.2. Reserved classes of identifiers Certain classes of identifiers (besides keywords) have special meanings. These classes are identified by the patterns of leading and trailing underscore characters: `_*` Not imported by `from module import *`. The special identifier `_` is used in the interactive interpreter to store the result of the last evaluation; it is stored in the [`builtins`](../library/builtins#module-builtins "builtins: The module that provides the built-in namespace.") module. When not in interactive mode, `_` has no special meaning and is not defined. See section [The import statement](simple_stmts#import). Note The name `_` is often used in conjunction with internationalization; refer to the documentation for the [`gettext`](../library/gettext#module-gettext "gettext: Multilingual internationalization services.") module for more information on this convention. `__*__` System-defined names, informally known as “dunder” names. These names are defined by the interpreter and its implementation (including the standard library). Current system names are discussed in the [Special method names](datamodel#specialnames) section and elsewhere. More will likely be defined in future versions of Python. *Any* use of `__*__` names, in any context, that does not follow explicitly documented use, is subject to breakage without warning. `__*` Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between “private” attributes of base and derived classes. See section [Identifiers (Names)](expressions#atom-identifiers). 2.4. Literals -------------- Literals are notations for constant values of some built-in types. ### 2.4.1. String and Bytes literals String literals are described by the following lexical definitions: ``` **stringliteral** ::= [[stringprefix](#grammar-token-stringprefix)]([shortstring](#grammar-token-shortstring) | [longstring](#grammar-token-longstring)) **stringprefix** ::= "r" | "u" | "R" | "U" | "f" | "F" | "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | "Rf" | "RF" **shortstring** ::= "'" [shortstringitem](#grammar-token-shortstringitem)* "'" | '"' [shortstringitem](#grammar-token-shortstringitem)* '"' **longstring** ::= "'''" [longstringitem](#grammar-token-longstringitem)* "'''" | '"""' [longstringitem](#grammar-token-longstringitem)* '"""' **shortstringitem** ::= [shortstringchar](#grammar-token-shortstringchar) | [stringescapeseq](#grammar-token-stringescapeseq) **longstringitem** ::= [longstringchar](#grammar-token-longstringchar) | [stringescapeseq](#grammar-token-stringescapeseq) **shortstringchar** ::= <any source character except "\" or newline or the quote> **longstringchar** ::= <any source character except "\"> **stringescapeseq** ::= "\" <any source character> ``` ``` **bytesliteral** ::= [bytesprefix](#grammar-token-bytesprefix)([shortbytes](#grammar-token-shortbytes) | [longbytes](#grammar-token-longbytes)) **bytesprefix** ::= "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB" **shortbytes** ::= "'" [shortbytesitem](#grammar-token-shortbytesitem)* "'" | '"' [shortbytesitem](#grammar-token-shortbytesitem)* '"' **longbytes** ::= "'''" [longbytesitem](#grammar-token-longbytesitem)* "'''" | '"""' [longbytesitem](#grammar-token-longbytesitem)* '"""' **shortbytesitem** ::= [shortbyteschar](#grammar-token-shortbyteschar) | [bytesescapeseq](#grammar-token-bytesescapeseq) **longbytesitem** ::= [longbyteschar](#grammar-token-longbyteschar) | [bytesescapeseq](#grammar-token-bytesescapeseq) **shortbyteschar** ::= <any ASCII character except "\" or newline or the quote> **longbyteschar** ::= <any ASCII character except "\"> **bytesescapeseq** ::= "\" <any ASCII character> ``` One syntactic restriction not indicated by these productions is that whitespace is not allowed between the [`stringprefix`](#grammar-token-stringprefix) or [`bytesprefix`](#grammar-token-bytesprefix) and the rest of the literal. The source character set is defined by the encoding declaration; it is UTF-8 if no encoding declaration is given in the source file; see section [Encoding declarations](#encodings). In plain English: Both types of literals can be enclosed in matching single quotes (`'`) or double quotes (`"`). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as *triple-quoted strings*). The backslash (`\`) character is used to give special meaning to otherwise ordinary characters like `n`, which means ‘newline’ when escaped (`\n`). It can also be used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character. See [escape sequences](#escape-sequences) below for examples. Bytes literals are always prefixed with `'b'` or `'B'`; they produce an instance of the [`bytes`](../library/stdtypes#bytes "bytes") type instead of the [`str`](../library/stdtypes#str "str") type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes. Both string and bytes literals may optionally be prefixed with a letter `'r'` or `'R'`; such strings are called *raw strings* and treat backslashes as literal characters. As a result, in string literals, `'\U'` and `'\u'` escapes in raw strings are not treated specially. Given that Python 2.x’s raw unicode literals behave differently than Python 3.x’s the `'ur'` syntax is not supported. New in version 3.3: The `'rb'` prefix of raw bytes literals has been added as a synonym of `'br'`. New in version 3.3: Support for the unicode legacy literal (`u'value'`) was reintroduced to simplify the maintenance of dual Python 2.x and 3.x codebases. See [**PEP 414**](https://www.python.org/dev/peps/pep-0414) for more information. A string literal with `'f'` or `'F'` in its prefix is a *formatted string literal*; see [Formatted string literals](#f-strings). The `'f'` may be combined with `'r'`, but not with `'b'` or `'u'`, therefore raw formatted strings are possible, but formatted bytes literals are not. In triple-quoted literals, unescaped newlines and quotes are allowed (and are retained), except that three unescaped quotes in a row terminate the literal. (A “quote” is the character used to open the literal, i.e. either `'` or `"`.) Unless an `'r'` or `'R'` prefix is present, escape sequences in string and bytes literals are interpreted according to rules similar to those used by Standard C. The recognized escape sequences are: | Escape Sequence | Meaning | Notes | | --- | --- | --- | | `\newline` | Backslash and newline ignored | | | `\\` | Backslash (`\`) | | | `\'` | Single quote (`'`) | | | `\"` | Double quote (`"`) | | | `\a` | ASCII Bell (BEL) | | | `\b` | ASCII Backspace (BS) | | | `\f` | ASCII Formfeed (FF) | | | `\n` | ASCII Linefeed (LF) | | | `\r` | ASCII Carriage Return (CR) | | | `\t` | ASCII Horizontal Tab (TAB) | | | `\v` | ASCII Vertical Tab (VT) | | | `\ooo` | Character with octal value *ooo* | (1,3) | | `\xhh` | Character with hex value *hh* | (2,3) | Escape sequences only recognized in string literals are: | Escape Sequence | Meaning | Notes | | --- | --- | --- | | `\N{name}` | Character named *name* in the Unicode database | (4) | | `\uxxxx` | Character with 16-bit hex value *xxxx* | (5) | | `\Uxxxxxxxx` | Character with 32-bit hex value *xxxxxxxx* | (6) | Notes: 1. As in Standard C, up to three octal digits are accepted. 2. Unlike in Standard C, exactly two hex digits are required. 3. In a bytes literal, hexadecimal and octal escapes denote the byte with the given value. In a string literal, these escapes denote a Unicode character with the given value. 4. Changed in version 3.3: Support for name aliases [1](#id13) has been added. 5. Exactly four hex digits are required. 6. Any Unicode character can be encoded this way. Exactly eight hex digits are required. Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., *the backslash is left in the result*. (This behavior is useful when debugging: if an escape sequence is mistyped, the resulting output is more easily recognized as broken.) It is also important to note that the escape sequences only recognized in string literals fall into the category of unrecognized escapes for bytes literals. Changed in version 3.6: Unrecognized escape sequences produce a [`DeprecationWarning`](../library/exceptions#DeprecationWarning "DeprecationWarning"). In a future Python version they will be a [`SyntaxWarning`](../library/exceptions#SyntaxWarning "SyntaxWarning") and eventually a [`SyntaxError`](../library/exceptions#SyntaxError "SyntaxError"). Even in a raw literal, quotes can be escaped with a backslash, but the backslash remains in the result; for example, `r"\""` is a valid string literal consisting of two characters: a backslash and a double quote; `r"\"` is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, *a raw literal cannot end in a single backslash* (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the literal, *not* as a line continuation. ### 2.4.2. String literal concatenation Multiple adjacent string or bytes literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, `"hello" 'world'` is equivalent to `"helloworld"`. This feature can be used to reduce the number of backslashes needed, to split long strings conveniently across long lines, or even to add comments to parts of strings, for example: ``` re.compile("[A-Za-z_]" # letter or underscore "[A-Za-z0-9_]*" # letter, digit or underscore ) ``` Note that this feature is defined at the syntactical level, but implemented at compile time. The ‘+’ operator must be used to concatenate string expressions at run time. Also note that literal concatenation can use different quoting styles for each component (even mixing raw strings and triple quoted strings), and formatted string literals may be concatenated with plain string literals. ### 2.4.3. Formatted string literals New in version 3.6. A *formatted string literal* or *f-string* is a string literal that is prefixed with `'f'` or `'F'`. These strings may contain replacement fields, which are expressions delimited by curly braces `{}`. While other string literals always have a constant value, formatted strings are really expressions evaluated at run time. Escape sequences are decoded like in ordinary string literals (except when a literal is also marked as a raw string). After decoding, the grammar for the contents of the string is: ``` **f\_string** ::= ([literal\_char](#grammar-token-literal-char) | "{{" | "}}" | [replacement\_field](#grammar-token-replacement-field))* **replacement\_field** ::= "{" [f\_expression](#grammar-token-f-expression) ["="] ["!" [conversion](#grammar-token-conversion)] [":" [format\_spec](#grammar-token-format-spec)] "}" **f\_expression** ::= ([conditional\_expression](expressions#grammar-token-conditional-expression) | "*" [or\_expr](expressions#grammar-token-or-expr)) ("," [conditional\_expression](expressions#grammar-token-conditional-expression) | "," "*" [or\_expr](expressions#grammar-token-or-expr))* [","] | [yield\_expression](expressions#grammar-token-yield-expression) **conversion** ::= "s" | "r" | "a" **format\_spec** ::= ([literal\_char](#grammar-token-literal-char) | NULL | [replacement\_field](#grammar-token-replacement-field))* **literal\_char** ::= <any code point except "{", "}" or NULL> ``` The parts of the string outside curly braces are treated literally, except that any doubled curly braces `'{{'` or `'}}'` are replaced with the corresponding single curly brace. A single opening curly bracket `'{'` marks a replacement field, which starts with a Python expression. To display both the expression text and its value after evaluation, (useful in debugging), an equal sign `'='` may be added after the expression. A conversion field, introduced by an exclamation point `'!'` may follow. A format specifier may also be appended, introduced by a colon `':'`. A replacement field ends with a closing curly bracket `'}'`. Expressions in formatted string literals are treated like regular Python expressions surrounded by parentheses, with a few exceptions. An empty expression is not allowed, and both [`lambda`](expressions#lambda) and assignment expressions `:=` must be surrounded by explicit parentheses. Replacement expressions can contain line breaks (e.g. in triple-quoted strings), but they cannot contain comments. Each expression is evaluated in the context where the formatted string literal appears, in order from left to right. Changed in version 3.7: Prior to Python 3.7, an [`await`](expressions#await) expression and comprehensions containing an [`async for`](compound_stmts#async-for) clause were illegal in the expressions in formatted string literals due to a problem with the implementation. When the equal sign `'='` is provided, the output will have the expression text, the `'='` and the evaluated value. Spaces after the opening brace `'{'`, within the expression and after the `'='` are all retained in the output. By default, the `'='` causes the [`repr()`](../library/functions#repr "repr") of the expression to be provided, unless there is a format specified. When a format is specified it defaults to the [`str()`](../library/stdtypes#str "str") of the expression unless a conversion `'!r'` is declared. New in version 3.8: The equal sign `'='`. If a conversion is specified, the result of evaluating the expression is converted before formatting. Conversion `'!s'` calls [`str()`](../library/stdtypes#str "str") on the result, `'!r'` calls [`repr()`](../library/functions#repr "repr"), and `'!a'` calls [`ascii()`](../library/functions#ascii "ascii"). The result is then formatted using the [`format()`](../library/functions#format "format") protocol. The format specifier is passed to the [`__format__()`](datamodel#object.__format__ "object.__format__") method of the expression or conversion result. An empty string is passed when the format specifier is omitted. The formatted result is then included in the final value of the whole string. Top-level format specifiers may include nested replacement fields. These nested fields may include their own conversion fields and [format specifiers](../library/string#formatspec), but may not include more deeply-nested replacement fields. The [format specifier mini-language](../library/string#formatspec) is the same as that used by the [`str.format()`](../library/stdtypes#str.format "str.format") method. Formatted string literals may be concatenated, but replacement fields cannot be split across literals. Some examples of formatted string literals: ``` >>> name = "Fred" >>> f"He said his name is {name!r}." "He said his name is 'Fred'." >>> f"He said his name is {repr(name)}." # repr() is equivalent to !r "He said his name is 'Fred'." >>> width = 10 >>> precision = 4 >>> value = decimal.Decimal("12.34567") >>> f"result: {value:{width}.{precision}}" # nested fields 'result: 12.35' >>> today = datetime(year=2017, month=1, day=27) >>> f"{today:%B %d, %Y}" # using date format specifier 'January 27, 2017' >>> f"{today=:%B %d, %Y}" # using date format specifier and debugging 'today=January 27, 2017' >>> number = 1024 >>> f"{number:#0x}" # using integer format specifier '0x400' >>> foo = "bar" >>> f"{ foo = }" # preserves whitespace " foo = 'bar'" >>> line = "The mill's closed" >>> f"{line = }" 'line = "The mill\'s closed"' >>> f"{line = :20}" "line = The mill's closed " >>> f"{line = !r:20}" 'line = "The mill\'s closed" ' ``` A consequence of sharing the same syntax as regular string literals is that characters in the replacement fields must not conflict with the quoting used in the outer formatted string literal: ``` f"abc {a["x"]} def" # error: outer string literal ended prematurely f"abc {a['x']} def" # workaround: use different quoting ``` Backslashes are not allowed in format expressions and will raise an error: ``` f"newline: {ord('\n')}" # raises SyntaxError ``` To include a value in which a backslash escape is required, create a temporary variable. ``` >>> newline = ord('\n') >>> f"newline: {newline}" 'newline: 10' ``` Formatted string literals cannot be used as docstrings, even if they do not include expressions. ``` >>> def foo(): ... f"Not a docstring" ... >>> foo.__doc__ is None True ``` See also [**PEP 498**](https://www.python.org/dev/peps/pep-0498) for the proposal that added formatted string literals, and [`str.format()`](../library/stdtypes#str.format "str.format"), which uses a related format string mechanism. ### 2.4.4. Numeric literals There are three types of numeric literals: integers, floating point numbers, and imaginary numbers. There are no complex literals (complex numbers can be formed by adding a real number and an imaginary number). Note that numeric literals do not include a sign; a phrase like `-1` is actually an expression composed of the unary operator ‘`-`’ and the literal `1`. ### 2.4.5. Integer literals Integer literals are described by the following lexical definitions: ``` **integer** ::= [decinteger](#grammar-token-decinteger) | [bininteger](#grammar-token-bininteger) | [octinteger](#grammar-token-octinteger) | [hexinteger](#grammar-token-hexinteger) **decinteger** ::= [nonzerodigit](#grammar-token-nonzerodigit) (["_"] [digit](#grammar-token-digit))* | "0"+ (["_"] "0")* **bininteger** ::= "0" ("b" | "B") (["_"] [bindigit](#grammar-token-bindigit))+ **octinteger** ::= "0" ("o" | "O") (["_"] [octdigit](#grammar-token-octdigit))+ **hexinteger** ::= "0" ("x" | "X") (["_"] [hexdigit](#grammar-token-hexdigit))+ **nonzerodigit** ::= "1"..."9" **digit** ::= "0"..."9" **bindigit** ::= "0" | "1" **octdigit** ::= "0"..."7" **hexdigit** ::= [digit](#grammar-token-digit) | "a"..."f" | "A"..."F" ``` There is no limit for the length of integer literals apart from what can be stored in available memory. Underscores are ignored for determining the numeric value of the literal. They can be used to group digits for enhanced readability. One underscore can occur between digits, and after base specifiers like `0x`. Note that leading zeros in a non-zero decimal number are not allowed. This is for disambiguation with C-style octal literals, which Python used before version 3.0. Some examples of integer literals: ``` 7 2147483647 0o177 0b100110111 3 79228162514264337593543950336 0o377 0xdeadbeef 100_000_000_000 0b_1110_0101 ``` Changed in version 3.6: Underscores are now allowed for grouping purposes in literals. ### 2.4.6. Floating point literals Floating point literals are described by the following lexical definitions: ``` **floatnumber** ::= [pointfloat](#grammar-token-pointfloat) | [exponentfloat](#grammar-token-exponentfloat) **pointfloat** ::= [[digitpart](#grammar-token-digitpart)] [fraction](#grammar-token-fraction) | [digitpart](#grammar-token-digitpart) "." **exponentfloat** ::= ([digitpart](#grammar-token-digitpart) | [pointfloat](#grammar-token-pointfloat)) [exponent](#grammar-token-exponent) **digitpart** ::= [digit](#grammar-token-digit) (["_"] [digit](#grammar-token-digit))* **fraction** ::= "." [digitpart](#grammar-token-digitpart) **exponent** ::= ("e" | "E") ["+" | "-"] [digitpart](#grammar-token-digitpart) ``` Note that the integer and exponent parts are always interpreted using radix 10. For example, `077e010` is legal, and denotes the same number as `77e10`. The allowed range of floating point literals is implementation-dependent. As in integer literals, underscores are supported for digit grouping. Some examples of floating point literals: ``` 3.14 10. .001 1e100 3.14e-10 0e0 3.14_15_93 ``` Changed in version 3.6: Underscores are now allowed for grouping purposes in literals. ### 2.4.7. Imaginary literals Imaginary literals are described by the following lexical definitions: ``` **imagnumber** ::= ([floatnumber](#grammar-token-floatnumber) | [digitpart](#grammar-token-digitpart)) ("j" | "J") ``` An imaginary literal yields a complex number with a real part of 0.0. Complex numbers are represented as a pair of floating point numbers and have the same restrictions on their range. To create a complex number with a nonzero real part, add a floating point number to it, e.g., `(3+4j)`. Some examples of imaginary literals: ``` 3.14j 10.j 10j .001j 1e100j 3.14e-10j 3.14_15_93j ``` 2.5. Operators --------------- The following tokens are operators: ``` + - * ** / // % @ << >> & | ^ ~ := < > <= >= == != ``` 2.6. Delimiters ---------------- The following tokens serve as delimiters in the grammar: ``` ( ) [ ] { } , : . ; @ = -> += -= *= /= //= %= @= &= |= ^= >>= <<= **= ``` The period can also occur in floating-point and imaginary literals. A sequence of three periods has a special meaning as an ellipsis literal. The second half of the list, the augmented assignment operators, serve lexically as delimiters, but also perform an operation. The following printing ASCII characters have special meaning as part of other tokens or are otherwise significant to the lexical analyzer: ``` ' " # \ ``` The following printing ASCII characters are not used in Python. Their occurrence outside string literals and comments is an unconditional error: ``` $ ? ` ``` #### Footnotes `1` <https://www.unicode.org/Public/11.0.0/ucd/NameAliases.txt>
programming_docs
python Top-level components Top-level components ===================== The Python interpreter can get its input from a number of sources: from a script passed to it as standard input or as program argument, typed in interactively, from a module source file, etc. This chapter gives the syntax used in these cases. 9.1. Complete Python programs ------------------------------ While a language specification need not prescribe how the language interpreter is invoked, it is useful to have a notion of a complete Python program. A complete Python program is executed in a minimally initialized environment: all built-in and standard modules are available, but none have been initialized, except for [`sys`](../library/sys#module-sys "sys: Access system-specific parameters and functions.") (various system services), [`builtins`](../library/builtins#module-builtins "builtins: The module that provides the built-in namespace.") (built-in functions, exceptions and `None`) and [`__main__`](../library/__main__#module-__main__ "__main__: The environment where the top-level script is run."). The latter is used to provide the local and global namespace for execution of the complete program. The syntax for a complete Python program is that for file input, described in the next section. The interpreter may also be invoked in interactive mode; in this case, it does not read and execute a complete program but reads and executes one statement (possibly compound) at a time. The initial environment is identical to that of a complete program; each statement is executed in the namespace of [`__main__`](../library/__main__#module-__main__ "__main__: The environment where the top-level script is run."). A complete program can be passed to the interpreter in three forms: with the [`-c`](../using/cmdline#cmdoption-c) *string* command line option, as a file passed as the first command line argument, or as standard input. If the file or standard input is a tty device, the interpreter enters interactive mode; otherwise, it executes the file as a complete program. 9.2. File input ---------------- All input read from non-interactive files has the same form: ``` **file\_input** ::= (NEWLINE | [statement](compound_stmts#grammar-token-statement))* ``` This syntax is used in the following situations: * when parsing a complete Python program (from a file or from a string); * when parsing a module; * when parsing a string passed to the [`exec()`](../library/functions#exec "exec") function; 9.3. Interactive input ----------------------- Input in interactive mode is parsed using the following grammar: ``` **interactive\_input** ::= [[stmt\_list](compound_stmts#grammar-token-stmt-list)] NEWLINE | [compound\_stmt](compound_stmts#grammar-token-compound-stmt) NEWLINE ``` Note that a (top-level) compound statement must be followed by a blank line in interactive mode; this is needed to help the parser detect the end of the input. 9.4. Expression input ---------------------- [`eval()`](../library/functions#eval "eval") is used for expression input. It ignores leading whitespace. The string argument to [`eval()`](../library/functions#eval "eval") must have the following form: ``` **eval\_input** ::= [expression\_list](expressions#grammar-token-expression-list) NEWLINE* ``` python Execution model Execution model ================ 4.1. Structure of a program ---------------------------- A Python program is constructed from code blocks. A *block* is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition. Each command typed interactively is a block. A script file (a file given as standard input to the interpreter or specified as a command line argument to the interpreter) is a code block. A script command (a command specified on the interpreter command line with the [`-c`](../using/cmdline#cmdoption-c) option) is a code block. A module run as a top level script (as module `__main__`) from the command line using a [`-m`](../using/cmdline#cmdoption-m) argument is also a code block. The string argument passed to the built-in functions [`eval()`](../library/functions#eval "eval") and [`exec()`](../library/functions#exec "exec") is a code block. A code block is executed in an *execution frame*. A frame contains some administrative information (used for debugging) and determines where and how execution continues after the code block’s execution has completed. 4.2. Naming and binding ------------------------ ### 4.2.1. Binding of names *Names* refer to objects. Names are introduced by name binding operations. The following constructs bind names: formal parameters to functions, [`import`](simple_stmts#import) statements, class and function definitions (these bind the class or function name in the defining block), and targets that are identifiers if occurring in an assignment, [`for`](compound_stmts#for) loop header, or after `as` in a [`with`](compound_stmts#with) statement or [`except`](compound_stmts#except) clause. The `import` statement of the form `from ... import *` binds all names defined in the imported module, except those beginning with an underscore. This form may only be used at the module level. A target occurring in a [`del`](simple_stmts#del) statement is also considered bound for this purpose (though the actual semantics are to unbind the name). Each assignment or import statement occurs within a block defined by a class or function definition or at the module level (the top-level code block). If a name is bound in a block, it is a local variable of that block, unless declared as [`nonlocal`](simple_stmts#nonlocal) or [`global`](simple_stmts#global). If a name is bound at the module level, it is a global variable. (The variables of the module code block are local and global.) If a variable is used in a code block but not defined there, it is a *free variable*. Each occurrence of a name in the program text refers to the *binding* of that name established by the following name resolution rules. ### 4.2.2. Resolution of names A *scope* defines the visibility of a name within a block. If a local variable is defined in a block, its scope includes that block. If the definition occurs in a function block, the scope extends to any blocks contained within the defining one, unless a contained block introduces a different binding for the name. When a name is used in a code block, it is resolved using the nearest enclosing scope. The set of all such scopes visible to a code block is called the block’s *environment*. When a name is not found at all, a [`NameError`](../library/exceptions#NameError "NameError") exception is raised. If the current scope is a function scope, and the name refers to a local variable that has not yet been bound to a value at the point where the name is used, an [`UnboundLocalError`](../library/exceptions#UnboundLocalError "UnboundLocalError") exception is raised. [`UnboundLocalError`](../library/exceptions#UnboundLocalError "UnboundLocalError") is a subclass of [`NameError`](../library/exceptions#NameError "NameError"). If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block. This can lead to errors when a name is used within a block before it is bound. This rule is subtle. Python lacks declarations and allows name binding operations to occur anywhere within a code block. The local variables of a code block can be determined by scanning the entire text of the block for name binding operations. If the [`global`](simple_stmts#global) statement occurs within a block, all uses of the names specified in the statement refer to the bindings of those names in the top-level namespace. Names are resolved in the top-level namespace by searching the global namespace, i.e. the namespace of the module containing the code block, and the builtins namespace, the namespace of the module [`builtins`](../library/builtins#module-builtins "builtins: The module that provides the built-in namespace."). The global namespace is searched first. If the names are not found there, the builtins namespace is searched. The `global` statement must precede all uses of the listed names. The [`global`](simple_stmts#global) statement has the same scope as a name binding operation in the same block. If the nearest enclosing scope for a free variable contains a global statement, the free variable is treated as a global. The [`nonlocal`](simple_stmts#nonlocal) statement causes corresponding names to refer to previously bound variables in the nearest enclosing function scope. [`SyntaxError`](../library/exceptions#SyntaxError "SyntaxError") is raised at compile time if the given name does not exist in any enclosing function scope. The namespace for a module is automatically created the first time a module is imported. The main module for a script is always called [`__main__`](../library/__main__#module-__main__ "__main__: The environment where the top-level script is run."). Class definition blocks and arguments to [`exec()`](../library/functions#exec "exec") and [`eval()`](../library/functions#eval "eval") are special in the context of name resolution. A class definition is an executable statement that may use and define names. These references follow the normal rules for name resolution with an exception that unbound local variables are looked up in the global namespace. The namespace of the class definition becomes the attribute dictionary of the class. The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods – this includes comprehensions and generator expressions since they are implemented using a function scope. This means that the following will fail: ``` class A: a = 42 b = list(a + i for i in range(10)) ``` ### 4.2.3. Builtins and restricted execution **CPython implementation detail:** Users should not touch `__builtins__`; it is strictly an implementation detail. Users wanting to override values in the builtins namespace should [`import`](simple_stmts#import) the [`builtins`](../library/builtins#module-builtins "builtins: The module that provides the built-in namespace.") module and modify its attributes appropriately. The builtins namespace associated with the execution of a code block is actually found by looking up the name `__builtins__` in its global namespace; this should be a dictionary or a module (in the latter case the module’s dictionary is used). By default, when in the [`__main__`](../library/__main__#module-__main__ "__main__: The environment where the top-level script is run.") module, `__builtins__` is the built-in module [`builtins`](../library/builtins#module-builtins "builtins: The module that provides the built-in namespace."); when in any other module, `__builtins__` is an alias for the dictionary of the [`builtins`](../library/builtins#module-builtins "builtins: The module that provides the built-in namespace.") module itself. ### 4.2.4. Interaction with dynamic features Name resolution of free variables occurs at runtime, not at compile time. This means that the following code will print 42: ``` i = 10 def f(): print(i) i = 42 f() ``` The [`eval()`](../library/functions#eval "eval") and [`exec()`](../library/functions#exec "exec") functions do not have access to the full environment for resolving names. Names may be resolved in the local and global namespaces of the caller. Free variables are not resolved in the nearest enclosing namespace, but in the global namespace. [1](#id3) The [`exec()`](../library/functions#exec "exec") and [`eval()`](../library/functions#eval "eval") functions have optional arguments to override the global and local namespace. If only one namespace is specified, it is used for both. 4.3. Exceptions ---------------- Exceptions are a means of breaking out of the normal flow of control of a code block in order to handle errors or other exceptional conditions. An exception is *raised* at the point where the error is detected; it may be *handled* by the surrounding code block or by any code block that directly or indirectly invoked the code block where the error occurred. The Python interpreter raises an exception when it detects a run-time error (such as division by zero). A Python program can also explicitly raise an exception with the [`raise`](simple_stmts#raise) statement. Exception handlers are specified with the [`try`](compound_stmts#try) … [`except`](compound_stmts#except) statement. The [`finally`](compound_stmts#finally) clause of such a statement can be used to specify cleanup code which does not handle the exception, but is executed whether an exception occurred or not in the preceding code. Python uses the “termination” model of error handling: an exception handler can find out what happened and continue execution at an outer level, but it cannot repair the cause of the error and retry the failing operation (except by re-entering the offending piece of code from the top). When an exception is not handled at all, the interpreter terminates execution of the program, or returns to its interactive main loop. In either case, it prints a stack traceback, except when the exception is [`SystemExit`](../library/exceptions#SystemExit "SystemExit"). Exceptions are identified by class instances. The [`except`](compound_stmts#except) clause is selected depending on the class of the instance: it must reference the class of the instance or a [non-virtual base class](../glossary#term-abstract-base-class) thereof. The instance can be received by the handler and can carry additional information about the exceptional condition. Note Exception messages are not part of the Python API. Their contents may change from one version of Python to the next without warning and should not be relied on by code which will run under multiple versions of the interpreter. See also the description of the [`try`](compound_stmts#try) statement in section [The try statement](compound_stmts#try) and [`raise`](simple_stmts#raise) statement in section [The raise statement](simple_stmts#raise). #### Footnotes `1` This limitation occurs because the code that is executed by these operations is not available at the time the module is compiled. python The import system The import system ================== Python code in one [module](../glossary#term-module) gains access to the code in another module by the process of [importing](../glossary#term-importing) it. The [`import`](simple_stmts#import) statement is the most common way of invoking the import machinery, but it is not the only way. Functions such as [`importlib.import_module()`](../library/importlib#importlib.import_module "importlib.import_module") and built-in [`__import__()`](../library/functions#__import__ "__import__") can also be used to invoke the import machinery. The [`import`](simple_stmts#import) statement combines two operations; it searches for the named module, then it binds the results of that search to a name in the local scope. The search operation of the `import` statement is defined as a call to the [`__import__()`](../library/functions#__import__ "__import__") function, with the appropriate arguments. The return value of [`__import__()`](../library/functions#__import__ "__import__") is used to perform the name binding operation of the `import` statement. See the `import` statement for the exact details of that name binding operation. A direct call to [`__import__()`](../library/functions#__import__ "__import__") performs only the module search and, if found, the module creation operation. While certain side-effects may occur, such as the importing of parent packages, and the updating of various caches (including [`sys.modules`](../library/sys#sys.modules "sys.modules")), only the [`import`](simple_stmts#import) statement performs a name binding operation. When an [`import`](simple_stmts#import) statement is executed, the standard builtin [`__import__()`](../library/functions#__import__ "__import__") function is called. Other mechanisms for invoking the import system (such as [`importlib.import_module()`](../library/importlib#importlib.import_module "importlib.import_module")) may choose to bypass [`__import__()`](../library/functions#__import__ "__import__") and use their own solutions to implement import semantics. When a module is first imported, Python searches for the module and if found, it creates a module object [1](#fnmo), initializing it. If the named module cannot be found, a [`ModuleNotFoundError`](../library/exceptions#ModuleNotFoundError "ModuleNotFoundError") is raised. Python implements various strategies to search for the named module when the import machinery is invoked. These strategies can be modified and extended by using various hooks described in the sections below. Changed in version 3.3: The import system has been updated to fully implement the second phase of [**PEP 302**](https://www.python.org/dev/peps/pep-0302). There is no longer any implicit import machinery - the full import system is exposed through [`sys.meta_path`](../library/sys#sys.meta_path "sys.meta_path"). In addition, native namespace package support has been implemented (see [**PEP 420**](https://www.python.org/dev/peps/pep-0420)). 5.1. importlib --------------- The [`importlib`](../library/importlib#module-importlib "importlib: The implementation of the import machinery.") module provides a rich API for interacting with the import system. For example [`importlib.import_module()`](../library/importlib#importlib.import_module "importlib.import_module") provides a recommended, simpler API than built-in [`__import__()`](../library/functions#__import__ "__import__") for invoking the import machinery. Refer to the [`importlib`](../library/importlib#module-importlib "importlib: The implementation of the import machinery.") library documentation for additional detail. 5.2. Packages -------------- Python has only one type of module object, and all modules are of this type, regardless of whether the module is implemented in Python, C, or something else. To help organize modules and provide a naming hierarchy, Python has a concept of [packages](../glossary#term-package). You can think of packages as the directories on a file system and modules as files within directories, but don’t take this analogy too literally since packages and modules need not originate from the file system. For the purposes of this documentation, we’ll use this convenient analogy of directories and files. Like file system directories, packages are organized hierarchically, and packages may themselves contain subpackages, as well as regular modules. It’s important to keep in mind that all packages are modules, but not all modules are packages. Or put another way, packages are just a special kind of module. Specifically, any module that contains a `__path__` attribute is considered a package. All modules have a name. Subpackage names are separated from their parent package name by a dot, akin to Python’s standard attribute access syntax. Thus you might have a package called [`email`](../library/email#module-email "email: Package supporting the parsing, manipulating, and generating email messages."), which in turn has a subpackage called [`email.mime`](../library/email.mime#module-email.mime "email.mime: Build MIME messages.") and a module within that subpackage called `email.mime.text`. ### 5.2.1. Regular packages Python defines two types of packages, [regular packages](../glossary#term-regular-package) and [namespace packages](../glossary#term-namespace-package). Regular packages are traditional packages as they existed in Python 3.2 and earlier. A regular package is typically implemented as a directory containing an `__init__.py` file. When a regular package is imported, this `__init__.py` file is implicitly executed, and the objects it defines are bound to names in the package’s namespace. The `__init__.py` file can contain the same Python code that any other module can contain, and Python will add some additional attributes to the module when it is imported. For example, the following file system layout defines a top level `parent` package with three subpackages: ``` parent/ __init__.py one/ __init__.py two/ __init__.py three/ __init__.py ``` Importing `parent.one` will implicitly execute `parent/__init__.py` and `parent/one/__init__.py`. Subsequent imports of `parent.two` or `parent.three` will execute `parent/two/__init__.py` and `parent/three/__init__.py` respectively. ### 5.2.2. Namespace packages A namespace package is a composite of various [portions](../glossary#term-portion), where each portion contributes a subpackage to the parent package. Portions may reside in different locations on the file system. Portions may also be found in zip files, on the network, or anywhere else that Python searches during import. Namespace packages may or may not correspond directly to objects on the file system; they may be virtual modules that have no concrete representation. Namespace packages do not use an ordinary list for their `__path__` attribute. They instead use a custom iterable type which will automatically perform a new search for package portions on the next import attempt within that package if the path of their parent package (or [`sys.path`](../library/sys#sys.path "sys.path") for a top level package) changes. With namespace packages, there is no `parent/__init__.py` file. In fact, there may be multiple `parent` directories found during import search, where each one is provided by a different portion. Thus `parent/one` may not be physically located next to `parent/two`. In this case, Python will create a namespace package for the top-level `parent` package whenever it or one of its subpackages is imported. See also [**PEP 420**](https://www.python.org/dev/peps/pep-0420) for the namespace package specification. 5.3. Searching --------------- To begin the search, Python needs the [fully qualified](../glossary#term-qualified-name) name of the module (or package, but for the purposes of this discussion, the difference is immaterial) being imported. This name may come from various arguments to the [`import`](simple_stmts#import) statement, or from the parameters to the [`importlib.import_module()`](../library/importlib#importlib.import_module "importlib.import_module") or [`__import__()`](../library/functions#__import__ "__import__") functions. This name will be used in various phases of the import search, and it may be the dotted path to a submodule, e.g. `foo.bar.baz`. In this case, Python first tries to import `foo`, then `foo.bar`, and finally `foo.bar.baz`. If any of the intermediate imports fail, a [`ModuleNotFoundError`](../library/exceptions#ModuleNotFoundError "ModuleNotFoundError") is raised. ### 5.3.1. The module cache The first place checked during import search is [`sys.modules`](../library/sys#sys.modules "sys.modules"). This mapping serves as a cache of all modules that have been previously imported, including the intermediate paths. So if `foo.bar.baz` was previously imported, [`sys.modules`](../library/sys#sys.modules "sys.modules") will contain entries for `foo`, `foo.bar`, and `foo.bar.baz`. Each key will have as its value the corresponding module object. During import, the module name is looked up in [`sys.modules`](../library/sys#sys.modules "sys.modules") and if present, the associated value is the module satisfying the import, and the process completes. However, if the value is `None`, then a [`ModuleNotFoundError`](../library/exceptions#ModuleNotFoundError "ModuleNotFoundError") is raised. If the module name is missing, Python will continue searching for the module. [`sys.modules`](../library/sys#sys.modules "sys.modules") is writable. Deleting a key may not destroy the associated module (as other modules may hold references to it), but it will invalidate the cache entry for the named module, causing Python to search anew for the named module upon its next import. The key can also be assigned to `None`, forcing the next import of the module to result in a [`ModuleNotFoundError`](../library/exceptions#ModuleNotFoundError "ModuleNotFoundError"). Beware though, as if you keep a reference to the module object, invalidate its cache entry in [`sys.modules`](../library/sys#sys.modules "sys.modules"), and then re-import the named module, the two module objects will *not* be the same. By contrast, [`importlib.reload()`](../library/importlib#importlib.reload "importlib.reload") will reuse the *same* module object, and simply reinitialise the module contents by rerunning the module’s code. ### 5.3.2. Finders and loaders If the named module is not found in [`sys.modules`](../library/sys#sys.modules "sys.modules"), then Python’s import protocol is invoked to find and load the module. This protocol consists of two conceptual objects, [finders](../glossary#term-finder) and [loaders](../glossary#term-loader). A finder’s job is to determine whether it can find the named module using whatever strategy it knows about. Objects that implement both of these interfaces are referred to as [importers](../glossary#term-importer) - they return themselves when they find that they can load the requested module. Python includes a number of default finders and importers. The first one knows how to locate built-in modules, and the second knows how to locate frozen modules. A third default finder searches an [import path](../glossary#term-import-path) for modules. The [import path](../glossary#term-import-path) is a list of locations that may name file system paths or zip files. It can also be extended to search for any locatable resource, such as those identified by URLs. The import machinery is extensible, so new finders can be added to extend the range and scope of module searching. Finders do not actually load modules. If they can find the named module, they return a *module spec*, an encapsulation of the module’s import-related information, which the import machinery then uses when loading the module. The following sections describe the protocol for finders and loaders in more detail, including how you can create and register new ones to extend the import machinery. Changed in version 3.4: In previous versions of Python, finders returned [loaders](../glossary#term-loader) directly, whereas now they return module specs which *contain* loaders. Loaders are still used during import but have fewer responsibilities. ### 5.3.3. Import hooks The import machinery is designed to be extensible; the primary mechanism for this are the *import hooks*. There are two types of import hooks: *meta hooks* and *import path hooks*. Meta hooks are called at the start of import processing, before any other import processing has occurred, other than [`sys.modules`](../library/sys#sys.modules "sys.modules") cache look up. This allows meta hooks to override [`sys.path`](../library/sys#sys.path "sys.path") processing, frozen modules, or even built-in modules. Meta hooks are registered by adding new finder objects to [`sys.meta_path`](../library/sys#sys.meta_path "sys.meta_path"), as described below. Import path hooks are called as part of [`sys.path`](../library/sys#sys.path "sys.path") (or `package.__path__`) processing, at the point where their associated path item is encountered. Import path hooks are registered by adding new callables to [`sys.path_hooks`](../library/sys#sys.path_hooks "sys.path_hooks") as described below. ### 5.3.4. The meta path When the named module is not found in [`sys.modules`](../library/sys#sys.modules "sys.modules"), Python next searches [`sys.meta_path`](../library/sys#sys.meta_path "sys.meta_path"), which contains a list of meta path finder objects. These finders are queried in order to see if they know how to handle the named module. Meta path finders must implement a method called [`find_spec()`](../library/importlib#importlib.abc.MetaPathFinder.find_spec "importlib.abc.MetaPathFinder.find_spec") which takes three arguments: a name, an import path, and (optionally) a target module. The meta path finder can use any strategy it wants to determine whether it can handle the named module or not. If the meta path finder knows how to handle the named module, it returns a spec object. If it cannot handle the named module, it returns `None`. If [`sys.meta_path`](../library/sys#sys.meta_path "sys.meta_path") processing reaches the end of its list without returning a spec, then a [`ModuleNotFoundError`](../library/exceptions#ModuleNotFoundError "ModuleNotFoundError") is raised. Any other exceptions raised are simply propagated up, aborting the import process. The [`find_spec()`](../library/importlib#importlib.abc.MetaPathFinder.find_spec "importlib.abc.MetaPathFinder.find_spec") method of meta path finders is called with two or three arguments. The first is the fully qualified name of the module being imported, for example `foo.bar.baz`. The second argument is the path entries to use for the module search. For top-level modules, the second argument is `None`, but for submodules or subpackages, the second argument is the value of the parent package’s `__path__` attribute. If the appropriate `__path__` attribute cannot be accessed, a [`ModuleNotFoundError`](../library/exceptions#ModuleNotFoundError "ModuleNotFoundError") is raised. The third argument is an existing module object that will be the target of loading later. The import system passes in a target module only during reload. The meta path may be traversed multiple times for a single import request. For example, assuming none of the modules involved has already been cached, importing `foo.bar.baz` will first perform a top level import, calling `mpf.find_spec("foo", None, None)` on each meta path finder (`mpf`). After `foo` has been imported, `foo.bar` will be imported by traversing the meta path a second time, calling `mpf.find_spec("foo.bar", foo.__path__, None)`. Once `foo.bar` has been imported, the final traversal will call `mpf.find_spec("foo.bar.baz", foo.bar.__path__, None)`. Some meta path finders only support top level imports. These importers will always return `None` when anything other than `None` is passed as the second argument. Python’s default [`sys.meta_path`](../library/sys#sys.meta_path "sys.meta_path") has three meta path finders, one that knows how to import built-in modules, one that knows how to import frozen modules, and one that knows how to import modules from an [import path](../glossary#term-import-path) (i.e. the [path based finder](../glossary#term-path-based-finder)). Changed in version 3.4: The [`find_spec()`](../library/importlib#importlib.abc.MetaPathFinder.find_spec "importlib.abc.MetaPathFinder.find_spec") method of meta path finders replaced [`find_module()`](../library/importlib#importlib.abc.MetaPathFinder.find_module "importlib.abc.MetaPathFinder.find_module"), which is now deprecated. While it will continue to work without change, the import machinery will try it only if the finder does not implement `find_spec()`. 5.4. Loading ------------- If and when a module spec is found, the import machinery will use it (and the loader it contains) when loading the module. Here is an approximation of what happens during the loading portion of import: ``` module = None if spec.loader is not None and hasattr(spec.loader, 'create_module'): # It is assumed 'exec_module' will also be defined on the loader. module = spec.loader.create_module(spec) if module is None: module = ModuleType(spec.name) # The import-related module attributes get set here: _init_module_attrs(spec, module) if spec.loader is None: # unsupported raise ImportError if spec.origin is None and spec.submodule_search_locations is not None: # namespace package sys.modules[spec.name] = module elif not hasattr(spec.loader, 'exec_module'): module = spec.loader.load_module(spec.name) # Set __loader__ and __package__ if missing. else: sys.modules[spec.name] = module try: spec.loader.exec_module(module) except BaseException: try: del sys.modules[spec.name] except KeyError: pass raise return sys.modules[spec.name] ``` Note the following details: * If there is an existing module object with the given name in [`sys.modules`](../library/sys#sys.modules "sys.modules"), import will have already returned it. * The module will exist in [`sys.modules`](../library/sys#sys.modules "sys.modules") before the loader executes the module code. This is crucial because the module code may (directly or indirectly) import itself; adding it to [`sys.modules`](../library/sys#sys.modules "sys.modules") beforehand prevents unbounded recursion in the worst case and multiple loading in the best. * If loading fails, the failing module – and only the failing module – gets removed from [`sys.modules`](../library/sys#sys.modules "sys.modules"). Any module already in the [`sys.modules`](../library/sys#sys.modules "sys.modules") cache, and any module that was successfully loaded as a side-effect, must remain in the cache. This contrasts with reloading where even the failing module is left in [`sys.modules`](../library/sys#sys.modules "sys.modules"). * After the module is created but before execution, the import machinery sets the import-related module attributes (“\_init\_module\_attrs” in the pseudo-code example above), as summarized in a [later section](#import-mod-attrs). * Module execution is the key moment of loading in which the module’s namespace gets populated. Execution is entirely delegated to the loader, which gets to decide what gets populated and how. * The module created during loading and passed to exec\_module() may not be the one returned at the end of import [2](#fnlo). Changed in version 3.4: The import system has taken over the boilerplate responsibilities of loaders. These were previously performed by the [`importlib.abc.Loader.load_module()`](../library/importlib#importlib.abc.Loader.load_module "importlib.abc.Loader.load_module") method. ### 5.4.1. Loaders Module loaders provide the critical function of loading: module execution. The import machinery calls the [`importlib.abc.Loader.exec_module()`](../library/importlib#importlib.abc.Loader.exec_module "importlib.abc.Loader.exec_module") method with a single argument, the module object to execute. Any value returned from [`exec_module()`](../library/importlib#importlib.abc.Loader.exec_module "importlib.abc.Loader.exec_module") is ignored. Loaders must satisfy the following requirements: * If the module is a Python module (as opposed to a built-in module or a dynamically loaded extension), the loader should execute the module’s code in the module’s global name space (`module.__dict__`). * If the loader cannot execute the module, it should raise an [`ImportError`](../library/exceptions#ImportError "ImportError"), although any other exception raised during [`exec_module()`](../library/importlib#importlib.abc.Loader.exec_module "importlib.abc.Loader.exec_module") will be propagated. In many cases, the finder and loader can be the same object; in such cases the [`find_spec()`](../library/importlib#importlib.abc.MetaPathFinder.find_spec "importlib.abc.MetaPathFinder.find_spec") method would just return a spec with the loader set to `self`. Module loaders may opt in to creating the module object during loading by implementing a [`create_module()`](../library/importlib#importlib.abc.Loader.create_module "importlib.abc.Loader.create_module") method. It takes one argument, the module spec, and returns the new module object to use during loading. `create_module()` does not need to set any attributes on the module object. If the method returns `None`, the import machinery will create the new module itself. New in version 3.4: The [`create_module()`](../library/importlib#importlib.abc.Loader.create_module "importlib.abc.Loader.create_module") method of loaders. Changed in version 3.4: The [`load_module()`](../library/importlib#importlib.abc.Loader.load_module "importlib.abc.Loader.load_module") method was replaced by [`exec_module()`](../library/importlib#importlib.abc.Loader.exec_module "importlib.abc.Loader.exec_module") and the import machinery assumed all the boilerplate responsibilities of loading. For compatibility with existing loaders, the import machinery will use the `load_module()` method of loaders if it exists and the loader does not also implement `exec_module()`. However, `load_module()` has been deprecated and loaders should implement `exec_module()` instead. The `load_module()` method must implement all the boilerplate loading functionality described above in addition to executing the module. All the same constraints apply, with some additional clarification: * If there is an existing module object with the given name in [`sys.modules`](../library/sys#sys.modules "sys.modules"), the loader must use that existing module. (Otherwise, [`importlib.reload()`](../library/importlib#importlib.reload "importlib.reload") will not work correctly.) If the named module does not exist in [`sys.modules`](../library/sys#sys.modules "sys.modules"), the loader must create a new module object and add it to [`sys.modules`](../library/sys#sys.modules "sys.modules"). * The module *must* exist in [`sys.modules`](../library/sys#sys.modules "sys.modules") before the loader executes the module code, to prevent unbounded recursion or multiple loading. * If loading fails, the loader must remove any modules it has inserted into [`sys.modules`](../library/sys#sys.modules "sys.modules"), but it must remove **only** the failing module(s), and only if the loader itself has loaded the module(s) explicitly. Changed in version 3.5: A [`DeprecationWarning`](../library/exceptions#DeprecationWarning "DeprecationWarning") is raised when `exec_module()` is defined but `create_module()` is not. Changed in version 3.6: An [`ImportError`](../library/exceptions#ImportError "ImportError") is raised when `exec_module()` is defined but `create_module()` is not. ### 5.4.2. Submodules When a submodule is loaded using any mechanism (e.g. `importlib` APIs, the `import` or `import-from` statements, or built-in `__import__()`) a binding is placed in the parent module’s namespace to the submodule object. For example, if package `spam` has a submodule `foo`, after importing `spam.foo`, `spam` will have an attribute `foo` which is bound to the submodule. Let’s say you have the following directory structure: ``` spam/ __init__.py foo.py ``` and `spam/__init__.py` has the following line in it: ``` from .foo import Foo ``` then executing the following puts name bindings for `foo` and `Foo` in the `spam` module: ``` >>> import spam >>> spam.foo <module 'spam.foo' from '/tmp/imports/spam/foo.py'> >>> spam.Foo <class 'spam.foo.Foo'> ``` Given Python’s familiar name binding rules this might seem surprising, but it’s actually a fundamental feature of the import system. The invariant holding is that if you have `sys.modules['spam']` and `sys.modules['spam.foo']` (as you would after the above import), the latter must appear as the `foo` attribute of the former. ### 5.4.3. Module spec The import machinery uses a variety of information about each module during import, especially before loading. Most of the information is common to all modules. The purpose of a module’s spec is to encapsulate this import-related information on a per-module basis. Using a spec during import allows state to be transferred between import system components, e.g. between the finder that creates the module spec and the loader that executes it. Most importantly, it allows the import machinery to perform the boilerplate operations of loading, whereas without a module spec the loader had that responsibility. The module’s spec is exposed as the `__spec__` attribute on a module object. See [`ModuleSpec`](../library/importlib#importlib.machinery.ModuleSpec "importlib.machinery.ModuleSpec") for details on the contents of the module spec. New in version 3.4. ### 5.4.4. Import-related module attributes The import machinery fills in these attributes on each module object during loading, based on the module’s spec, before the loader executes the module. `__name__` The `__name__` attribute must be set to the fully-qualified name of the module. This name is used to uniquely identify the module in the import system. `__loader__` The `__loader__` attribute must be set to the loader object that the import machinery used when loading the module. This is mostly for introspection, but can be used for additional loader-specific functionality, for example getting data associated with a loader. `__package__` The module’s `__package__` attribute must be set. Its value must be a string, but it can be the same value as its `__name__`. When the module is a package, its `__package__` value should be set to its `__name__`. When the module is not a package, `__package__` should be set to the empty string for top-level modules, or for submodules, to the parent package’s name. See [**PEP 366**](https://www.python.org/dev/peps/pep-0366) for further details. This attribute is used instead of `__name__` to calculate explicit relative imports for main modules, as defined in [**PEP 366**](https://www.python.org/dev/peps/pep-0366). It is expected to have the same value as `__spec__.parent`. Changed in version 3.6: The value of `__package__` is expected to be the same as `__spec__.parent`. `__spec__` The `__spec__` attribute must be set to the module spec that was used when importing the module. Setting `__spec__` appropriately applies equally to [modules initialized during interpreter startup](toplevel_components#programs). The one exception is `__main__`, where `__spec__` is [set to None in some cases](#main-spec). When `__package__` is not defined, `__spec__.parent` is used as a fallback. New in version 3.4. Changed in version 3.6: `__spec__.parent` is used as a fallback when `__package__` is not defined. `__path__` If the module is a package (either regular or namespace), the module object’s `__path__` attribute must be set. The value must be iterable, but may be empty if `__path__` has no further significance. If `__path__` is not empty, it must produce strings when iterated over. More details on the semantics of `__path__` are given [below](#package-path-rules). Non-package modules should not have a `__path__` attribute. `__file__` `__cached__` `__file__` is optional. If set, this attribute’s value must be a string. The import system may opt to leave `__file__` unset if it has no semantic meaning (e.g. a module loaded from a database). If `__file__` is set, it may also be appropriate to set the `__cached__` attribute which is the path to any compiled version of the code (e.g. byte-compiled file). The file does not need to exist to set this attribute; the path can simply point to where the compiled file would exist (see [**PEP 3147**](https://www.python.org/dev/peps/pep-3147)). It is also appropriate to set `__cached__` when `__file__` is not set. However, that scenario is quite atypical. Ultimately, the loader is what makes use of `__file__` and/or `__cached__`. So if a loader can load from a cached module but otherwise does not load from a file, that atypical scenario may be appropriate. ### 5.4.5. module.\_\_path\_\_ By definition, if a module has a `__path__` attribute, it is a package. A package’s `__path__` attribute is used during imports of its subpackages. Within the import machinery, it functions much the same as [`sys.path`](../library/sys#sys.path "sys.path"), i.e. providing a list of locations to search for modules during import. However, `__path__` is typically much more constrained than [`sys.path`](../library/sys#sys.path "sys.path"). `__path__` must be an iterable of strings, but it may be empty. The same rules used for [`sys.path`](../library/sys#sys.path "sys.path") also apply to a package’s `__path__`, and [`sys.path_hooks`](../library/sys#sys.path_hooks "sys.path_hooks") (described below) are consulted when traversing a package’s `__path__`. A package’s `__init__.py` file may set or alter the package’s `__path__` attribute, and this was typically the way namespace packages were implemented prior to [**PEP 420**](https://www.python.org/dev/peps/pep-0420). With the adoption of [**PEP 420**](https://www.python.org/dev/peps/pep-0420), namespace packages no longer need to supply `__init__.py` files containing only `__path__` manipulation code; the import machinery automatically sets `__path__` correctly for the namespace package. ### 5.4.6. Module reprs By default, all modules have a usable repr, however depending on the attributes set above, and in the module’s spec, you can more explicitly control the repr of module objects. If the module has a spec (`__spec__`), the import machinery will try to generate a repr from it. If that fails or there is no spec, the import system will craft a default repr using whatever information is available on the module. It will try to use the `module.__name__`, `module.__file__`, and `module.__loader__` as input into the repr, with defaults for whatever information is missing. Here are the exact rules used: * If the module has a `__spec__` attribute, the information in the spec is used to generate the repr. The “name”, “loader”, “origin”, and “has\_location” attributes are consulted. * If the module has a `__file__` attribute, this is used as part of the module’s repr. * If the module has no `__file__` but does have a `__loader__` that is not `None`, then the loader’s repr is used as part of the module’s repr. * Otherwise, just use the module’s `__name__` in the repr. Changed in version 3.4: Use of [`loader.module_repr()`](../library/importlib#importlib.abc.Loader.module_repr "importlib.abc.Loader.module_repr") has been deprecated and the module spec is now used by the import machinery to generate a module repr. For backward compatibility with Python 3.3, the module repr will be generated by calling the loader’s [`module_repr()`](../library/importlib#importlib.abc.Loader.module_repr "importlib.abc.Loader.module_repr") method, if defined, before trying either approach described above. However, the method is deprecated. ### 5.4.7. Cached bytecode invalidation Before Python loads cached bytecode from a `.pyc` file, it checks whether the cache is up-to-date with the source `.py` file. By default, Python does this by storing the source’s last-modified timestamp and size in the cache file when writing it. At runtime, the import system then validates the cache file by checking the stored metadata in the cache file against the source’s metadata. Python also supports “hash-based” cache files, which store a hash of the source file’s contents rather than its metadata. There are two variants of hash-based `.pyc` files: checked and unchecked. For checked hash-based `.pyc` files, Python validates the cache file by hashing the source file and comparing the resulting hash with the hash in the cache file. If a checked hash-based cache file is found to be invalid, Python regenerates it and writes a new checked hash-based cache file. For unchecked hash-based `.pyc` files, Python simply assumes the cache file is valid if it exists. Hash-based `.pyc` files validation behavior may be overridden with the [`--check-hash-based-pycs`](../using/cmdline#cmdoption-check-hash-based-pycs) flag. Changed in version 3.7: Added hash-based `.pyc` files. Previously, Python only supported timestamp-based invalidation of bytecode caches. 5.5. The Path Based Finder --------------------------- As mentioned previously, Python comes with several default meta path finders. One of these, called the [path based finder](../glossary#term-path-based-finder) ([`PathFinder`](../library/importlib#importlib.machinery.PathFinder "importlib.machinery.PathFinder")), searches an [import path](../glossary#term-import-path), which contains a list of [path entries](../glossary#term-path-entry). Each path entry names a location to search for modules. The path based finder itself doesn’t know how to import anything. Instead, it traverses the individual path entries, associating each of them with a path entry finder that knows how to handle that particular kind of path. The default set of path entry finders implement all the semantics for finding modules on the file system, handling special file types such as Python source code (`.py` files), Python byte code (`.pyc` files) and shared libraries (e.g. `.so` files). When supported by the [`zipimport`](../library/zipimport#module-zipimport "zipimport: Support for importing Python modules from ZIP archives.") module in the standard library, the default path entry finders also handle loading all of these file types (other than shared libraries) from zipfiles. Path entries need not be limited to file system locations. They can refer to URLs, database queries, or any other location that can be specified as a string. The path based finder provides additional hooks and protocols so that you can extend and customize the types of searchable path entries. For example, if you wanted to support path entries as network URLs, you could write a hook that implements HTTP semantics to find modules on the web. This hook (a callable) would return a [path entry finder](../glossary#term-path-entry-finder) supporting the protocol described below, which was then used to get a loader for the module from the web. A word of warning: this section and the previous both use the term *finder*, distinguishing between them by using the terms [meta path finder](../glossary#term-meta-path-finder) and [path entry finder](../glossary#term-path-entry-finder). These two types of finders are very similar, support similar protocols, and function in similar ways during the import process, but it’s important to keep in mind that they are subtly different. In particular, meta path finders operate at the beginning of the import process, as keyed off the [`sys.meta_path`](../library/sys#sys.meta_path "sys.meta_path") traversal. By contrast, path entry finders are in a sense an implementation detail of the path based finder, and in fact, if the path based finder were to be removed from [`sys.meta_path`](../library/sys#sys.meta_path "sys.meta_path"), none of the path entry finder semantics would be invoked. ### 5.5.1. Path entry finders The [path based finder](../glossary#term-path-based-finder) is responsible for finding and loading Python modules and packages whose location is specified with a string [path entry](../glossary#term-path-entry). Most path entries name locations in the file system, but they need not be limited to this. As a meta path finder, the [path based finder](../glossary#term-path-based-finder) implements the [`find_spec()`](../library/importlib#importlib.abc.MetaPathFinder.find_spec "importlib.abc.MetaPathFinder.find_spec") protocol previously described, however it exposes additional hooks that can be used to customize how modules are found and loaded from the [import path](../glossary#term-import-path). Three variables are used by the [path based finder](../glossary#term-path-based-finder), [`sys.path`](../library/sys#sys.path "sys.path"), [`sys.path_hooks`](../library/sys#sys.path_hooks "sys.path_hooks") and [`sys.path_importer_cache`](../library/sys#sys.path_importer_cache "sys.path_importer_cache"). The `__path__` attributes on package objects are also used. These provide additional ways that the import machinery can be customized. [`sys.path`](../library/sys#sys.path "sys.path") contains a list of strings providing search locations for modules and packages. It is initialized from the `PYTHONPATH` environment variable and various other installation- and implementation-specific defaults. Entries in [`sys.path`](../library/sys#sys.path "sys.path") can name directories on the file system, zip files, and potentially other “locations” (see the [`site`](../library/site#module-site "site: Module responsible for site-specific configuration.") module) that should be searched for modules, such as URLs, or database queries. Only strings and bytes should be present on [`sys.path`](../library/sys#sys.path "sys.path"); all other data types are ignored. The encoding of bytes entries is determined by the individual [path entry finders](../glossary#term-path-entry-finder). The [path based finder](../glossary#term-path-based-finder) is a [meta path finder](../glossary#term-meta-path-finder), so the import machinery begins the [import path](../glossary#term-import-path) search by calling the path based finder’s [`find_spec()`](../library/importlib#importlib.machinery.PathFinder.find_spec "importlib.machinery.PathFinder.find_spec") method as described previously. When the `path` argument to [`find_spec()`](../library/importlib#importlib.machinery.PathFinder.find_spec "importlib.machinery.PathFinder.find_spec") is given, it will be a list of string paths to traverse - typically a package’s `__path__` attribute for an import within that package. If the `path` argument is `None`, this indicates a top level import and [`sys.path`](../library/sys#sys.path "sys.path") is used. The path based finder iterates over every entry in the search path, and for each of these, looks for an appropriate [path entry finder](../glossary#term-path-entry-finder) ([`PathEntryFinder`](../library/importlib#importlib.abc.PathEntryFinder "importlib.abc.PathEntryFinder")) for the path entry. Because this can be an expensive operation (e.g. there may be `stat()` call overheads for this search), the path based finder maintains a cache mapping path entries to path entry finders. This cache is maintained in [`sys.path_importer_cache`](../library/sys#sys.path_importer_cache "sys.path_importer_cache") (despite the name, this cache actually stores finder objects rather than being limited to [importer](../glossary#term-importer) objects). In this way, the expensive search for a particular [path entry](../glossary#term-path-entry) location’s [path entry finder](../glossary#term-path-entry-finder) need only be done once. User code is free to remove cache entries from [`sys.path_importer_cache`](../library/sys#sys.path_importer_cache "sys.path_importer_cache") forcing the path based finder to perform the path entry search again [3](#fnpic). If the path entry is not present in the cache, the path based finder iterates over every callable in [`sys.path_hooks`](../library/sys#sys.path_hooks "sys.path_hooks"). Each of the [path entry hooks](../glossary#term-path-entry-hook) in this list is called with a single argument, the path entry to be searched. This callable may either return a [path entry finder](../glossary#term-path-entry-finder) that can handle the path entry, or it may raise [`ImportError`](../library/exceptions#ImportError "ImportError"). An [`ImportError`](../library/exceptions#ImportError "ImportError") is used by the path based finder to signal that the hook cannot find a [path entry finder](../glossary#term-path-entry-finder) for that [path entry](../glossary#term-path-entry). The exception is ignored and [import path](../glossary#term-import-path) iteration continues. The hook should expect either a string or bytes object; the encoding of bytes objects is up to the hook (e.g. it may be a file system encoding, UTF-8, or something else), and if the hook cannot decode the argument, it should raise [`ImportError`](../library/exceptions#ImportError "ImportError"). If [`sys.path_hooks`](../library/sys#sys.path_hooks "sys.path_hooks") iteration ends with no [path entry finder](../glossary#term-path-entry-finder) being returned, then the path based finder’s [`find_spec()`](../library/importlib#importlib.machinery.PathFinder.find_spec "importlib.machinery.PathFinder.find_spec") method will store `None` in [`sys.path_importer_cache`](../library/sys#sys.path_importer_cache "sys.path_importer_cache") (to indicate that there is no finder for this path entry) and return `None`, indicating that this [meta path finder](../glossary#term-meta-path-finder) could not find the module. If a [path entry finder](../glossary#term-path-entry-finder) *is* returned by one of the [path entry hook](../glossary#term-path-entry-hook) callables on [`sys.path_hooks`](../library/sys#sys.path_hooks "sys.path_hooks"), then the following protocol is used to ask the finder for a module spec, which is then used when loading the module. The current working directory – denoted by an empty string – is handled slightly differently from other entries on [`sys.path`](../library/sys#sys.path "sys.path"). First, if the current working directory is found to not exist, no value is stored in [`sys.path_importer_cache`](../library/sys#sys.path_importer_cache "sys.path_importer_cache"). Second, the value for the current working directory is looked up fresh for each module lookup. Third, the path used for [`sys.path_importer_cache`](../library/sys#sys.path_importer_cache "sys.path_importer_cache") and returned by [`importlib.machinery.PathFinder.find_spec()`](../library/importlib#importlib.machinery.PathFinder.find_spec "importlib.machinery.PathFinder.find_spec") will be the actual current working directory and not the empty string. ### 5.5.2. Path entry finder protocol In order to support imports of modules and initialized packages and also to contribute portions to namespace packages, path entry finders must implement the [`find_spec()`](../library/importlib#importlib.abc.PathEntryFinder.find_spec "importlib.abc.PathEntryFinder.find_spec") method. [`find_spec()`](../library/importlib#importlib.abc.PathEntryFinder.find_spec "importlib.abc.PathEntryFinder.find_spec") takes two arguments: the fully qualified name of the module being imported, and the (optional) target module. `find_spec()` returns a fully populated spec for the module. This spec will always have “loader” set (with one exception). To indicate to the import machinery that the spec represents a namespace [portion](../glossary#term-portion), the path entry finder sets “submodule\_search\_locations” to a list containing the portion. Changed in version 3.4: [`find_spec()`](../library/importlib#importlib.abc.PathEntryFinder.find_spec "importlib.abc.PathEntryFinder.find_spec") replaced [`find_loader()`](../library/importlib#importlib.abc.PathEntryFinder.find_loader "importlib.abc.PathEntryFinder.find_loader") and [`find_module()`](../library/importlib#importlib.abc.PathEntryFinder.find_module "importlib.abc.PathEntryFinder.find_module"), both of which are now deprecated, but will be used if `find_spec()` is not defined. Older path entry finders may implement one of these two deprecated methods instead of `find_spec()`. The methods are still respected for the sake of backward compatibility. However, if `find_spec()` is implemented on the path entry finder, the legacy methods are ignored. [`find_loader()`](../library/importlib#importlib.abc.PathEntryFinder.find_loader "importlib.abc.PathEntryFinder.find_loader") takes one argument, the fully qualified name of the module being imported. `find_loader()` returns a 2-tuple where the first item is the loader and the second item is a namespace [portion](../glossary#term-portion). For backwards compatibility with other implementations of the import protocol, many path entry finders also support the same, traditional `find_module()` method that meta path finders support. However path entry finder `find_module()` methods are never called with a `path` argument (they are expected to record the appropriate path information from the initial call to the path hook). The `find_module()` method on path entry finders is deprecated, as it does not allow the path entry finder to contribute portions to namespace packages. If both `find_loader()` and `find_module()` exist on a path entry finder, the import system will always call `find_loader()` in preference to `find_module()`. 5.6. Replacing the standard import system ------------------------------------------ The most reliable mechanism for replacing the entire import system is to delete the default contents of [`sys.meta_path`](../library/sys#sys.meta_path "sys.meta_path"), replacing them entirely with a custom meta path hook. If it is acceptable to only alter the behaviour of import statements without affecting other APIs that access the import system, then replacing the builtin [`__import__()`](../library/functions#__import__ "__import__") function may be sufficient. This technique may also be employed at the module level to only alter the behaviour of import statements within that module. To selectively prevent the import of some modules from a hook early on the meta path (rather than disabling the standard import system entirely), it is sufficient to raise [`ModuleNotFoundError`](../library/exceptions#ModuleNotFoundError "ModuleNotFoundError") directly from [`find_spec()`](../library/importlib#importlib.abc.MetaPathFinder.find_spec "importlib.abc.MetaPathFinder.find_spec") instead of returning `None`. The latter indicates that the meta path search should continue, while raising an exception terminates it immediately. 5.7. Package Relative Imports ------------------------------ Relative imports use leading dots. A single leading dot indicates a relative import, starting with the current package. Two or more leading dots indicate a relative import to the parent(s) of the current package, one level per dot after the first. For example, given the following package layout: ``` package/ __init__.py subpackage1/ __init__.py moduleX.py moduleY.py subpackage2/ __init__.py moduleZ.py moduleA.py ``` In either `subpackage1/moduleX.py` or `subpackage1/__init__.py`, the following are valid relative imports: ``` from .moduleY import spam from .moduleY import spam as ham from . import moduleY from ..subpackage1 import moduleY from ..subpackage2.moduleZ import eggs from ..moduleA import foo ``` Absolute imports may use either the `import <>` or `from <> import <>` syntax, but relative imports may only use the second form; the reason for this is that: ``` import XXX.YYY.ZZZ ``` should expose `XXX.YYY.ZZZ` as a usable expression, but .moduleY is not a valid expression. 5.8. Special considerations for \_\_main\_\_ --------------------------------------------- The [`__main__`](../library/__main__#module-__main__ "__main__: The environment where the top-level script is run.") module is a special case relative to Python’s import system. As noted [elsewhere](toplevel_components#programs), the `__main__` module is directly initialized at interpreter startup, much like [`sys`](../library/sys#module-sys "sys: Access system-specific parameters and functions.") and [`builtins`](../library/builtins#module-builtins "builtins: The module that provides the built-in namespace."). However, unlike those two, it doesn’t strictly qualify as a built-in module. This is because the manner in which `__main__` is initialized depends on the flags and other options with which the interpreter is invoked. ### 5.8.1. \_\_main\_\_.\_\_spec\_\_ Depending on how [`__main__`](../library/__main__#module-__main__ "__main__: The environment where the top-level script is run.") is initialized, `__main__.__spec__` gets set appropriately or to `None`. When Python is started with the [`-m`](../using/cmdline#cmdoption-m) option, `__spec__` is set to the module spec of the corresponding module or package. `__spec__` is also populated when the `__main__` module is loaded as part of executing a directory, zipfile or other [`sys.path`](../library/sys#sys.path "sys.path") entry. In [the remaining cases](../using/cmdline#using-on-interface-options) `__main__.__spec__` is set to `None`, as the code used to populate the [`__main__`](../library/__main__#module-__main__ "__main__: The environment where the top-level script is run.") does not correspond directly with an importable module: * interactive prompt * [`-c`](../using/cmdline#cmdoption-c) option * running from stdin * running directly from a source or bytecode file Note that `__main__.__spec__` is always `None` in the last case, *even if* the file could technically be imported directly as a module instead. Use the [`-m`](../using/cmdline#cmdoption-m) switch if valid module metadata is desired in [`__main__`](../library/__main__#module-__main__ "__main__: The environment where the top-level script is run."). Note also that even when `__main__` corresponds with an importable module and `__main__.__spec__` is set accordingly, they’re still considered *distinct* modules. This is due to the fact that blocks guarded by `if __name__ == "__main__":` checks only execute when the module is used to populate the `__main__` namespace, and not during normal import. 5.9. Open issues ----------------- XXX It would be really nice to have a diagram. XXX \* (import\_machinery.rst) how about a section devoted just to the attributes of modules and packages, perhaps expanding upon or supplanting the related entries in the data model reference page? XXX runpy, pkgutil, et al in the library manual should all get “See Also” links at the top pointing to the new import system section. XXX Add more explanation regarding the different ways in which `__main__` is initialized? XXX Add more info on `__main__` quirks/pitfalls (i.e. copy from [**PEP 395**](https://www.python.org/dev/peps/pep-0395)). 5.10. References ----------------- The import machinery has evolved considerably since Python’s early days. The original [specification for packages](https://www.python.org/doc/essays/packages/) is still available to read, although some details have changed since the writing of that document. The original specification for [`sys.meta_path`](../library/sys#sys.meta_path "sys.meta_path") was [**PEP 302**](https://www.python.org/dev/peps/pep-0302), with subsequent extension in [**PEP 420**](https://www.python.org/dev/peps/pep-0420). [**PEP 420**](https://www.python.org/dev/peps/pep-0420) introduced [namespace packages](../glossary#term-namespace-package) for Python 3.3. [**PEP 420**](https://www.python.org/dev/peps/pep-0420) also introduced the `find_loader()` protocol as an alternative to `find_module()`. [**PEP 366**](https://www.python.org/dev/peps/pep-0366) describes the addition of the `__package__` attribute for explicit relative imports in main modules. [**PEP 328**](https://www.python.org/dev/peps/pep-0328) introduced absolute and explicit relative imports and initially proposed `__name__` for semantics [**PEP 366**](https://www.python.org/dev/peps/pep-0366) would eventually specify for `__package__`. [**PEP 338**](https://www.python.org/dev/peps/pep-0338) defines executing modules as scripts. [**PEP 451**](https://www.python.org/dev/peps/pep-0451) adds the encapsulation of per-module import state in spec objects. It also off-loads most of the boilerplate responsibilities of loaders back onto the import machinery. These changes allow the deprecation of several APIs in the import system and also addition of new methods to finders and loaders. #### Footnotes `1` See [`types.ModuleType`](../library/types#types.ModuleType "types.ModuleType"). `2` The importlib implementation avoids using the return value directly. Instead, it gets the module object by looking the module name up in [`sys.modules`](../library/sys#sys.modules "sys.modules"). The indirect effect of this is that an imported module may replace itself in [`sys.modules`](../library/sys#sys.modules "sys.modules"). This is implementation-specific behavior that is not guaranteed to work in other Python implementations. `3` In legacy code, it is possible to find instances of [`imp.NullImporter`](../library/imp#imp.NullImporter "imp.NullImporter") in the [`sys.path_importer_cache`](../library/sys#sys.path_importer_cache "sys.path_importer_cache"). It is recommended that code be changed to use `None` instead. See [Porting Python code](https://docs.python.org/3.9/whatsnew/3.3.html#portingpythoncode) for more details.
programming_docs
python Expressions Expressions ============ This chapter explains the meaning of the elements of expressions in Python. **Syntax Notes:** In this and the following chapters, extended BNF notation will be used to describe syntax, not lexical analysis. When (one alternative of) a syntax rule has the form ``` **name** ::= othername ``` and no semantics are given, the semantics of this form of `name` are the same as for `othername`. 6.1. Arithmetic conversions ---------------------------- When a description of an arithmetic operator below uses the phrase “the numeric arguments are converted to a common type”, this means that the operator implementation for built-in types works as follows: * If either argument is a complex number, the other is converted to complex; * otherwise, if either argument is a floating point number, the other is converted to floating point; * otherwise, both must be integers and no conversion is necessary. Some additional rules apply for certain operators (e.g., a string as a left argument to the ‘%’ operator). Extensions must define their own conversion behavior. 6.2. Atoms ----------- Atoms are the most basic elements of expressions. The simplest atoms are identifiers or literals. Forms enclosed in parentheses, brackets or braces are also categorized syntactically as atoms. The syntax for atoms is: ``` **atom** ::= [identifier](lexical_analysis#grammar-token-identifier) | [literal](#grammar-token-literal) | [enclosure](#grammar-token-enclosure) **enclosure** ::= [parenth\_form](#grammar-token-parenth-form) | [list\_display](#grammar-token-list-display) | [dict\_display](#grammar-token-dict-display) | [set\_display](#grammar-token-set-display) | [generator\_expression](#grammar-token-generator-expression) | [yield\_atom](#grammar-token-yield-atom) ``` ### 6.2.1. Identifiers (Names) An identifier occurring as an atom is a name. See section [Identifiers and keywords](lexical_analysis#identifiers) for lexical definition and section [Naming and binding](executionmodel#naming) for documentation of naming and binding. When the name is bound to an object, evaluation of the atom yields that object. When a name is not bound, an attempt to evaluate it raises a [`NameError`](../library/exceptions#NameError "NameError") exception. **Private name mangling:** When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a *private name* of that class. Private names are transformed to a longer form before code is generated for them. The transformation inserts the class name, with leading underscores removed and a single underscore inserted, in front of the name. For example, the identifier `__spam` occurring in a class named `Ham` will be transformed to `_Ham__spam`. This transformation is independent of the syntactical context in which the identifier is used. If the transformed name is extremely long (longer than 255 characters), implementation defined truncation may happen. If the class name consists only of underscores, no transformation is done. ### 6.2.2. Literals Python supports string and bytes literals and various numeric literals: ``` **literal** ::= [stringliteral](lexical_analysis#grammar-token-stringliteral) | [bytesliteral](lexical_analysis#grammar-token-bytesliteral) | [integer](lexical_analysis#grammar-token-integer) | [floatnumber](lexical_analysis#grammar-token-floatnumber) | [imagnumber](lexical_analysis#grammar-token-imagnumber) ``` Evaluation of a literal yields an object of the given type (string, bytes, integer, floating point number, complex number) with the given value. The value may be approximated in the case of floating point and imaginary (complex) literals. See section [Literals](lexical_analysis#literals) for details. All literals correspond to immutable data types, and hence the object’s identity is less important than its value. Multiple evaluations of literals with the same value (either the same occurrence in the program text or a different occurrence) may obtain the same object or a different object with the same value. ### 6.2.3. Parenthesized forms A parenthesized form is an optional expression list enclosed in parentheses: ``` **parenth\_form** ::= "(" [[starred\_expression](#grammar-token-starred-expression)] ")" ``` A parenthesized expression list yields whatever that expression list yields: if the list contains at least one comma, it yields a tuple; otherwise, it yields the single expression that makes up the expression list. An empty pair of parentheses yields an empty tuple object. Since tuples are immutable, the same rules as for literals apply (i.e., two occurrences of the empty tuple may or may not yield the same object). Note that tuples are not formed by the parentheses, but rather by use of the comma operator. The exception is the empty tuple, for which parentheses *are* required — allowing unparenthesized “nothing” in expressions would cause ambiguities and allow common typos to pass uncaught. ### 6.2.4. Displays for lists, sets and dictionaries For constructing a list, a set or a dictionary Python provides special syntax called “displays”, each of them in two flavors: * either the container contents are listed explicitly, or * they are computed via a set of looping and filtering instructions, called a *comprehension*. Common syntax elements for comprehensions are: ``` **comprehension** ::= [assignment\_expression](#grammar-token-assignment-expression) [comp\_for](#grammar-token-comp-for) **comp\_for** ::= ["async"] "for" [target\_list](simple_stmts#grammar-token-target-list) "in" [or\_test](#grammar-token-or-test) [[comp\_iter](#grammar-token-comp-iter)] **comp\_iter** ::= [comp\_for](#grammar-token-comp-for) | [comp\_if](#grammar-token-comp-if) **comp\_if** ::= "if" [or\_test](#grammar-token-or-test) [[comp\_iter](#grammar-token-comp-iter)] ``` The comprehension consists of a single expression followed by at least one `for` clause and zero or more `for` or `if` clauses. In this case, the elements of the new container are those that would be produced by considering each of the `for` or `if` clauses a block, nesting from left to right, and evaluating the expression to produce an element each time the innermost block is reached. However, aside from the iterable expression in the leftmost `for` clause, the comprehension is executed in a separate implicitly nested scope. This ensures that names assigned to in the target list don’t “leak” into the enclosing scope. The iterable expression in the leftmost `for` clause is evaluated directly in the enclosing scope and then passed as an argument to the implicitly nested scope. Subsequent `for` clauses and any filter condition in the leftmost `for` clause cannot be evaluated in the enclosing scope as they may depend on the values obtained from the leftmost iterable. For example: `[x*y for x in range(10) for y in range(x, x+10)]`. To ensure the comprehension always results in a container of the appropriate type, `yield` and `yield from` expressions are prohibited in the implicitly nested scope. Since Python 3.6, in an [`async def`](compound_stmts#async-def) function, an `async for` clause may be used to iterate over a [asynchronous iterator](../glossary#term-asynchronous-iterator). A comprehension in an `async def` function may consist of either a `for` or `async for` clause following the leading expression, may contain additional `for` or `async for` clauses, and may also use [`await`](#await) expressions. If a comprehension contains either `async for` clauses or `await` expressions it is called an *asynchronous comprehension*. An asynchronous comprehension may suspend the execution of the coroutine function in which it appears. See also [**PEP 530**](https://www.python.org/dev/peps/pep-0530). New in version 3.6: Asynchronous comprehensions were introduced. Changed in version 3.8: `yield` and `yield from` prohibited in the implicitly nested scope. ### 6.2.5. List displays A list display is a possibly empty series of expressions enclosed in square brackets: ``` **list\_display** ::= "[" [[starred\_list](#grammar-token-starred-list) | [comprehension](#grammar-token-comprehension)] "]" ``` A list display yields a new list object, the contents being specified by either a list of expressions or a comprehension. When a comma-separated list of expressions is supplied, its elements are evaluated from left to right and placed into the list object in that order. When a comprehension is supplied, the list is constructed from the elements resulting from the comprehension. ### 6.2.6. Set displays A set display is denoted by curly braces and distinguishable from dictionary displays by the lack of colons separating keys and values: ``` **set\_display** ::= "{" ([starred\_list](#grammar-token-starred-list) | [comprehension](#grammar-token-comprehension)) "}" ``` A set display yields a new mutable set object, the contents being specified by either a sequence of expressions or a comprehension. When a comma-separated list of expressions is supplied, its elements are evaluated from left to right and added to the set object. When a comprehension is supplied, the set is constructed from the elements resulting from the comprehension. An empty set cannot be constructed with `{}`; this literal constructs an empty dictionary. ### 6.2.7. Dictionary displays A dictionary display is a possibly empty series of key/datum pairs enclosed in curly braces: ``` **dict\_display** ::= "{" [[key\_datum\_list](#grammar-token-key-datum-list) | [dict\_comprehension](#grammar-token-dict-comprehension)] "}" **key\_datum\_list** ::= [key\_datum](#grammar-token-key-datum) ("," [key\_datum](#grammar-token-key-datum))* [","] **key\_datum** ::= [expression](#grammar-token-expression) ":" [expression](#grammar-token-expression) | "**" [or\_expr](#grammar-token-or-expr) **dict\_comprehension** ::= [expression](#grammar-token-expression) ":" [expression](#grammar-token-expression) [comp\_for](#grammar-token-comp-for) ``` A dictionary display yields a new dictionary object. If a comma-separated sequence of key/datum pairs is given, they are evaluated from left to right to define the entries of the dictionary: each key object is used as a key into the dictionary to store the corresponding datum. This means that you can specify the same key multiple times in the key/datum list, and the final dictionary’s value for that key will be the last one given. A double asterisk `**` denotes *dictionary unpacking*. Its operand must be a [mapping](../glossary#term-mapping). Each mapping item is added to the new dictionary. Later values replace values already set by earlier key/datum pairs and earlier dictionary unpackings. New in version 3.5: Unpacking into dictionary displays, originally proposed by [**PEP 448**](https://www.python.org/dev/peps/pep-0448). A dict comprehension, in contrast to list and set comprehensions, needs two expressions separated with a colon followed by the usual “for” and “if” clauses. When the comprehension is run, the resulting key and value elements are inserted in the new dictionary in the order they are produced. Restrictions on the types of the key values are listed earlier in section [The standard type hierarchy](datamodel#types). (To summarize, the key type should be [hashable](../glossary#term-hashable), which excludes all mutable objects.) Clashes between duplicate keys are not detected; the last datum (textually rightmost in the display) stored for a given key value prevails. Changed in version 3.8: Prior to Python 3.8, in dict comprehensions, the evaluation order of key and value was not well-defined. In CPython, the value was evaluated before the key. Starting with 3.8, the key is evaluated before the value, as proposed by [**PEP 572**](https://www.python.org/dev/peps/pep-0572). ### 6.2.8. Generator expressions A generator expression is a compact generator notation in parentheses: ``` **generator\_expression** ::= "(" [expression](#grammar-token-expression) [comp\_for](#grammar-token-comp-for) ")" ``` A generator expression yields a new generator object. Its syntax is the same as for comprehensions, except that it is enclosed in parentheses instead of brackets or curly braces. Variables used in the generator expression are evaluated lazily when the [`__next__()`](#generator.__next__ "generator.__next__") method is called for the generator object (in the same fashion as normal generators). However, the iterable expression in the leftmost `for` clause is immediately evaluated, so that an error produced by it will be emitted at the point where the generator expression is defined, rather than at the point where the first value is retrieved. Subsequent `for` clauses and any filter condition in the leftmost `for` clause cannot be evaluated in the enclosing scope as they may depend on the values obtained from the leftmost iterable. For example: `(x*y for x in range(10) for y in range(x, x+10))`. The parentheses can be omitted on calls with only one argument. See section [Calls](#calls) for details. To avoid interfering with the expected operation of the generator expression itself, `yield` and `yield from` expressions are prohibited in the implicitly defined generator. If a generator expression contains either `async for` clauses or [`await`](#await) expressions it is called an *asynchronous generator expression*. An asynchronous generator expression returns a new asynchronous generator object, which is an asynchronous iterator (see [Asynchronous Iterators](datamodel#async-iterators)). New in version 3.6: Asynchronous generator expressions were introduced. Changed in version 3.7: Prior to Python 3.7, asynchronous generator expressions could only appear in [`async def`](compound_stmts#async-def) coroutines. Starting with 3.7, any function can use asynchronous generator expressions. Changed in version 3.8: `yield` and `yield from` prohibited in the implicitly nested scope. ### 6.2.9. Yield expressions ``` **yield\_atom** ::= "(" [yield\_expression](#grammar-token-yield-expression) ")" **yield\_expression** ::= "yield" [[expression\_list](#grammar-token-expression-list) | "from" [expression](#grammar-token-expression)] ``` The yield expression is used when defining a [generator](../glossary#term-generator) function or an [asynchronous generator](../glossary#term-asynchronous-generator) function and thus can only be used in the body of a function definition. Using a yield expression in a function’s body causes that function to be a generator function, and using it in an [`async def`](compound_stmts#async-def) function’s body causes that coroutine function to be an asynchronous generator function. For example: ``` def gen(): # defines a generator function yield 123 async def agen(): # defines an asynchronous generator function yield 123 ``` Due to their side effects on the containing scope, `yield` expressions are not permitted as part of the implicitly defined scopes used to implement comprehensions and generator expressions. Changed in version 3.8: Yield expressions prohibited in the implicitly nested scopes used to implement comprehensions and generator expressions. Generator functions are described below, while asynchronous generator functions are described separately in section [Asynchronous generator functions](#asynchronous-generator-functions). When a generator function is called, it returns an iterator known as a generator. That generator then controls the execution of the generator function. The execution starts when one of the generator’s methods is called. At that time, the execution proceeds to the first yield expression, where it is suspended again, returning the value of [`expression_list`](#grammar-token-expression-list) to the generator’s caller. By suspended, we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, the internal evaluation stack, and the state of any exception handling. When the execution is resumed by calling one of the generator’s methods, the function can proceed exactly as if the yield expression were just another external call. The value of the yield expression after resuming depends on the method which resumed the execution. If [`__next__()`](#generator.__next__ "generator.__next__") is used (typically via either a [`for`](compound_stmts#for) or the [`next()`](../library/functions#next "next") builtin) then the result is [`None`](../library/constants#None "None"). Otherwise, if [`send()`](#generator.send "generator.send") is used, then the result will be the value passed in to that method. All of this makes generator functions quite similar to coroutines; they yield multiple times, they have more than one entry point and their execution can be suspended. The only difference is that a generator function cannot control where the execution should continue after it yields; the control is always transferred to the generator’s caller. Yield expressions are allowed anywhere in a [`try`](compound_stmts#try) construct. If the generator is not resumed before it is finalized (by reaching a zero reference count or by being garbage collected), the generator-iterator’s [`close()`](#generator.close "generator.close") method will be called, allowing any pending [`finally`](compound_stmts#finally) clauses to execute. When `yield from <expr>` is used, the supplied expression must be an iterable. The values produced by iterating that iterable are passed directly to the caller of the current generator’s methods. Any values passed in with [`send()`](#generator.send "generator.send") and any exceptions passed in with [`throw()`](#generator.throw "generator.throw") are passed to the underlying iterator if it has the appropriate methods. If this is not the case, then [`send()`](#generator.send "generator.send") will raise [`AttributeError`](../library/exceptions#AttributeError "AttributeError") or [`TypeError`](../library/exceptions#TypeError "TypeError"), while [`throw()`](#generator.throw "generator.throw") will just raise the passed in exception immediately. When the underlying iterator is complete, the `value` attribute of the raised [`StopIteration`](../library/exceptions#StopIteration "StopIteration") instance becomes the value of the yield expression. It can be either set explicitly when raising [`StopIteration`](../library/exceptions#StopIteration "StopIteration"), or automatically when the subiterator is a generator (by returning a value from the subgenerator). Changed in version 3.3: Added `yield from <expr>` to delegate control flow to a subiterator. The parentheses may be omitted when the yield expression is the sole expression on the right hand side of an assignment statement. See also [**PEP 255**](https://www.python.org/dev/peps/pep-0255) - Simple Generators The proposal for adding generators and the [`yield`](simple_stmts#yield) statement to Python. [**PEP 342**](https://www.python.org/dev/peps/pep-0342) - Coroutines via Enhanced Generators The proposal to enhance the API and syntax of generators, making them usable as simple coroutines. [**PEP 380**](https://www.python.org/dev/peps/pep-0380) - Syntax for Delegating to a Subgenerator The proposal to introduce the `yield_from` syntax, making delegation to subgenerators easy. [**PEP 525**](https://www.python.org/dev/peps/pep-0525) - Asynchronous Generators The proposal that expanded on [**PEP 492**](https://www.python.org/dev/peps/pep-0492) by adding generator capabilities to coroutine functions. #### 6.2.9.1. Generator-iterator methods This subsection describes the methods of a generator iterator. They can be used to control the execution of a generator function. Note that calling any of the generator methods below when the generator is already executing raises a [`ValueError`](../library/exceptions#ValueError "ValueError") exception. `generator.__next__()` Starts the execution of a generator function or resumes it at the last executed yield expression. When a generator function is resumed with a [`__next__()`](#generator.__next__ "generator.__next__") method, the current yield expression always evaluates to [`None`](../library/constants#None "None"). The execution then continues to the next yield expression, where the generator is suspended again, and the value of the [`expression_list`](#grammar-token-expression-list) is returned to [`__next__()`](#generator.__next__ "generator.__next__")’s caller. If the generator exits without yielding another value, a [`StopIteration`](../library/exceptions#StopIteration "StopIteration") exception is raised. This method is normally called implicitly, e.g. by a [`for`](compound_stmts#for) loop, or by the built-in [`next()`](../library/functions#next "next") function. `generator.send(value)` Resumes the execution and “sends” a value into the generator function. The *value* argument becomes the result of the current yield expression. The [`send()`](#generator.send "generator.send") method returns the next value yielded by the generator, or raises [`StopIteration`](../library/exceptions#StopIteration "StopIteration") if the generator exits without yielding another value. When [`send()`](#generator.send "generator.send") is called to start the generator, it must be called with [`None`](../library/constants#None "None") as the argument, because there is no yield expression that could receive the value. `generator.throw(value)` `generator.throw(type[, value[, traceback]])` Raises an exception at the point where the generator was paused, and returns the next value yielded by the generator function. If the generator exits without yielding another value, a [`StopIteration`](../library/exceptions#StopIteration "StopIteration") exception is raised. If the generator function does not catch the passed-in exception, or raises a different exception, then that exception propagates to the caller. In typical use, this is called with a single exception instance similar to the way the [`raise`](simple_stmts#raise) keyword is used. For backwards compatability, however, the second signature is supported, following a convention from older versions of Python. The *type* argument should be an exception class, and *value* should be an exception instance. If the *value* is not provided, the *type* constructor is called to get an instance. If *traceback* is provided, it is set on the exception, otherwise any existing `__traceback__` attribute stored in *value* may be cleared. `generator.close()` Raises a [`GeneratorExit`](../library/exceptions#GeneratorExit "GeneratorExit") at the point where the generator function was paused. If the generator function then exits gracefully, is already closed, or raises [`GeneratorExit`](../library/exceptions#GeneratorExit "GeneratorExit") (by not catching the exception), close returns to its caller. If the generator yields a value, a [`RuntimeError`](../library/exceptions#RuntimeError "RuntimeError") is raised. If the generator raises any other exception, it is propagated to the caller. [`close()`](#generator.close "generator.close") does nothing if the generator has already exited due to an exception or normal exit. #### 6.2.9.2. Examples Here is a simple example that demonstrates the behavior of generators and generator functions: ``` >>> def echo(value=None): ... print("Execution starts when 'next()' is called for the first time.") ... try: ... while True: ... try: ... value = (yield value) ... except Exception as e: ... value = e ... finally: ... print("Don't forget to clean up when 'close()' is called.") ... >>> generator = echo(1) >>> print(next(generator)) Execution starts when 'next()' is called for the first time. 1 >>> print(next(generator)) None >>> print(generator.send(2)) 2 >>> generator.throw(TypeError, "spam") TypeError('spam',) >>> generator.close() Don't forget to clean up when 'close()' is called. ``` For examples using `yield from`, see [PEP 380: Syntax for Delegating to a Subgenerator](https://docs.python.org/3.9/whatsnew/3.3.html#pep-380) in “What’s New in Python.” #### 6.2.9.3. Asynchronous generator functions The presence of a yield expression in a function or method defined using [`async def`](compound_stmts#async-def) further defines the function as an [asynchronous generator](../glossary#term-asynchronous-generator) function. When an asynchronous generator function is called, it returns an asynchronous iterator known as an asynchronous generator object. That object then controls the execution of the generator function. An asynchronous generator object is typically used in an [`async for`](compound_stmts#async-for) statement in a coroutine function analogously to how a generator object would be used in a [`for`](compound_stmts#for) statement. Calling one of the asynchronous generator’s methods returns an [awaitable](../glossary#term-awaitable) object, and the execution starts when this object is awaited on. At that time, the execution proceeds to the first yield expression, where it is suspended again, returning the value of [`expression_list`](#grammar-token-expression-list) to the awaiting coroutine. As with a generator, suspension means that all local state is retained, including the current bindings of local variables, the instruction pointer, the internal evaluation stack, and the state of any exception handling. When the execution is resumed by awaiting on the next object returned by the asynchronous generator’s methods, the function can proceed exactly as if the yield expression were just another external call. The value of the yield expression after resuming depends on the method which resumed the execution. If [`__anext__()`](#agen.__anext__ "agen.__anext__") is used then the result is [`None`](../library/constants#None "None"). Otherwise, if [`asend()`](#agen.asend "agen.asend") is used, then the result will be the value passed in to that method. In an asynchronous generator function, yield expressions are allowed anywhere in a [`try`](compound_stmts#try) construct. However, if an asynchronous generator is not resumed before it is finalized (by reaching a zero reference count or by being garbage collected), then a yield expression within a `try` construct could result in a failure to execute pending [`finally`](compound_stmts#finally) clauses. In this case, it is the responsibility of the event loop or scheduler running the asynchronous generator to call the asynchronous generator-iterator’s [`aclose()`](#agen.aclose "agen.aclose") method and run the resulting coroutine object, thus allowing any pending `finally` clauses to execute. To take care of finalization, an event loop should define a *finalizer* function which takes an asynchronous generator-iterator and presumably calls [`aclose()`](#agen.aclose "agen.aclose") and executes the coroutine. This *finalizer* may be registered by calling [`sys.set_asyncgen_hooks()`](../library/sys#sys.set_asyncgen_hooks "sys.set_asyncgen_hooks"). When first iterated over, an asynchronous generator-iterator will store the registered *finalizer* to be called upon finalization. For a reference example of a *finalizer* method see the implementation of `asyncio.Loop.shutdown_asyncgens` in [Lib/asyncio/base\_events.py](https://github.com/python/cpython/tree/3.9/Lib/asyncio/base_events.py). The expression `yield from <expr>` is a syntax error when used in an asynchronous generator function. #### 6.2.9.4. Asynchronous generator-iterator methods This subsection describes the methods of an asynchronous generator iterator, which are used to control the execution of a generator function. `coroutine agen.__anext__()` Returns an awaitable which when run starts to execute the asynchronous generator or resumes it at the last executed yield expression. When an asynchronous generator function is resumed with an [`__anext__()`](#agen.__anext__ "agen.__anext__") method, the current yield expression always evaluates to [`None`](../library/constants#None "None") in the returned awaitable, which when run will continue to the next yield expression. The value of the [`expression_list`](#grammar-token-expression-list) of the yield expression is the value of the [`StopIteration`](../library/exceptions#StopIteration "StopIteration") exception raised by the completing coroutine. If the asynchronous generator exits without yielding another value, the awaitable instead raises a [`StopAsyncIteration`](../library/exceptions#StopAsyncIteration "StopAsyncIteration") exception, signalling that the asynchronous iteration has completed. This method is normally called implicitly by a [`async for`](compound_stmts#async-for) loop. `coroutine agen.asend(value)` Returns an awaitable which when run resumes the execution of the asynchronous generator. As with the [`send()`](#generator.send "generator.send") method for a generator, this “sends” a value into the asynchronous generator function, and the *value* argument becomes the result of the current yield expression. The awaitable returned by the [`asend()`](#agen.asend "agen.asend") method will return the next value yielded by the generator as the value of the raised [`StopIteration`](../library/exceptions#StopIteration "StopIteration"), or raises [`StopAsyncIteration`](../library/exceptions#StopAsyncIteration "StopAsyncIteration") if the asynchronous generator exits without yielding another value. When [`asend()`](#agen.asend "agen.asend") is called to start the asynchronous generator, it must be called with [`None`](../library/constants#None "None") as the argument, because there is no yield expression that could receive the value. `coroutine agen.athrow(type[, value[, traceback]])` Returns an awaitable that raises an exception of type `type` at the point where the asynchronous generator was paused, and returns the next value yielded by the generator function as the value of the raised [`StopIteration`](../library/exceptions#StopIteration "StopIteration") exception. If the asynchronous generator exits without yielding another value, a [`StopAsyncIteration`](../library/exceptions#StopAsyncIteration "StopAsyncIteration") exception is raised by the awaitable. If the generator function does not catch the passed-in exception, or raises a different exception, then when the awaitable is run that exception propagates to the caller of the awaitable. `coroutine agen.aclose()` Returns an awaitable that when run will throw a [`GeneratorExit`](../library/exceptions#GeneratorExit "GeneratorExit") into the asynchronous generator function at the point where it was paused. If the asynchronous generator function then exits gracefully, is already closed, or raises [`GeneratorExit`](../library/exceptions#GeneratorExit "GeneratorExit") (by not catching the exception), then the returned awaitable will raise a [`StopIteration`](../library/exceptions#StopIteration "StopIteration") exception. Any further awaitables returned by subsequent calls to the asynchronous generator will raise a [`StopAsyncIteration`](../library/exceptions#StopAsyncIteration "StopAsyncIteration") exception. If the asynchronous generator yields a value, a [`RuntimeError`](../library/exceptions#RuntimeError "RuntimeError") is raised by the awaitable. If the asynchronous generator raises any other exception, it is propagated to the caller of the awaitable. If the asynchronous generator has already exited due to an exception or normal exit, then further calls to [`aclose()`](#agen.aclose "agen.aclose") will return an awaitable that does nothing. 6.3. Primaries --------------- Primaries represent the most tightly bound operations of the language. Their syntax is: ``` **primary** ::= [atom](#grammar-token-atom) | [attributeref](#grammar-token-attributeref) | [subscription](#grammar-token-subscription) | [slicing](#grammar-token-slicing) | [call](#grammar-token-call) ``` ### 6.3.1. Attribute references An attribute reference is a primary followed by a period and a name: ``` **attributeref** ::= [primary](#grammar-token-primary) "." [identifier](lexical_analysis#grammar-token-identifier) ``` The primary must evaluate to an object of a type that supports attribute references, which most objects do. This object is then asked to produce the attribute whose name is the identifier. This production can be customized by overriding the [`__getattr__()`](datamodel#object.__getattr__ "object.__getattr__") method. If this attribute is not available, the exception [`AttributeError`](../library/exceptions#AttributeError "AttributeError") is raised. Otherwise, the type and value of the object produced is determined by the object. Multiple evaluations of the same attribute reference may yield different objects. ### 6.3.2. Subscriptions The subscription of an instance of a [container class](datamodel#sequence-types) will generally select an element from the container. The subscription of a [generic class](../glossary#term-generic-type) will generally return a [GenericAlias](../library/stdtypes#types-genericalias) object. ``` **subscription** ::= [primary](#grammar-token-primary) "[" [expression\_list](#grammar-token-expression-list) "]" ``` When an object is subscripted, the interpreter will evaluate the primary and the expression list. The primary must evaluate to an object that supports subscription. An object may support subscription through defining one or both of [`__getitem__()`](datamodel#object.__getitem__ "object.__getitem__") and [`__class_getitem__()`](datamodel#object.__class_getitem__ "object.__class_getitem__"). When the primary is subscripted, the evaluated result of the expression list will be passed to one of these methods. For more details on when `__class_getitem__` is called instead of `__getitem__`, see [\_\_class\_getitem\_\_ versus \_\_getitem\_\_](datamodel#classgetitem-versus-getitem). If the expression list contains at least one comma, it will evaluate to a [`tuple`](../library/stdtypes#tuple "tuple") containing the items of the expression list. Otherwise, the expression list will evaluate to the value of the list’s sole member. For built-in objects, there are two types of objects that support subscription via [`__getitem__()`](datamodel#object.__getitem__ "object.__getitem__"): 1. Mappings. If the primary is a [mapping](../glossary#term-mapping), the expression list must evaluate to an object whose value is one of the keys of the mapping, and the subscription selects the value in the mapping that corresponds to that key. An example of a builtin mapping class is the [`dict`](../library/stdtypes#dict "dict") class. 2. Sequences. If the primary is a [sequence](../glossary#term-sequence), the expression list must evaluate to an [`int`](../library/functions#int "int") or a [`slice`](../library/functions#slice "slice") (as discussed in the following section). Examples of builtin sequence classes include the [`str`](../library/stdtypes#str "str"), [`list`](../library/stdtypes#list "list") and [`tuple`](../library/stdtypes#tuple "tuple") classes. The formal syntax makes no special provision for negative indices in [sequences](../glossary#term-sequence). However, built-in sequences all provide a [`__getitem__()`](datamodel#object.__getitem__ "object.__getitem__") method that interprets negative indices by adding the length of the sequence to the index so that, for example, `x[-1]` selects the last item of `x`. The resulting value must be a nonnegative integer less than the number of items in the sequence, and the subscription selects the item whose index is that value (counting from zero). Since the support for negative indices and slicing occurs in the object’s [`__getitem__()`](datamodel#object.__getitem__ "object.__getitem__") method, subclasses overriding this method will need to explicitly add that support. A [`string`](../library/stdtypes#str "str") is a special kind of sequence whose items are *characters*. A character is not a separate data type but a string of exactly one character. ### 6.3.3. Slicings A slicing selects a range of items in a sequence object (e.g., a string, tuple or list). Slicings may be used as expressions or as targets in assignment or [`del`](simple_stmts#del) statements. The syntax for a slicing: ``` **slicing** ::= [primary](#grammar-token-primary) "[" [slice\_list](#grammar-token-slice-list) "]" **slice\_list** ::= [slice\_item](#grammar-token-slice-item) ("," [slice\_item](#grammar-token-slice-item))* [","] **slice\_item** ::= [expression](#grammar-token-expression) | [proper\_slice](#grammar-token-proper-slice) **proper\_slice** ::= [[lower\_bound](#grammar-token-lower-bound)] ":" [[upper\_bound](#grammar-token-upper-bound)] [ ":" [[stride](#grammar-token-stride)] ] **lower\_bound** ::= [expression](#grammar-token-expression) **upper\_bound** ::= [expression](#grammar-token-expression) **stride** ::= [expression](#grammar-token-expression) ``` There is ambiguity in the formal syntax here: anything that looks like an expression list also looks like a slice list, so any subscription can be interpreted as a slicing. Rather than further complicating the syntax, this is disambiguated by defining that in this case the interpretation as a subscription takes priority over the interpretation as a slicing (this is the case if the slice list contains no proper slice). The semantics for a slicing are as follows. The primary is indexed (using the same [`__getitem__()`](datamodel#object.__getitem__ "object.__getitem__") method as normal subscription) with a key that is constructed from the slice list, as follows. If the slice list contains at least one comma, the key is a tuple containing the conversion of the slice items; otherwise, the conversion of the lone slice item is the key. The conversion of a slice item that is an expression is that expression. The conversion of a proper slice is a slice object (see section [The standard type hierarchy](datamodel#types)) whose `start`, `stop` and `step` attributes are the values of the expressions given as lower bound, upper bound and stride, respectively, substituting `None` for missing expressions. ### 6.3.4. Calls A call calls a callable object (e.g., a [function](../glossary#term-function)) with a possibly empty series of [arguments](../glossary#term-argument): ``` **call** ::= [primary](#grammar-token-primary) "(" [[argument\_list](#grammar-token-argument-list) [","] | [comprehension](#grammar-token-comprehension)] ")" **argument\_list** ::= [positional\_arguments](#grammar-token-positional-arguments) ["," [starred\_and\_keywords](#grammar-token-starred-and-keywords)] ["," [keywords\_arguments](#grammar-token-keywords-arguments)] | [starred\_and\_keywords](#grammar-token-starred-and-keywords) ["," [keywords\_arguments](#grammar-token-keywords-arguments)] | [keywords\_arguments](#grammar-token-keywords-arguments) **positional\_arguments** ::= positional_item ("," positional_item)* **positional\_item** ::= [assignment\_expression](#grammar-token-assignment-expression) | "*" [expression](#grammar-token-expression) **starred\_and\_keywords** ::= ("*" [expression](#grammar-token-expression) | [keyword\_item](#grammar-token-keyword-item)) ("," "*" [expression](#grammar-token-expression) | "," [keyword\_item](#grammar-token-keyword-item))* **keywords\_arguments** ::= ([keyword\_item](#grammar-token-keyword-item) | "**" [expression](#grammar-token-expression)) ("," [keyword\_item](#grammar-token-keyword-item) | "," "**" [expression](#grammar-token-expression))* **keyword\_item** ::= [identifier](lexical_analysis#grammar-token-identifier) "=" [expression](#grammar-token-expression) ``` An optional trailing comma may be present after the positional and keyword arguments but does not affect the semantics. The primary must evaluate to a callable object (user-defined functions, built-in functions, methods of built-in objects, class objects, methods of class instances, and all objects having a [`__call__()`](datamodel#object.__call__ "object.__call__") method are callable). All argument expressions are evaluated before the call is attempted. Please refer to section [Function definitions](compound_stmts#function) for the syntax of formal [parameter](../glossary#term-parameter) lists. If keyword arguments are present, they are first converted to positional arguments, as follows. First, a list of unfilled slots is created for the formal parameters. If there are N positional arguments, they are placed in the first N slots. Next, for each keyword argument, the identifier is used to determine the corresponding slot (if the identifier is the same as the first formal parameter name, the first slot is used, and so on). If the slot is already filled, a [`TypeError`](../library/exceptions#TypeError "TypeError") exception is raised. Otherwise, the value of the argument is placed in the slot, filling it (even if the expression is `None`, it fills the slot). When all arguments have been processed, the slots that are still unfilled are filled with the corresponding default value from the function definition. (Default values are calculated, once, when the function is defined; thus, a mutable object such as a list or dictionary used as default value will be shared by all calls that don’t specify an argument value for the corresponding slot; this should usually be avoided.) If there are any unfilled slots for which no default value is specified, a [`TypeError`](../library/exceptions#TypeError "TypeError") exception is raised. Otherwise, the list of filled slots is used as the argument list for the call. **CPython implementation detail:** An implementation may provide built-in functions whose positional parameters do not have names, even if they are ‘named’ for the purpose of documentation, and which therefore cannot be supplied by keyword. In CPython, this is the case for functions implemented in C that use [`PyArg_ParseTuple()`](../c-api/arg#c.PyArg_ParseTuple "PyArg_ParseTuple") to parse their arguments. If there are more positional arguments than there are formal parameter slots, a [`TypeError`](../library/exceptions#TypeError "TypeError") exception is raised, unless a formal parameter using the syntax `*identifier` is present; in this case, that formal parameter receives a tuple containing the excess positional arguments (or an empty tuple if there were no excess positional arguments). If any keyword argument does not correspond to a formal parameter name, a [`TypeError`](../library/exceptions#TypeError "TypeError") exception is raised, unless a formal parameter using the syntax `**identifier` is present; in this case, that formal parameter receives a dictionary containing the excess keyword arguments (using the keywords as keys and the argument values as corresponding values), or a (new) empty dictionary if there were no excess keyword arguments. If the syntax `*expression` appears in the function call, `expression` must evaluate to an [iterable](../glossary#term-iterable). Elements from these iterables are treated as if they were additional positional arguments. For the call `f(x1, x2, *y, x3, x4)`, if *y* evaluates to a sequence *y1*, …, *yM*, this is equivalent to a call with M+4 positional arguments *x1*, *x2*, *y1*, …, *yM*, *x3*, *x4*. A consequence of this is that although the `*expression` syntax may appear *after* explicit keyword arguments, it is processed *before* the keyword arguments (and any `**expression` arguments – see below). So: ``` >>> def f(a, b): ... print(a, b) ... >>> f(b=1, *(2,)) 2 1 >>> f(a=1, *(2,)) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: f() got multiple values for keyword argument 'a' >>> f(1, *(2,)) 1 2 ``` It is unusual for both keyword arguments and the `*expression` syntax to be used in the same call, so in practice this confusion does not arise. If the syntax `**expression` appears in the function call, `expression` must evaluate to a [mapping](../glossary#term-mapping), the contents of which are treated as additional keyword arguments. If a keyword is already present (as an explicit keyword argument, or from another unpacking), a [`TypeError`](../library/exceptions#TypeError "TypeError") exception is raised. Formal parameters using the syntax `*identifier` or `**identifier` cannot be used as positional argument slots or as keyword argument names. Changed in version 3.5: Function calls accept any number of `*` and `**` unpackings, positional arguments may follow iterable unpackings (`*`), and keyword arguments may follow dictionary unpackings (`**`). Originally proposed by [**PEP 448**](https://www.python.org/dev/peps/pep-0448). A call always returns some value, possibly `None`, unless it raises an exception. How this value is computed depends on the type of the callable object. If it is— a user-defined function: The code block for the function is executed, passing it the argument list. The first thing the code block will do is bind the formal parameters to the arguments; this is described in section [Function definitions](compound_stmts#function). When the code block executes a [`return`](simple_stmts#return) statement, this specifies the return value of the function call. a built-in function or method: The result is up to the interpreter; see [Built-in Functions](../library/functions#built-in-funcs) for the descriptions of built-in functions and methods. a class object: A new instance of that class is returned. a class instance method: The corresponding user-defined function is called, with an argument list that is one longer than the argument list of the call: the instance becomes the first argument. a class instance: The class must define a [`__call__()`](datamodel#object.__call__ "object.__call__") method; the effect is then the same as if that method was called. 6.4. Await expression ---------------------- Suspend the execution of [coroutine](../glossary#term-coroutine) on an [awaitable](../glossary#term-awaitable) object. Can only be used inside a [coroutine function](../glossary#term-coroutine-function). ``` **await\_expr** ::= "await" [primary](#grammar-token-primary) ``` New in version 3.5. 6.5. The power operator ------------------------ The power operator binds more tightly than unary operators on its left; it binds less tightly than unary operators on its right. The syntax is: ``` **power** ::= ([await\_expr](#grammar-token-await-expr) | [primary](#grammar-token-primary)) ["**" [u\_expr](#grammar-token-u-expr)] ``` Thus, in an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left (this does not constrain the evaluation order for the operands): `-1**2` results in `-1`. The power operator has the same semantics as the built-in [`pow()`](../library/functions#pow "pow") function, when called with two arguments: it yields its left argument raised to the power of its right argument. The numeric arguments are first converted to a common type, and the result is of that type. For int operands, the result has the same type as the operands unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example, `10**2` returns `100`, but `10**-2` returns `0.01`. Raising `0.0` to a negative power results in a [`ZeroDivisionError`](../library/exceptions#ZeroDivisionError "ZeroDivisionError"). Raising a negative number to a fractional power results in a [`complex`](../library/functions#complex "complex") number. (In earlier versions it raised a [`ValueError`](../library/exceptions#ValueError "ValueError").) This operation can be customized using the special [`__pow__()`](datamodel#object.__pow__ "object.__pow__") method. 6.6. Unary arithmetic and bitwise operations --------------------------------------------- All unary arithmetic and bitwise operations have the same priority: ``` **u\_expr** ::= [power](#grammar-token-power) | "-" [u\_expr](#grammar-token-u-expr) | "+" [u\_expr](#grammar-token-u-expr) | "~" [u\_expr](#grammar-token-u-expr) ``` The unary `-` (minus) operator yields the negation of its numeric argument; the operation can be overridden with the [`__neg__()`](datamodel#object.__neg__ "object.__neg__") special method. The unary `+` (plus) operator yields its numeric argument unchanged; the operation can be overridden with the [`__pos__()`](datamodel#object.__pos__ "object.__pos__") special method. The unary `~` (invert) operator yields the bitwise inversion of its integer argument. The bitwise inversion of `x` is defined as `-(x+1)`. It only applies to integral numbers or to custom objects that override the [`__invert__()`](datamodel#object.__invert__ "object.__invert__") special method. In all three cases, if the argument does not have the proper type, a [`TypeError`](../library/exceptions#TypeError "TypeError") exception is raised. 6.7. Binary arithmetic operations ---------------------------------- The binary arithmetic operations have the conventional priority levels. Note that some of these operations also apply to certain non-numeric types. Apart from the power operator, there are only two levels, one for multiplicative operators and one for additive operators: ``` **m\_expr** ::= [u\_expr](#grammar-token-u-expr) | [m\_expr](#grammar-token-m-expr) "*" [u\_expr](#grammar-token-u-expr) | [m\_expr](#grammar-token-m-expr) "@" [m\_expr](#grammar-token-m-expr) | [m\_expr](#grammar-token-m-expr) "//" [u\_expr](#grammar-token-u-expr) | [m\_expr](#grammar-token-m-expr) "/" [u\_expr](#grammar-token-u-expr) | [m\_expr](#grammar-token-m-expr) "%" [u\_expr](#grammar-token-u-expr) **a\_expr** ::= [m\_expr](#grammar-token-m-expr) | [a\_expr](#grammar-token-a-expr) "+" [m\_expr](#grammar-token-m-expr) | [a\_expr](#grammar-token-a-expr) "-" [m\_expr](#grammar-token-m-expr) ``` The `*` (multiplication) operator yields the product of its arguments. The arguments must either both be numbers, or one argument must be an integer and the other must be a sequence. In the former case, the numbers are converted to a common type and then multiplied together. In the latter case, sequence repetition is performed; a negative repetition factor yields an empty sequence. This operation can be customized using the special [`__mul__()`](datamodel#object.__mul__ "object.__mul__") and [`__rmul__()`](datamodel#object.__rmul__ "object.__rmul__") methods. The `@` (at) operator is intended to be used for matrix multiplication. No builtin Python types implement this operator. New in version 3.5. The `/` (division) and `//` (floor division) operators yield the quotient of their arguments. The numeric arguments are first converted to a common type. Division of integers yields a float, while floor division of integers results in an integer; the result is that of mathematical division with the ‘floor’ function applied to the result. Division by zero raises the [`ZeroDivisionError`](../library/exceptions#ZeroDivisionError "ZeroDivisionError") exception. This operation can be customized using the special [`__truediv__()`](datamodel#object.__truediv__ "object.__truediv__") and [`__floordiv__()`](datamodel#object.__floordiv__ "object.__floordiv__") methods. The `%` (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the [`ZeroDivisionError`](../library/exceptions#ZeroDivisionError "ZeroDivisionError") exception. The arguments may be floating point numbers, e.g., `3.14%0.7` equals `0.34` (since `3.14` equals `4*0.7 + 0.34`.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [1](#id17). The floor division and modulo operators are connected by the following identity: `x == (x//y)*y + (x%y)`. Floor division and modulo are also connected with the built-in function [`divmod()`](../library/functions#divmod "divmod"): `divmod(x, y) == (x//y, x%y)`. [2](#id18). In addition to performing the modulo operation on numbers, the `%` operator is also overloaded by string objects to perform old-style string formatting (also known as interpolation). The syntax for string formatting is described in the Python Library Reference, section [printf-style String Formatting](../library/stdtypes#old-string-formatting). The *modulo* operation can be customized using the special [`__mod__()`](datamodel#object.__mod__ "object.__mod__") method. The floor division operator, the modulo operator, and the [`divmod()`](../library/functions#divmod "divmod") function are not defined for complex numbers. Instead, convert to a floating point number using the [`abs()`](../library/functions#abs "abs") function if appropriate. The `+` (addition) operator yields the sum of its arguments. The arguments must either both be numbers or both be sequences of the same type. In the former case, the numbers are converted to a common type and then added together. In the latter case, the sequences are concatenated. This operation can be customized using the special [`__add__()`](datamodel#object.__add__ "object.__add__") and [`__radd__()`](datamodel#object.__radd__ "object.__radd__") methods. The `-` (subtraction) operator yields the difference of its arguments. The numeric arguments are first converted to a common type. This operation can be customized using the special [`__sub__()`](datamodel#object.__sub__ "object.__sub__") method. 6.8. Shifting operations ------------------------- The shifting operations have lower priority than the arithmetic operations: ``` **shift\_expr** ::= [a\_expr](#grammar-token-a-expr) | [shift\_expr](#grammar-token-shift-expr) ("<<" | ">>") [a\_expr](#grammar-token-a-expr) ``` These operators accept integers as arguments. They shift the first argument to the left or right by the number of bits given by the second argument. This operation can be customized using the special [`__lshift__()`](datamodel#object.__lshift__ "object.__lshift__") and [`__rshift__()`](datamodel#object.__rshift__ "object.__rshift__") methods. A right shift by *n* bits is defined as floor division by `pow(2,n)`. A left shift by *n* bits is defined as multiplication with `pow(2,n)`. 6.9. Binary bitwise operations ------------------------------- Each of the three bitwise operations has a different priority level: ``` **and\_expr** ::= [shift\_expr](#grammar-token-shift-expr) | [and\_expr](#grammar-token-and-expr) "&" [shift\_expr](#grammar-token-shift-expr) **xor\_expr** ::= [and\_expr](#grammar-token-and-expr) | [xor\_expr](#grammar-token-xor-expr) "^" [and\_expr](#grammar-token-and-expr) **or\_expr** ::= [xor\_expr](#grammar-token-xor-expr) | [or\_expr](#grammar-token-or-expr) "|" [xor\_expr](#grammar-token-xor-expr) ``` The `&` operator yields the bitwise AND of its arguments, which must be integers or one of them must be a custom object overriding [`__and__()`](datamodel#object.__and__ "object.__and__") or [`__rand__()`](datamodel#object.__rand__ "object.__rand__") special methods. The `^` operator yields the bitwise XOR (exclusive OR) of its arguments, which must be integers or one of them must be a custom object overriding [`__xor__()`](datamodel#object.__xor__ "object.__xor__") or [`__rxor__()`](datamodel#object.__rxor__ "object.__rxor__") special methods. The `|` operator yields the bitwise (inclusive) OR of its arguments, which must be integers or one of them must be a custom object overriding [`__or__()`](datamodel#object.__or__ "object.__or__") or [`__ror__()`](datamodel#object.__ror__ "object.__ror__") special methods. 6.10. Comparisons ------------------ Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Also unlike C, expressions like `a < b < c` have the interpretation that is conventional in mathematics: ``` **comparison** ::= [or\_expr](#grammar-token-or-expr) ([comp\_operator](#grammar-token-comp-operator) [or\_expr](#grammar-token-or-expr))* **comp\_operator** ::= "<" | ">" | "==" | ">=" | "<=" | "!=" | "is" ["not"] | ["not"] "in" ``` Comparisons yield boolean values: `True` or `False`. Custom *rich comparison methods* may return non-boolean values. In this case Python will call [`bool()`](../library/functions#bool "bool") on such value in boolean contexts. Comparisons can be chained arbitrarily, e.g., `x < y <= z` is equivalent to `x < y and y <= z`, except that `y` is evaluated only once (but in both cases `z` is not evaluated at all when `x < y` is found to be false). Formally, if *a*, *b*, *c*, …, *y*, *z* are expressions and *op1*, *op2*, …, *opN* are comparison operators, then `a op1 b op2 c ... y opN z` is equivalent to `a op1 b and b op2 c and ... y opN z`, except that each expression is evaluated at most once. Note that `a op1 b op2 c` doesn’t imply any kind of comparison between *a* and *c*, so that, e.g., `x < y > z` is perfectly legal (though perhaps not pretty). ### 6.10.1. Value comparisons The operators `<`, `>`, `==`, `>=`, `<=`, and `!=` compare the values of two objects. The objects do not need to have the same type. Chapter [Objects, values and types](datamodel#objects) states that objects have a value (in addition to type and identity). The value of an object is a rather abstract notion in Python: For example, there is no canonical access method for an object’s value. Also, there is no requirement that the value of an object should be constructed in a particular way, e.g. comprised of all its data attributes. Comparison operators implement a particular notion of what the value of an object is. One can think of them as defining the value of an object indirectly, by means of their comparison implementation. Because all types are (direct or indirect) subtypes of [`object`](../library/functions#object "object"), they inherit the default comparison behavior from [`object`](../library/functions#object "object"). Types can customize their comparison behavior by implementing *rich comparison methods* like [`__lt__()`](datamodel#object.__lt__ "object.__lt__"), described in [Basic customization](datamodel#customization). The default behavior for equality comparison (`==` and `!=`) is based on the identity of the objects. Hence, equality comparison of instances with the same identity results in equality, and equality comparison of instances with different identities results in inequality. A motivation for this default behavior is the desire that all objects should be reflexive (i.e. `x is y` implies `x == y`). A default order comparison (`<`, `>`, `<=`, and `>=`) is not provided; an attempt raises [`TypeError`](../library/exceptions#TypeError "TypeError"). A motivation for this default behavior is the lack of a similar invariant as for equality. The behavior of the default equality comparison, that instances with different identities are always unequal, may be in contrast to what types will need that have a sensible definition of object value and value-based equality. Such types will need to customize their comparison behavior, and in fact, a number of built-in types have done that. The following list describes the comparison behavior of the most important built-in types. * Numbers of built-in numeric types ([Numeric Types — int, float, complex](../library/stdtypes#typesnumeric)) and of the standard library types [`fractions.Fraction`](../library/fractions#fractions.Fraction "fractions.Fraction") and [`decimal.Decimal`](../library/decimal#decimal.Decimal "decimal.Decimal") can be compared within and across their types, with the restriction that complex numbers do not support order comparison. Within the limits of the types involved, they compare mathematically (algorithmically) correct without loss of precision. The not-a-number values `float('NaN')` and `decimal.Decimal('NaN')` are special. Any ordered comparison of a number to a not-a-number value is false. A counter-intuitive implication is that not-a-number values are not equal to themselves. For example, if `x = float('NaN')`, `3 < x`, `x < 3` and `x == x` are all false, while `x != x` is true. This behavior is compliant with IEEE 754. * `None` and `NotImplemented` are singletons. [**PEP 8**](https://www.python.org/dev/peps/pep-0008) advises that comparisons for singletons should always be done with `is` or `is not`, never the equality operators. * Binary sequences (instances of [`bytes`](../library/stdtypes#bytes "bytes") or [`bytearray`](../library/stdtypes#bytearray "bytearray")) can be compared within and across their types. They compare lexicographically using the numeric values of their elements. * Strings (instances of [`str`](../library/stdtypes#str "str")) compare lexicographically using the numerical Unicode code points (the result of the built-in function [`ord()`](../library/functions#ord "ord")) of their characters. [3](#id19) Strings and binary sequences cannot be directly compared. * Sequences (instances of [`tuple`](../library/stdtypes#tuple "tuple"), [`list`](../library/stdtypes#list "list"), or [`range`](../library/stdtypes#range "range")) can be compared only within each of their types, with the restriction that ranges do not support order comparison. Equality comparison across these types results in inequality, and ordering comparison across these types raises [`TypeError`](../library/exceptions#TypeError "TypeError"). Sequences compare lexicographically using comparison of corresponding elements. The built-in containers typically assume identical objects are equal to themselves. That lets them bypass equality tests for identical objects to improve performance and to maintain their internal invariants. Lexicographical comparison between built-in collections works as follows: + For two collections to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example, `[1,2] == (1,2)` is false because the type is not the same). + Collections that support order comparison are ordered the same as their first unequal elements (for example, `[1,2,x] <= [1,2,y]` has the same value as `x <= y`). If a corresponding element does not exist, the shorter collection is ordered first (for example, `[1,2] < [1,2,3]` is true). * Mappings (instances of [`dict`](../library/stdtypes#dict "dict")) compare equal if and only if they have equal `(key, value)` pairs. Equality comparison of the keys and values enforces reflexivity. Order comparisons (`<`, `>`, `<=`, and `>=`) raise [`TypeError`](../library/exceptions#TypeError "TypeError"). * Sets (instances of [`set`](../library/stdtypes#set "set") or [`frozenset`](../library/stdtypes#frozenset "frozenset")) can be compared within and across their types. They define order comparison operators to mean subset and superset tests. Those relations do not define total orderings (for example, the two sets `{1,2}` and `{2,3}` are not equal, nor subsets of one another, nor supersets of one another). Accordingly, sets are not appropriate arguments for functions which depend on total ordering (for example, [`min()`](../library/functions#min "min"), [`max()`](../library/functions#max "max"), and [`sorted()`](../library/functions#sorted "sorted") produce undefined results given a list of sets as inputs). Comparison of sets enforces reflexivity of its elements. * Most other built-in types have no comparison methods implemented, so they inherit the default comparison behavior. User-defined classes that customize their comparison behavior should follow some consistency rules, if possible: * Equality comparison should be reflexive. In other words, identical objects should compare equal: `x is y` implies `x == y` * Comparison should be symmetric. In other words, the following expressions should have the same result: `x == y` and `y == x` `x != y` and `y != x` `x < y` and `y > x` `x <= y` and `y >= x` * Comparison should be transitive. The following (non-exhaustive) examples illustrate that: `x > y and y > z` implies `x > z` `x < y and y <= z` implies `x < z` * Inverse comparison should result in the boolean negation. In other words, the following expressions should have the same result: `x == y` and `not x != y` `x < y` and `not x >= y` (for total ordering) `x > y` and `not x <= y` (for total ordering) The last two expressions apply to totally ordered collections (e.g. to sequences, but not to sets or mappings). See also the [`total_ordering()`](../library/functools#functools.total_ordering "functools.total_ordering") decorator. * The [`hash()`](../library/functions#hash "hash") result should be consistent with equality. Objects that are equal should either have the same hash value, or be marked as unhashable. Python does not enforce these consistency rules. In fact, the not-a-number values are an example for not following these rules. ### 6.10.2. Membership test operations The operators [`in`](#in) and [`not in`](#not-in) test for membership. `x in s` evaluates to `True` if *x* is a member of *s*, and `False` otherwise. `x not in s` returns the negation of `x in s`. All built-in sequences and set types support this as well as dictionary, for which `in` tests whether the dictionary has a given key. For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression `x in y` is equivalent to `any(x is e or x == e for e in y)`. For the string and bytes types, `x in y` is `True` if and only if *x* is a substring of *y*. An equivalent test is `y.find(x) != -1`. Empty strings are always considered to be a substring of any other string, so `"" in "abc"` will return `True`. For user-defined classes which define the [`__contains__()`](datamodel#object.__contains__ "object.__contains__") method, `x in y` returns `True` if `y.__contains__(x)` returns a true value, and `False` otherwise. For user-defined classes which do not define [`__contains__()`](datamodel#object.__contains__ "object.__contains__") but do define [`__iter__()`](datamodel#object.__iter__ "object.__iter__"), `x in y` is `True` if some value `z`, for which the expression `x is z or x == z` is true, is produced while iterating over `y`. If an exception is raised during the iteration, it is as if [`in`](#in) raised that exception. Lastly, the old-style iteration protocol is tried: if a class defines [`__getitem__()`](datamodel#object.__getitem__ "object.__getitem__"), `x in y` is `True` if and only if there is a non-negative integer index *i* such that `x is y[i] or x == y[i]`, and no lower integer index raises the [`IndexError`](../library/exceptions#IndexError "IndexError") exception. (If any other exception is raised, it is as if [`in`](#in) raised that exception). The operator [`not in`](#not-in) is defined to have the inverse truth value of [`in`](#in). ### 6.10.3. Identity comparisons The operators [`is`](#is) and [`is not`](#is-not) test for an object’s identity: `x is y` is true if and only if *x* and *y* are the same object. An Object’s identity is determined using the [`id()`](../library/functions#id "id") function. `x is not y` yields the inverse truth value. [4](#id20) 6.11. Boolean operations ------------------------- ``` **or\_test** ::= [and\_test](#grammar-token-and-test) | [or\_test](#grammar-token-or-test) "or" [and\_test](#grammar-token-and-test) **and\_test** ::= [not\_test](#grammar-token-not-test) | [and\_test](#grammar-token-and-test) "and" [not\_test](#grammar-token-not-test) **not\_test** ::= [comparison](#grammar-token-comparison) | "not" [not\_test](#grammar-token-not-test) ``` In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: `False`, `None`, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a [`__bool__()`](datamodel#object.__bool__ "object.__bool__") method. The operator [`not`](#not) yields `True` if its argument is false, `False` otherwise. The expression `x and y` first evaluates *x*; if *x* is false, its value is returned; otherwise, *y* is evaluated and the resulting value is returned. The expression `x or y` first evaluates *x*; if *x* is true, its value is returned; otherwise, *y* is evaluated and the resulting value is returned. Note that neither [`and`](#and) nor [`or`](#or) restrict the value and type they return to `False` and `True`, but rather return the last evaluated argument. This is sometimes useful, e.g., if `s` is a string that should be replaced by a default value if it is empty, the expression `s or 'foo'` yields the desired value. Because [`not`](#not) has to create a new value, it returns a boolean value regardless of the type of its argument (for example, `not 'foo'` produces `False` rather than `''`.) 6.12. Assignment expressions ----------------------------- ``` **assignment\_expression** ::= [[identifier](lexical_analysis#grammar-token-identifier) ":="] [expression](#grammar-token-expression) ``` An assignment expression (sometimes also called a “named expression” or “walrus”) assigns an [`expression`](#grammar-token-expression) to an [`identifier`](lexical_analysis#grammar-token-identifier), while also returning the value of the [`expression`](#grammar-token-expression). One common use case is when handling matched regular expressions: ``` if matching := pattern.search(data): do_something(matching) ``` Or, when processing a file stream in chunks: ``` while chunk := file.read(9000): process(chunk) ``` New in version 3.8: See [**PEP 572**](https://www.python.org/dev/peps/pep-0572) for more details about assignment expressions. 6.13. Conditional expressions ------------------------------ ``` **conditional\_expression** ::= [or\_test](#grammar-token-or-test) ["if" [or\_test](#grammar-token-or-test) "else" [expression](#grammar-token-expression)] **expression** ::= [conditional\_expression](#grammar-token-conditional-expression) | [lambda\_expr](#grammar-token-lambda-expr) ``` Conditional expressions (sometimes called a “ternary operator”) have the lowest priority of all Python operations. The expression `x if C else y` first evaluates the condition, *C* rather than *x*. If *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is evaluated and its value is returned. See [**PEP 308**](https://www.python.org/dev/peps/pep-0308) for more details about conditional expressions. 6.14. Lambdas -------------- ``` **lambda\_expr** ::= "lambda" [[parameter\_list](compound_stmts#grammar-token-parameter-list)] ":" [expression](#grammar-token-expression) ``` Lambda expressions (sometimes called lambda forms) are used to create anonymous functions. The expression `lambda parameters: expression` yields a function object. The unnamed object behaves like a function object defined with: ``` def <lambda>(parameters): return expression ``` See section [Function definitions](compound_stmts#function) for the syntax of parameter lists. Note that functions created with lambda expressions cannot contain statements or annotations. 6.15. Expression lists ----------------------- ``` **expression\_list** ::= [expression](#grammar-token-expression) ("," [expression](#grammar-token-expression))* [","] **starred\_list** ::= [starred\_item](#grammar-token-starred-item) ("," [starred\_item](#grammar-token-starred-item))* [","] **starred\_expression** ::= [expression](#grammar-token-expression) | ([starred\_item](#grammar-token-starred-item) ",")* [[starred\_item](#grammar-token-starred-item)] **starred\_item** ::= [assignment\_expression](#grammar-token-assignment-expression) | "*" [or\_expr](#grammar-token-or-expr) ``` Except when part of a list or set display, an expression list containing at least one comma yields a tuple. The length of the tuple is the number of expressions in the list. The expressions are evaluated from left to right. An asterisk `*` denotes *iterable unpacking*. Its operand must be an [iterable](../glossary#term-iterable). The iterable is expanded into a sequence of items, which are included in the new tuple, list, or set, at the site of the unpacking. New in version 3.5: Iterable unpacking in expression lists, originally proposed by [**PEP 448**](https://www.python.org/dev/peps/pep-0448). The trailing comma is required only to create a single tuple (a.k.a. a *singleton*); it is optional in all other cases. A single expression without a trailing comma doesn’t create a tuple, but rather yields the value of that expression. (To create an empty tuple, use an empty pair of parentheses: `()`.) 6.16. Evaluation order ----------------------- Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side. In the following lines, expressions will be evaluated in the arithmetic order of their suffixes: ``` expr1, expr2, expr3, expr4 (expr1, expr2, expr3, expr4) {expr1: expr2, expr3: expr4} expr1 + expr2 * (expr3 - expr4) expr1(expr2, expr3, *expr4, **expr5) expr3, expr4 = expr1, expr2 ``` 6.17. Operator precedence -------------------------- The following table summarizes the operator precedence in Python, from highest precedence (most binding) to lowest precedence (least binding). Operators in the same box have the same precedence. Unless the syntax is explicitly given, operators are binary. Operators in the same box group left to right (except for exponentiation, which groups from right to left). Note that comparisons, membership tests, and identity tests, all have the same precedence and have a left-to-right chaining feature as described in the [Comparisons](#comparisons) section. | Operator | Description | | --- | --- | | `(expressions...)`, `[expressions...]`, `{key: value...}`, `{expressions...}` | Binding or parenthesized expression, list display, dictionary display, set display | | `x[index]`, `x[index:index]`, `x(arguments...)`, `x.attribute` | Subscription, slicing, call, attribute reference | | [`await x`](#await) | Await expression | | `**` | Exponentiation [5](#id21) | | `+x`, `-x`, `~x` | Positive, negative, bitwise NOT | | `*`, `@`, `/`, `//`, `%` | Multiplication, matrix multiplication, division, floor division, remainder [6](#id22) | | `+`, `-` | Addition and subtraction | | `<<`, `>>` | Shifts | | `&` | Bitwise AND | | `^` | Bitwise XOR | | `|` | Bitwise OR | | [`in`](#in), [`not in`](#not-in), [`is`](#is), [`is not`](#is-not), `<`, `<=`, `>`, `>=`, `!=`, `==` | Comparisons, including membership tests and identity tests | | [`not x`](#not) | Boolean NOT | | [`and`](#and) | Boolean AND | | [`or`](#or) | Boolean OR | | [`if`](#if-expr) – `else` | Conditional expression | | [`lambda`](#lambda) | Lambda expression | | `:=` | Assignment expression | #### Footnotes `1` While `abs(x%y) < abs(y)` is true mathematically, for floats it may not be true numerically due to roundoff. For example, and assuming a platform on which a Python float is an IEEE 754 double-precision number, in order that `-1e-100 % 1e100` have the same sign as `1e100`, the computed result is `-1e-100 + 1e100`, which is numerically exactly equal to `1e100`. The function [`math.fmod()`](../library/math#math.fmod "math.fmod") returns a result whose sign matches the sign of the first argument instead, and so returns `-1e-100` in this case. Which approach is more appropriate depends on the application. `2` If x is very close to an exact integer multiple of y, it’s possible for `x//y` to be one larger than `(x-x%y)//y` due to rounding. In such cases, Python returns the latter result, in order to preserve that `divmod(x,y)[0] * y + x % y` be very close to `x`. `3` The Unicode standard distinguishes between *code points* (e.g. U+0041) and *abstract characters* (e.g. “LATIN CAPITAL LETTER A”). While most abstract characters in Unicode are only represented using one code point, there is a number of abstract characters that can in addition be represented using a sequence of more than one code point. For example, the abstract character “LATIN CAPITAL LETTER C WITH CEDILLA” can be represented as a single *precomposed character* at code position U+00C7, or as a sequence of a *base character* at code position U+0043 (LATIN CAPITAL LETTER C), followed by a *combining character* at code position U+0327 (COMBINING CEDILLA). The comparison operators on strings compare at the level of Unicode code points. This may be counter-intuitive to humans. For example, `"\u00C7" == "\u0043\u0327"` is `False`, even though both strings represent the same abstract character “LATIN CAPITAL LETTER C WITH CEDILLA”. To compare strings at the level of abstract characters (that is, in a way intuitive to humans), use [`unicodedata.normalize()`](../library/unicodedata#unicodedata.normalize "unicodedata.normalize"). `4` Due to automatic garbage-collection, free lists, and the dynamic nature of descriptors, you may notice seemingly unusual behaviour in certain uses of the [`is`](#is) operator, like those involving comparisons between instance methods, or constants. Check their documentation for more info. `5` The power operator `**` binds less tightly than an arithmetic or bitwise unary operator on its right, that is, `2**-1` is `0.5`. `6` The `%` operator is also used for string formatting; the same precedence applies.
programming_docs
python Simple statements Simple statements ================== A simple statement is comprised within a single logical line. Several simple statements may occur on a single line separated by semicolons. The syntax for simple statements is: ``` **simple\_stmt** ::= [expression\_stmt](#grammar-token-expression-stmt) | [assert\_stmt](#grammar-token-assert-stmt) | [assignment\_stmt](#grammar-token-assignment-stmt) | [augmented\_assignment\_stmt](#grammar-token-augmented-assignment-stmt) | [annotated\_assignment\_stmt](#grammar-token-annotated-assignment-stmt) | [pass\_stmt](#grammar-token-pass-stmt) | [del\_stmt](#grammar-token-del-stmt) | [return\_stmt](#grammar-token-return-stmt) | [yield\_stmt](#grammar-token-yield-stmt) | [raise\_stmt](#grammar-token-raise-stmt) | [break\_stmt](#grammar-token-break-stmt) | [continue\_stmt](#grammar-token-continue-stmt) | [import\_stmt](#grammar-token-import-stmt) | [future\_stmt](#grammar-token-future-stmt) | [global\_stmt](#grammar-token-global-stmt) | [nonlocal\_stmt](#grammar-token-nonlocal-stmt) ``` 7.1. Expression statements --------------------------- Expression statements are used (mostly interactively) to compute and write a value, or (usually) to call a procedure (a function that returns no meaningful result; in Python, procedures return the value `None`). Other uses of expression statements are allowed and occasionally useful. The syntax for an expression statement is: ``` **expression\_stmt** ::= [starred\_expression](expressions#grammar-token-starred-expression) ``` An expression statement evaluates the expression list (which may be a single expression). In interactive mode, if the value is not `None`, it is converted to a string using the built-in [`repr()`](../library/functions#repr "repr") function and the resulting string is written to standard output on a line by itself (except if the result is `None`, so that procedure calls do not cause any output.) 7.2. Assignment statements --------------------------- Assignment statements are used to (re)bind names to values and to modify attributes or items of mutable objects: ``` **assignment\_stmt** ::= ([target\_list](#grammar-token-target-list) "=")+ ([starred\_expression](expressions#grammar-token-starred-expression) | [yield\_expression](expressions#grammar-token-yield-expression)) **target\_list** ::= [target](#grammar-token-target) ("," [target](#grammar-token-target))* [","] **target** ::= [identifier](lexical_analysis#grammar-token-identifier) | "(" [[target\_list](#grammar-token-target-list)] ")" | "[" [[target\_list](#grammar-token-target-list)] "]" | [attributeref](expressions#grammar-token-attributeref) | [subscription](expressions#grammar-token-subscription) | [slicing](expressions#grammar-token-slicing) | "*" [target](#grammar-token-target) ``` (See section [Primaries](expressions#primaries) for the syntax definitions for *attributeref*, *subscription*, and *slicing*.) An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right. Assignment is defined recursively depending on the form of the target (list). When a target is part of a mutable object (an attribute reference, subscription or slicing), the mutable object must ultimately perform the assignment and decide about its validity, and may raise an exception if the assignment is unacceptable. The rules observed by various types and the exceptions raised are given with the definition of the object types (see section [The standard type hierarchy](datamodel#types)). Assignment of an object to a target list, optionally enclosed in parentheses or square brackets, is recursively defined as follows. * If the target list is a single target with no trailing comma, optionally in parentheses, the object is assigned to that target. * Else: + If the target list contains one target prefixed with an asterisk, called a “starred” target: The object must be an iterable with at least as many items as there are targets in the target list, minus one. The first items of the iterable are assigned, from left to right, to the targets before the starred target. The final items of the iterable are assigned to the targets after the starred target. A list of the remaining items in the iterable is then assigned to the starred target (the list can be empty). + Else: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets. Assignment of an object to a single target is recursively defined as follows. * If the target is an identifier (name): + If the name does not occur in a [`global`](#global) or [`nonlocal`](#nonlocal) statement in the current code block: the name is bound to the object in the current local namespace. + Otherwise: the name is bound to the object in the global namespace or the outer namespace determined by [`nonlocal`](#nonlocal), respectively.The name is rebound if it was already bound. This may cause the reference count for the object previously bound to the name to reach zero, causing the object to be deallocated and its destructor (if it has one) to be called. * If the target is an attribute reference: The primary expression in the reference is evaluated. It should yield an object with assignable attributes; if this is not the case, [`TypeError`](../library/exceptions#TypeError "TypeError") is raised. That object is then asked to assign the assigned object to the given attribute; if it cannot perform the assignment, it raises an exception (usually but not necessarily [`AttributeError`](../library/exceptions#AttributeError "AttributeError")). Note: If the object is a class instance and the attribute reference occurs on both sides of the assignment operator, the right-hand side expression, `a.x` can access either an instance attribute or (if no instance attribute exists) a class attribute. The left-hand side target `a.x` is always set as an instance attribute, creating it if necessary. Thus, the two occurrences of `a.x` do not necessarily refer to the same attribute: if the right-hand side expression refers to a class attribute, the left-hand side creates a new instance attribute as the target of the assignment: ``` class Cls: x = 3 # class variable inst = Cls() inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3 ``` This description does not necessarily apply to descriptor attributes, such as properties created with [`property()`](../library/functions#property "property"). * If the target is a subscription: The primary expression in the reference is evaluated. It should yield either a mutable sequence object (such as a list) or a mapping object (such as a dictionary). Next, the subscript expression is evaluated. If the primary is a mutable sequence object (such as a list), the subscript must yield an integer. If it is negative, the sequence’s length is added to it. The resulting value must be a nonnegative integer less than the sequence’s length, and the sequence is asked to assign the assigned object to its item with that index. If the index is out of range, [`IndexError`](../library/exceptions#IndexError "IndexError") is raised (assignment to a subscripted sequence cannot add new items to a list). If the primary is a mapping object (such as a dictionary), the subscript must have a type compatible with the mapping’s key type, and the mapping is then asked to create a key/datum pair which maps the subscript to the assigned object. This can either replace an existing key/value pair with the same key value, or insert a new key/value pair (if no key with the same value existed). For user-defined objects, the [`__setitem__()`](datamodel#object.__setitem__ "object.__setitem__") method is called with appropriate arguments. * If the target is a slicing: The primary expression in the reference is evaluated. It should yield a mutable sequence object (such as a list). The assigned object should be a sequence object of the same type. Next, the lower and upper bound expressions are evaluated, insofar they are present; defaults are zero and the sequence’s length. The bounds should evaluate to integers. If either bound is negative, the sequence’s length is added to it. The resulting bounds are clipped to lie between zero and the sequence’s length, inclusive. Finally, the sequence object is asked to replace the slice with the items of the assigned sequence. The length of the slice may be different from the length of the assigned sequence, thus changing the length of the target sequence, if the target sequence allows it. **CPython implementation detail:** In the current implementation, the syntax for targets is taken to be the same as for expressions, and invalid syntax is rejected during the code generation phase, causing less detailed error messages. Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are ‘simultaneous’ (for example `a, b = b, a` swaps two variables), overlaps *within* the collection of assigned-to variables occur left-to-right, sometimes resulting in confusion. For instance, the following program prints `[0, 2]`: ``` x = [0, 1] i = 0 i, x[i] = 1, 2 # i is updated, then x[i] is updated print(x) ``` See also [**PEP 3132**](https://www.python.org/dev/peps/pep-3132) - Extended Iterable Unpacking The specification for the `*target` feature. ### 7.2.1. Augmented assignment statements Augmented assignment is the combination, in a single statement, of a binary operation and an assignment statement: ``` **augmented\_assignment\_stmt** ::= [augtarget](#grammar-token-augtarget) [augop](#grammar-token-augop) ([expression\_list](expressions#grammar-token-expression-list) | [yield\_expression](expressions#grammar-token-yield-expression)) **augtarget** ::= [identifier](lexical_analysis#grammar-token-identifier) | [attributeref](expressions#grammar-token-attributeref) | [subscription](expressions#grammar-token-subscription) | [slicing](expressions#grammar-token-slicing) **augop** ::= "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**=" | ">>=" | "<<=" | "&=" | "^=" | "|=" ``` (See section [Primaries](expressions#primaries) for the syntax definitions of the last three symbols.) An augmented assignment evaluates the target (which, unlike normal assignment statements, cannot be an unpacking) and the expression list, performs the binary operation specific to the type of assignment on the two operands, and assigns the result to the original target. The target is only evaluated once. An augmented assignment expression like `x += 1` can be rewritten as `x = x + 1` to achieve a similar, but not exactly equal effect. In the augmented version, `x` is only evaluated once. Also, when possible, the actual operation is performed *in-place*, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead. Unlike normal assignments, augmented assignments evaluate the left-hand side *before* evaluating the right-hand side. For example, `a[i] += f(x)` first looks-up `a[i]`, then it evaluates `f(x)` and performs the addition, and lastly, it writes the result back to `a[i]`. With the exception of assigning to tuples and multiple targets in a single statement, the assignment done by augmented assignment statements is handled the same way as normal assignments. Similarly, with the exception of the possible *in-place* behavior, the binary operation performed by augmented assignment is the same as the normal binary operations. For targets which are attribute references, the same [caveat about class and instance attributes](#attr-target-note) applies as for regular assignments. ### 7.2.2. Annotated assignment statements [Annotation](../glossary#term-variable-annotation) assignment is the combination, in a single statement, of a variable or attribute annotation and an optional assignment statement: ``` **annotated\_assignment\_stmt** ::= [augtarget](#grammar-token-augtarget) ":" [expression](expressions#grammar-token-expression) ["=" ([starred\_expression](expressions#grammar-token-starred-expression) | [yield\_expression](expressions#grammar-token-yield-expression))] ``` The difference from normal [Assignment statements](#assignment) is that only single target is allowed. For simple names as assignment targets, if in class or module scope, the annotations are evaluated and stored in a special class or module attribute `__annotations__` that is a dictionary mapping from variable names (mangled if private) to evaluated annotations. This attribute is writable and is automatically created at the start of class or module body execution, if annotations are found statically. For expressions as assignment targets, the annotations are evaluated if in class or module scope, but not stored. If a name is annotated in a function scope, then this name is local for that scope. Annotations are never evaluated and stored in function scopes. If the right hand side is present, an annotated assignment performs the actual assignment before evaluating annotations (where applicable). If the right hand side is not present for an expression target, then the interpreter evaluates the target except for the last [`__setitem__()`](datamodel#object.__setitem__ "object.__setitem__") or [`__setattr__()`](datamodel#object.__setattr__ "object.__setattr__") call. See also [**PEP 526**](https://www.python.org/dev/peps/pep-0526) - Syntax for Variable Annotations The proposal that added syntax for annotating the types of variables (including class variables and instance variables), instead of expressing them through comments. [**PEP 484**](https://www.python.org/dev/peps/pep-0484) - Type hints The proposal that added the [`typing`](../library/typing#module-typing "typing: Support for type hints (see :pep:`484`).") module to provide a standard syntax for type annotations that can be used in static analysis tools and IDEs. Changed in version 3.8: Now annotated assignments allow same expressions in the right hand side as the regular assignments. Previously, some expressions (like un-parenthesized tuple expressions) caused a syntax error. 7.3. The `assert` statement ---------------------------- Assert statements are a convenient way to insert debugging assertions into a program: ``` **assert\_stmt** ::= "assert" [expression](expressions#grammar-token-expression) ["," [expression](expressions#grammar-token-expression)] ``` The simple form, `assert expression`, is equivalent to ``` if __debug__: if not expression: raise AssertionError ``` The extended form, `assert expression1, expression2`, is equivalent to ``` if __debug__: if not expression1: raise AssertionError(expression2) ``` These equivalences assume that [`__debug__`](../library/constants#__debug__ "__debug__") and [`AssertionError`](../library/exceptions#AssertionError "AssertionError") refer to the built-in variables with those names. In the current implementation, the built-in variable [`__debug__`](../library/constants#__debug__ "__debug__") is `True` under normal circumstances, `False` when optimization is requested (command line option [`-O`](../using/cmdline#cmdoption-o)). The current code generator emits no code for an assert statement when optimization is requested at compile time. Note that it is unnecessary to include the source code for the expression that failed in the error message; it will be displayed as part of the stack trace. Assignments to [`__debug__`](../library/constants#__debug__ "__debug__") are illegal. The value for the built-in variable is determined when the interpreter starts. 7.4. The `pass` statement -------------------------- ``` **pass\_stmt** ::= "pass" ``` [`pass`](#pass) is a null operation — when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example: ``` def f(arg): pass # a function that does nothing (yet) class C: pass # a class with no methods (yet) ``` 7.5. The `del` statement ------------------------- ``` **del\_stmt** ::= "del" [target\_list](#grammar-token-target-list) ``` Deletion is recursively defined very similar to the way assignment is defined. Rather than spelling it out in full details, here are some hints. Deletion of a target list recursively deletes each target, from left to right. Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a [`global`](#global) statement in the same code block. If the name is unbound, a [`NameError`](../library/exceptions#NameError "NameError") exception will be raised. Deletion of attribute references, subscriptions and slicings is passed to the primary object involved; deletion of a slicing is in general equivalent to assignment of an empty slice of the right type (but even this is determined by the sliced object). Changed in version 3.2: Previously it was illegal to delete a name from the local namespace if it occurs as a free variable in a nested block. 7.6. The `return` statement ---------------------------- ``` **return\_stmt** ::= "return" [[expression\_list](expressions#grammar-token-expression-list)] ``` [`return`](#return) may only occur syntactically nested in a function definition, not within a nested class definition. If an expression list is present, it is evaluated, else `None` is substituted. [`return`](#return) leaves the current function call with the expression list (or `None`) as return value. When [`return`](#return) passes control out of a [`try`](compound_stmts#try) statement with a [`finally`](compound_stmts#finally) clause, that `finally` clause is executed before really leaving the function. In a generator function, the [`return`](#return) statement indicates that the generator is done and will cause [`StopIteration`](../library/exceptions#StopIteration "StopIteration") to be raised. The returned value (if any) is used as an argument to construct [`StopIteration`](../library/exceptions#StopIteration "StopIteration") and becomes the `StopIteration.value` attribute. In an asynchronous generator function, an empty [`return`](#return) statement indicates that the asynchronous generator is done and will cause [`StopAsyncIteration`](../library/exceptions#StopAsyncIteration "StopAsyncIteration") to be raised. A non-empty `return` statement is a syntax error in an asynchronous generator function. 7.7. The `yield` statement --------------------------- ``` **yield\_stmt** ::= [yield\_expression](expressions#grammar-token-yield-expression) ``` A [`yield`](#yield) statement is semantically equivalent to a [yield expression](expressions#yieldexpr). The yield statement can be used to omit the parentheses that would otherwise be required in the equivalent yield expression statement. For example, the yield statements ``` yield <expr> yield from <expr> ``` are equivalent to the yield expression statements ``` (yield <expr>) (yield from <expr>) ``` Yield expressions and statements are only used when defining a [generator](../glossary#term-generator) function, and are only used in the body of the generator function. Using yield in a function definition is sufficient to cause that definition to create a generator function instead of a normal function. For full details of [`yield`](#yield) semantics, refer to the [Yield expressions](expressions#yieldexpr) section. 7.8. The `raise` statement --------------------------- ``` **raise\_stmt** ::= "raise" [[expression](expressions#grammar-token-expression) ["from" [expression](expressions#grammar-token-expression)]] ``` If no expressions are present, [`raise`](#raise) re-raises the exception that is currently being handled, which is also known as the *active exception*. If there isn’t currently an active exception, a [`RuntimeError`](../library/exceptions#RuntimeError "RuntimeError") exception is raised indicating that this is an error. Otherwise, [`raise`](#raise) evaluates the first expression as the exception object. It must be either a subclass or an instance of [`BaseException`](../library/exceptions#BaseException "BaseException"). If it is a class, the exception instance will be obtained when needed by instantiating the class with no arguments. The *type* of the exception is the exception instance’s class, the *value* is the instance itself. A traceback object is normally created automatically when an exception is raised and attached to it as the `__traceback__` attribute, which is writable. You can create an exception and set your own traceback in one step using the [`with_traceback()`](../library/exceptions#BaseException.with_traceback "BaseException.with_traceback") exception method (which returns the same exception instance, with its traceback set to its argument), like so: ``` raise Exception("foo occurred").with_traceback(tracebackobj) ``` The `from` clause is used for exception chaining: if given, the second *expression* must be another exception class or instance. If the second expression is an exception instance, it will be attached to the raised exception as the `__cause__` attribute (which is writable). If the expression is an exception class, the class will be instantiated and the resulting exception instance will be attached to the raised exception as the `__cause__` attribute. If the raised exception is not handled, both exceptions will be printed: ``` >>> try: ... print(1 / 0) ... except Exception as exc: ... raise RuntimeError("Something bad happened") from exc ... Traceback (most recent call last): File "<stdin>", line 2, in <module> ZeroDivisionError: division by zero The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<stdin>", line 4, in <module> RuntimeError: Something bad happened ``` A similar mechanism works implicitly if a new exception is raised when an exception is already being handled. An exception may be handled when an [`except`](compound_stmts#except) or [`finally`](compound_stmts#finally) clause, or a [`with`](compound_stmts#with) statement, is used. The previous exception is then attached as the new exception’s `__context__` attribute: ``` >>> try: ... print(1 / 0) ... except: ... raise RuntimeError("Something bad happened") ... Traceback (most recent call last): File "<stdin>", line 2, in <module> ZeroDivisionError: division by zero During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 4, in <module> RuntimeError: Something bad happened ``` Exception chaining can be explicitly suppressed by specifying [`None`](../library/constants#None "None") in the `from` clause: ``` >>> try: ... print(1 / 0) ... except: ... raise RuntimeError("Something bad happened") from None ... Traceback (most recent call last): File "<stdin>", line 4, in <module> RuntimeError: Something bad happened ``` Additional information on exceptions can be found in section [Exceptions](executionmodel#exceptions), and information about handling exceptions is in section [The try statement](compound_stmts#try). Changed in version 3.3: [`None`](../library/constants#None "None") is now permitted as `Y` in `raise X from Y`. New in version 3.3: The `__suppress_context__` attribute to suppress automatic display of the exception context. 7.9. The `break` statement --------------------------- ``` **break\_stmt** ::= "break" ``` [`break`](#break) may only occur syntactically nested in a [`for`](compound_stmts#for) or [`while`](compound_stmts#while) loop, but not nested in a function or class definition within that loop. It terminates the nearest enclosing loop, skipping the optional `else` clause if the loop has one. If a [`for`](compound_stmts#for) loop is terminated by [`break`](#break), the loop control target keeps its current value. When [`break`](#break) passes control out of a [`try`](compound_stmts#try) statement with a [`finally`](compound_stmts#finally) clause, that `finally` clause is executed before really leaving the loop. 7.10. The `continue` statement ------------------------------- ``` **continue\_stmt** ::= "continue" ``` [`continue`](#continue) may only occur syntactically nested in a [`for`](compound_stmts#for) or [`while`](compound_stmts#while) loop, but not nested in a function or class definition within that loop. It continues with the next cycle of the nearest enclosing loop. When [`continue`](#continue) passes control out of a [`try`](compound_stmts#try) statement with a [`finally`](compound_stmts#finally) clause, that `finally` clause is executed before really starting the next loop cycle. 7.11. The `import` statement ----------------------------- ``` **import\_stmt** ::= "import" [module](#grammar-token-module) ["as" [identifier](lexical_analysis#grammar-token-identifier)] ("," [module](#grammar-token-module) ["as" [identifier](lexical_analysis#grammar-token-identifier)])* | "from" [relative\_module](#grammar-token-relative-module) "import" [identifier](lexical_analysis#grammar-token-identifier) ["as" [identifier](lexical_analysis#grammar-token-identifier)] ("," [identifier](lexical_analysis#grammar-token-identifier) ["as" [identifier](lexical_analysis#grammar-token-identifier)])* | "from" [relative\_module](#grammar-token-relative-module) "import" "(" [identifier](lexical_analysis#grammar-token-identifier) ["as" [identifier](lexical_analysis#grammar-token-identifier)] ("," [identifier](lexical_analysis#grammar-token-identifier) ["as" [identifier](lexical_analysis#grammar-token-identifier)])* [","] ")" | "from" [relative\_module](#grammar-token-relative-module) "import" "*" **module** ::= ([identifier](lexical_analysis#grammar-token-identifier) ".")* [identifier](lexical_analysis#grammar-token-identifier) **relative\_module** ::= "."* [module](#grammar-token-module) | "."+ ``` The basic import statement (no [`from`](#from) clause) is executed in two steps: 1. find a module, loading and initializing it if necessary 2. define a name or names in the local namespace for the scope where the [`import`](#import) statement occurs. When the statement contains multiple clauses (separated by commas) the two steps are carried out separately for each clause, just as though the clauses had been separated out into individual import statements. The details of the first step, finding and loading modules are described in greater detail in the section on the [import system](import#importsystem), which also describes the various types of packages and modules that can be imported, as well as all the hooks that can be used to customize the import system. Note that failures in this step may indicate either that the module could not be located, *or* that an error occurred while initializing the module, which includes execution of the module’s code. If the requested module is retrieved successfully, it will be made available in the local namespace in one of three ways: * If the module name is followed by `as`, then the name following `as` is bound directly to the imported module. * If no other name is specified, and the module being imported is a top level module, the module’s name is bound in the local namespace as a reference to the imported module * If the module being imported is *not* a top level module, then the name of the top level package that contains the module is bound in the local namespace as a reference to the top level package. The imported module must be accessed using its full qualified name rather than directly The [`from`](#from) form uses a slightly more complex process: 1. find the module specified in the [`from`](#from) clause, loading and initializing it if necessary; 2. for each of the identifiers specified in the [`import`](#import) clauses: 1. check if the imported module has an attribute by that name 2. if not, attempt to import a submodule with that name and then check the imported module again for that attribute 3. if the attribute is not found, [`ImportError`](../library/exceptions#ImportError "ImportError") is raised. 4. otherwise, a reference to that value is stored in the local namespace, using the name in the `as` clause if it is present, otherwise using the attribute name Examples: ``` import foo # foo imported and bound locally import foo.bar.baz # foo, foo.bar, and foo.bar.baz imported, foo bound locally import foo.bar.baz as fbb # foo, foo.bar, and foo.bar.baz imported, foo.bar.baz bound as fbb from foo.bar import baz # foo, foo.bar, and foo.bar.baz imported, foo.bar.baz bound as baz from foo import attr # foo imported and foo.attr bound as attr ``` If the list of identifiers is replaced by a star (`'*'`), all public names defined in the module are bound in the local namespace for the scope where the [`import`](#import) statement occurs. The *public names* defined by a module are determined by checking the module’s namespace for a variable named `__all__`; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in `__all__` are all considered public and are required to exist. If `__all__` is not defined, the set of public names includes all names found in the module’s namespace which do not begin with an underscore character (`'_'`). `__all__` should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module). The wild card form of import — `from module import *` — is only allowed at the module level. Attempting to use it in class or function definitions will raise a [`SyntaxError`](../library/exceptions#SyntaxError "SyntaxError"). When specifying what module to import you do not have to specify the absolute name of the module. When a module or package is contained within another package it is possible to make a relative import within the same top package without having to mention the package name. By using leading dots in the specified module or package after [`from`](#from) you can specify how high to traverse up the current package hierarchy without specifying exact names. One leading dot means the current package where the module making the import exists. Two dots means up one package level. Three dots is up two levels, etc. So if you execute `from . import mod` from a module in the `pkg` package then you will end up importing `pkg.mod`. If you execute `from ..subpkg2 import mod` from within `pkg.subpkg1` you will import `pkg.subpkg2.mod`. The specification for relative imports is contained in the [Package Relative Imports](import#relativeimports) section. [`importlib.import_module()`](../library/importlib#importlib.import_module "importlib.import_module") is provided to support applications that determine dynamically the modules to be loaded. Raises an [auditing event](../library/sys#auditing) `import` with arguments `module`, `filename`, `sys.path`, `sys.meta_path`, `sys.path_hooks`. ### 7.11.1. Future statements A *future statement* is a directive to the compiler that a particular module should be compiled using syntax or semantics that will be available in a specified future release of Python where the feature becomes standard. The future statement is intended to ease migration to future versions of Python that introduce incompatible changes to the language. It allows use of the new features on a per-module basis before the release in which the feature becomes standard. ``` **future\_stmt** ::= "from" "__future__" "import" [feature](#grammar-token-feature) ["as" [identifier](lexical_analysis#grammar-token-identifier)] ("," [feature](#grammar-token-feature) ["as" [identifier](lexical_analysis#grammar-token-identifier)])* | "from" "__future__" "import" "(" [feature](#grammar-token-feature) ["as" [identifier](lexical_analysis#grammar-token-identifier)] ("," [feature](#grammar-token-feature) ["as" [identifier](lexical_analysis#grammar-token-identifier)])* [","] ")" **feature** ::= [identifier](lexical_analysis#grammar-token-identifier) ``` A future statement must appear near the top of the module. The only lines that can appear before a future statement are: * the module docstring (if any), * comments, * blank lines, and * other future statements. The only feature that requires using the future statement is `annotations` (see [**PEP 563**](https://www.python.org/dev/peps/pep-0563)). All historical features enabled by the future statement are still recognized by Python 3. The list includes `absolute_import`, `division`, `generators`, `generator_stop`, `unicode_literals`, `print_function`, `nested_scopes` and `with_statement`. They are all redundant because they are always enabled, and only kept for backwards compatibility. A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime. For any given release, the compiler knows which feature names have been defined, and raises a compile-time error if a future statement contains a feature not known to it. The direct runtime semantics are the same as for any import statement: there is a standard module [`__future__`](../library/__future__#module-__future__ "__future__: Future statement definitions"), described later, and it will be imported in the usual way at the time the future statement is executed. The interesting runtime semantics depend on the specific feature enabled by the future statement. Note that there is nothing special about the statement: ``` import __future__ [as name] ``` That is not a future statement; it’s an ordinary import statement with no special semantics or syntax restrictions. Code compiled by calls to the built-in functions [`exec()`](../library/functions#exec "exec") and [`compile()`](../library/functions#compile "compile") that occur in a module `M` containing a future statement will, by default, use the new syntax or semantics associated with the future statement. This can be controlled by optional arguments to [`compile()`](../library/functions#compile "compile") — see the documentation of that function for details. A future statement typed at an interactive interpreter prompt will take effect for the rest of the interpreter session. If an interpreter is started with the [`-i`](../using/cmdline#cmdoption-i) option, is passed a script name to execute, and the script includes a future statement, it will be in effect in the interactive session started after the script is executed. See also [**PEP 236**](https://www.python.org/dev/peps/pep-0236) - Back to the \_\_future\_\_ The original proposal for the \_\_future\_\_ mechanism. 7.12. The `global` statement ----------------------------- ``` **global\_stmt** ::= "global" [identifier](lexical_analysis#grammar-token-identifier) ("," [identifier](lexical_analysis#grammar-token-identifier))* ``` The [`global`](#global) statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without `global`, although free variables may refer to globals without being declared global. Names listed in a [`global`](#global) statement must not be used in the same code block textually preceding that `global` statement. Names listed in a [`global`](#global) statement must not be defined as formal parameters or in a [`for`](compound_stmts#for) loop control target, [`class`](compound_stmts#class) definition, function definition, [`import`](#import) statement, or variable annotation. **CPython implementation detail:** The current implementation does not enforce some of these restrictions, but programs should not abuse this freedom, as future implementations may enforce them or silently change the meaning of the program. **Programmer’s note:** [`global`](#global) is a directive to the parser. It applies only to code parsed at the same time as the `global` statement. In particular, a `global` statement contained in a string or code object supplied to the built-in [`exec()`](../library/functions#exec "exec") function does not affect the code block *containing* the function call, and code contained in such a string is unaffected by `global` statements in the code containing the function call. The same applies to the [`eval()`](../library/functions#eval "eval") and [`compile()`](../library/functions#compile "compile") functions. 7.13. The `nonlocal` statement ------------------------------- ``` **nonlocal\_stmt** ::= "nonlocal" [identifier](lexical_analysis#grammar-token-identifier) ("," [identifier](lexical_analysis#grammar-token-identifier))* ``` The [`nonlocal`](#nonlocal) statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope. Names listed in a [`nonlocal`](#nonlocal) statement, unlike those listed in a [`global`](#global) statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously). Names listed in a [`nonlocal`](#nonlocal) statement must not collide with pre-existing bindings in the local scope. See also [**PEP 3104**](https://www.python.org/dev/peps/pep-3104) - Access to Names in Outer Scopes The specification for the [`nonlocal`](#nonlocal) statement.
programming_docs
python Introduction Introduction ============= This reference manual describes the Python programming language. It is not intended as a tutorial. While I am trying to be as precise as possible, I chose to use English rather than formal specifications for everything except syntax and lexical analysis. This should make the document more understandable to the average reader, but will leave room for ambiguities. Consequently, if you were coming from Mars and tried to re-implement Python from this document alone, you might have to guess things and in fact you would probably end up implementing quite a different language. On the other hand, if you are using Python and wonder what the precise rules about a particular area of the language are, you should definitely be able to find them here. If you would like to see a more formal definition of the language, maybe you could volunteer your time — or invent a cloning machine :-). It is dangerous to add too many implementation details to a language reference document — the implementation may change, and other implementations of the same language may work differently. On the other hand, CPython is the one Python implementation in widespread use (although alternate implementations continue to gain support), and its particular quirks are sometimes worth being mentioned, especially where the implementation imposes additional limitations. Therefore, you’ll find short “implementation notes” sprinkled throughout the text. Every Python implementation comes with a number of built-in and standard modules. These are documented in [The Python Standard Library](../library/index#library-index). A few built-in modules are mentioned when they interact in a significant way with the language definition. 1.1. Alternate Implementations ------------------------------- Though there is one Python implementation which is by far the most popular, there are some alternate implementations which are of particular interest to different audiences. Known implementations include: CPython This is the original and most-maintained implementation of Python, written in C. New language features generally appear here first. Jython Python implemented in Java. This implementation can be used as a scripting language for Java applications, or can be used to create applications using the Java class libraries. It is also often used to create tests for Java libraries. More information can be found at [the Jython website](http://www.jython.org/). Python for .NET This implementation actually uses the CPython implementation, but is a managed .NET application and makes .NET libraries available. It was created by Brian Lloyd. For more information, see the [Python for .NET home page](https://pythonnet.github.io/). IronPython An alternate Python for .NET. Unlike Python.NET, this is a complete Python implementation that generates IL, and compiles Python code directly to .NET assemblies. It was created by Jim Hugunin, the original creator of Jython. For more information, see [the IronPython website](http://ironpython.net/). PyPy An implementation of Python written completely in Python. It supports several advanced features not found in other implementations like stackless support and a Just in Time compiler. One of the goals of the project is to encourage experimentation with the language itself by making it easier to modify the interpreter (since it is written in Python). Additional information is available on [the PyPy project’s home page](http://pypy.org/). Each of these implementations varies in some way from the language as documented in this manual, or introduces specific information beyond what’s covered in the standard Python documentation. Please refer to the implementation-specific documentation to determine what else you need to know about the specific implementation you’re using. 1.2. Notation -------------- The descriptions of lexical analysis and syntax use a modified BNF grammar notation. This uses the following style of definition: ``` **name** ::= [lc\_letter](#grammar-token-lc-letter) ([lc\_letter](#grammar-token-lc-letter) | "_")* **lc\_letter** ::= "a"..."z" ``` The first line says that a `name` is an `lc_letter` followed by a sequence of zero or more `lc_letter`s and underscores. An `lc_letter` in turn is any of the single characters `'a'` through `'z'`. (This rule is actually adhered to for the names defined in lexical and grammar rules in this document.) Each rule begins with a name (which is the name defined by the rule) and `::=`. A vertical bar (`|`) is used to separate alternatives; it is the least binding operator in this notation. A star (`*`) means zero or more repetitions of the preceding item; likewise, a plus (`+`) means one or more repetitions, and a phrase enclosed in square brackets (`[ ]`) means zero or one occurrences (in other words, the enclosed phrase is optional). The `*` and `+` operators bind as tightly as possible; parentheses are used for grouping. Literal strings are enclosed in quotes. White space is only meaningful to separate tokens. Rules are normally contained on a single line; rules with many alternatives may be formatted alternatively with each line after the first beginning with a vertical bar. In lexical definitions (as the example above), two more conventions are used: Two literal characters separated by three dots mean a choice of any single character in the given (inclusive) range of ASCII characters. A phrase between angular brackets (`<...>`) gives an informal description of the symbol defined; e.g., this could be used to describe the notion of ‘control character’ if needed. Even though the notation used is almost the same, there is a big difference between the meaning of lexical and syntactic definitions: a lexical definition operates on the individual characters of the input source, while a syntax definition operates on the stream of tokens generated by the lexical analysis. All uses of BNF in the next chapter (“Lexical Analysis”) are lexical definitions; uses in subsequent chapters are syntactic definitions. python Compound statements Compound statements ==================== Compound statements contain (groups of) other statements; they affect or control the execution of those other statements in some way. In general, compound statements span multiple lines, although in simple incarnations a whole compound statement may be contained in one line. The [`if`](#if), [`while`](#while) and [`for`](#for) statements implement traditional control flow constructs. [`try`](#try) specifies exception handlers and/or cleanup code for a group of statements, while the [`with`](#with) statement allows the execution of initialization and finalization code around a block of code. Function and class definitions are also syntactically compound statements. A compound statement consists of one or more ‘clauses.’ A clause consists of a header and a ‘suite.’ The clause headers of a particular compound statement are all at the same indentation level. Each clause header begins with a uniquely identifying keyword and ends with a colon. A suite is a group of statements controlled by a clause. A suite can be one or more semicolon-separated simple statements on the same line as the header, following the header’s colon, or it can be one or more indented statements on subsequent lines. Only the latter form of a suite can contain nested compound statements; the following is illegal, mostly because it wouldn’t be clear to which [`if`](#if) clause a following [`else`](#else) clause would belong: ``` if test1: if test2: print(x) ``` Also note that the semicolon binds tighter than the colon in this context, so that in the following example, either all or none of the [`print()`](../library/functions#print "print") calls are executed: ``` if x < y < z: print(x); print(y); print(z) ``` Summarizing: ``` **compound\_stmt** ::= [if\_stmt](#grammar-token-if-stmt) | [while\_stmt](#grammar-token-while-stmt) | [for\_stmt](#grammar-token-for-stmt) | [try\_stmt](#grammar-token-try-stmt) | [with\_stmt](#grammar-token-with-stmt) | [funcdef](#grammar-token-funcdef) | [classdef](#grammar-token-classdef) | [async\_with\_stmt](#grammar-token-async-with-stmt) | [async\_for\_stmt](#grammar-token-async-for-stmt) | [async\_funcdef](#grammar-token-async-funcdef) **suite** ::= [stmt\_list](#grammar-token-stmt-list) NEWLINE | NEWLINE INDENT [statement](#grammar-token-statement)+ DEDENT **statement** ::= [stmt\_list](#grammar-token-stmt-list) NEWLINE | [compound\_stmt](#grammar-token-compound-stmt) **stmt\_list** ::= [simple\_stmt](simple_stmts#grammar-token-simple-stmt) (";" [simple\_stmt](simple_stmts#grammar-token-simple-stmt))* [";"] ``` Note that statements always end in a `NEWLINE` possibly followed by a `DEDENT`. Also note that optional continuation clauses always begin with a keyword that cannot start a statement, thus there are no ambiguities (the ‘dangling [`else`](#else)’ problem is solved in Python by requiring nested [`if`](#if) statements to be indented). The formatting of the grammar rules in the following sections places each clause on a separate line for clarity. 8.1. The `if` statement ------------------------ The [`if`](#if) statement is used for conditional execution: ``` **if\_stmt** ::= "if" [assignment\_expression](expressions#grammar-token-assignment-expression) ":" [suite](#grammar-token-suite) ("elif" [assignment\_expression](expressions#grammar-token-assignment-expression) ":" [suite](#grammar-token-suite))* ["else" ":" [suite](#grammar-token-suite)] ``` It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true (see section [Boolean operations](expressions#booleans) for the definition of true and false); then that suite is executed (and no other part of the [`if`](#if) statement is executed or evaluated). If all expressions are false, the suite of the [`else`](#else) clause, if present, is executed. 8.2. The `while` statement --------------------------- The [`while`](#while) statement is used for repeated execution as long as an expression is true: ``` **while\_stmt** ::= "while" [assignment\_expression](expressions#grammar-token-assignment-expression) ":" [suite](#grammar-token-suite) ["else" ":" [suite](#grammar-token-suite)] ``` This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the `else` clause, if present, is executed and the loop terminates. A [`break`](simple_stmts#break) statement executed in the first suite terminates the loop without executing the `else` clause’s suite. A [`continue`](simple_stmts#continue) statement executed in the first suite skips the rest of the suite and goes back to testing the expression. 8.3. The `for` statement ------------------------- The [`for`](#for) statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object: ``` **for\_stmt** ::= "for" [target\_list](simple_stmts#grammar-token-target-list) "in" [expression\_list](expressions#grammar-token-expression-list) ":" [suite](#grammar-token-suite) ["else" ":" [suite](#grammar-token-suite)] ``` The expression list is evaluated once; it should yield an iterable object. An iterator is created for the result of the `expression_list`. The suite is then executed once for each item provided by the iterator, in the order returned by the iterator. Each item in turn is assigned to the target list using the standard rules for assignments (see [Assignment statements](simple_stmts#assignment)), and then the suite is executed. When the items are exhausted (which is immediately when the sequence is empty or an iterator raises a [`StopIteration`](../library/exceptions#StopIteration "StopIteration") exception), the suite in the `else` clause, if present, is executed, and the loop terminates. A [`break`](simple_stmts#break) statement executed in the first suite terminates the loop without executing the `else` clause’s suite. A [`continue`](simple_stmts#continue) statement executed in the first suite skips the rest of the suite and continues with the next item, or with the `else` clause if there is no next item. The for-loop makes assignments to the variables in the target list. This overwrites all previous assignments to those variables including those made in the suite of the for-loop: ``` for i in range(10): print(i) i = 5 # this will not affect the for-loop # because i will be overwritten with the next # index in the range ``` Names in the target list are not deleted when the loop is finished, but if the sequence is empty, they will not have been assigned to at all by the loop. Hint: the built-in function [`range()`](../library/stdtypes#range "range") returns an iterator of integers suitable to emulate the effect of Pascal’s `for i := a to b do`; e.g., `list(range(3))` returns the list `[0, 1, 2]`. Note There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, e.g. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop. This can lead to nasty bugs that can be avoided by making a temporary copy using a slice of the whole sequence, e.g., ``` for x in a[:]: if x < 0: a.remove(x) ``` 8.4. The `try` statement ------------------------- The [`try`](#try) statement specifies exception handlers and/or cleanup code for a group of statements: ``` **try\_stmt** ::= [try1\_stmt](#grammar-token-try1-stmt) | [try2\_stmt](#grammar-token-try2-stmt) **try1\_stmt** ::= "try" ":" [suite](#grammar-token-suite) ("except" [[expression](expressions#grammar-token-expression) ["as" [identifier](lexical_analysis#grammar-token-identifier)]] ":" [suite](#grammar-token-suite))+ ["else" ":" [suite](#grammar-token-suite)] ["finally" ":" [suite](#grammar-token-suite)] **try2\_stmt** ::= "try" ":" [suite](#grammar-token-suite) "finally" ":" [suite](#grammar-token-suite) ``` The [`except`](#except) clause(s) specify one or more exception handlers. When no exception occurs in the [`try`](#try) clause, no exception handler is executed. When an exception occurs in the `try` suite, a search for an exception handler is started. This search inspects the except clauses in turn until one is found that matches the exception. An expression-less except clause, if present, must be last; it matches any exception. For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is “compatible” with the exception. An object is compatible with an exception if the object is the class or a [non-virtual base class](../glossary#term-abstract-base-class) of the exception object, or a tuple containing an item that is the class or a non-virtual base class of the exception object. If no except clause matches the exception, the search for an exception handler continues in the surrounding code and on the invocation stack. [1](#id4) If the evaluation of an expression in the header of an except clause raises an exception, the original search for a handler is canceled and a search starts for the new exception in the surrounding code and on the call stack (it is treated as if the entire [`try`](#try) statement raised the exception). When a matching except clause is found, the exception is assigned to the target specified after the `as` keyword in that except clause, if present, and the except clause’s suite is executed. All except clauses must have an executable block. When the end of this block is reached, execution continues normally after the entire try statement. (This means that if two nested handlers exist for the same exception, and the exception occurs in the try clause of the inner handler, the outer handler will not handle the exception.) When an exception has been assigned using `as target`, it is cleared at the end of the except clause. This is as if ``` except E as N: foo ``` was translated to ``` except E as N: try: foo finally: del N ``` This means the exception must be assigned to a different name to be able to refer to it after the except clause. Exceptions are cleared because with the traceback attached to them, they form a reference cycle with the stack frame, keeping all locals in that frame alive until the next garbage collection occurs. Before an except clause’s suite is executed, details about the exception are stored in the [`sys`](../library/sys#module-sys "sys: Access system-specific parameters and functions.") module and can be accessed via [`sys.exc_info()`](../library/sys#sys.exc_info "sys.exc_info"). [`sys.exc_info()`](../library/sys#sys.exc_info "sys.exc_info") returns a 3-tuple consisting of the exception class, the exception instance and a traceback object (see section [The standard type hierarchy](datamodel#types)) identifying the point in the program where the exception occurred. [`sys.exc_info()`](../library/sys#sys.exc_info "sys.exc_info") values are restored to their previous values (before the call) when returning from a function that handled an exception. The optional `else` clause is executed if the control flow leaves the [`try`](#try) suite, no exception was raised, and no [`return`](simple_stmts#return), [`continue`](simple_stmts#continue), or [`break`](simple_stmts#break) statement was executed. Exceptions in the `else` clause are not handled by the preceding [`except`](#except) clauses. If [`finally`](#finally) is present, it specifies a ‘cleanup’ handler. The [`try`](#try) clause is executed, including any [`except`](#except) and `else` clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The `finally` clause is executed. If there is a saved exception it is re-raised at the end of the `finally` clause. If the `finally` clause raises another exception, the saved exception is set as the context of the new exception. If the `finally` clause executes a [`return`](simple_stmts#return), [`break`](simple_stmts#break) or [`continue`](simple_stmts#continue) statement, the saved exception is discarded: ``` >>> def f(): ... try: ... 1/0 ... finally: ... return 42 ... >>> f() 42 ``` The exception information is not available to the program during execution of the [`finally`](#finally) clause. When a [`return`](simple_stmts#return), [`break`](simple_stmts#break) or [`continue`](simple_stmts#continue) statement is executed in the [`try`](#try) suite of a `try`…`finally` statement, the [`finally`](#finally) clause is also executed ‘on the way out.’ The return value of a function is determined by the last [`return`](simple_stmts#return) statement executed. Since the [`finally`](#finally) clause always executes, a `return` statement executed in the `finally` clause will always be the last one executed: ``` >>> def foo(): ... try: ... return 'try' ... finally: ... return 'finally' ... >>> foo() 'finally' ``` Additional information on exceptions can be found in section [Exceptions](executionmodel#exceptions), and information on using the [`raise`](simple_stmts#raise) statement to generate exceptions may be found in section [The raise statement](simple_stmts#raise). Changed in version 3.8: Prior to Python 3.8, a [`continue`](simple_stmts#continue) statement was illegal in the [`finally`](#finally) clause due to a problem with the implementation. 8.5. The `with` statement -------------------------- The [`with`](#with) statement is used to wrap the execution of a block with methods defined by a context manager (see section [With Statement Context Managers](datamodel#context-managers)). This allows common [`try`](#try)…[`except`](#except)…[`finally`](#finally) usage patterns to be encapsulated for convenient reuse. ``` **with\_stmt** ::= "with" [with\_item](#grammar-token-with-item) ("," [with\_item](#grammar-token-with-item))* ":" [suite](#grammar-token-suite) **with\_item** ::= [expression](expressions#grammar-token-expression) ["as" [target](simple_stmts#grammar-token-target)] ``` The execution of the [`with`](#with) statement with one “item” proceeds as follows: 1. The context expression (the expression given in the [`with_item`](#grammar-token-with-item)) is evaluated to obtain a context manager. 2. The context manager’s [`__enter__()`](datamodel#object.__enter__ "object.__enter__") is loaded for later use. 3. The context manager’s [`__exit__()`](datamodel#object.__exit__ "object.__exit__") is loaded for later use. 4. The context manager’s [`__enter__()`](datamodel#object.__enter__ "object.__enter__") method is invoked. 5. If a target was included in the [`with`](#with) statement, the return value from [`__enter__()`](datamodel#object.__enter__ "object.__enter__") is assigned to it. Note The [`with`](#with) statement guarantees that if the [`__enter__()`](datamodel#object.__enter__ "object.__enter__") method returns without an error, then [`__exit__()`](datamodel#object.__exit__ "object.__exit__") will always be called. Thus, if an error occurs during the assignment to the target list, it will be treated the same as an error occurring within the suite would be. See step 6 below. 6. The suite is executed. 7. The context manager’s [`__exit__()`](datamodel#object.__exit__ "object.__exit__") method is invoked. If an exception caused the suite to be exited, its type, value, and traceback are passed as arguments to [`__exit__()`](datamodel#object.__exit__ "object.__exit__"). Otherwise, three [`None`](../library/constants#None "None") arguments are supplied. If the suite was exited due to an exception, and the return value from the [`__exit__()`](datamodel#object.__exit__ "object.__exit__") method was false, the exception is reraised. If the return value was true, the exception is suppressed, and execution continues with the statement following the [`with`](#with) statement. If the suite was exited for any reason other than an exception, the return value from [`__exit__()`](datamodel#object.__exit__ "object.__exit__") is ignored, and execution proceeds at the normal location for the kind of exit that was taken. The following code: ``` with EXPRESSION as TARGET: SUITE ``` is semantically equivalent to: ``` manager = (EXPRESSION) enter = type(manager).__enter__ exit = type(manager).__exit__ value = enter(manager) hit_except = False try: TARGET = value SUITE except: hit_except = True if not exit(manager, *sys.exc_info()): raise finally: if not hit_except: exit(manager, None, None, None) ``` With more than one item, the context managers are processed as if multiple [`with`](#with) statements were nested: ``` with A() as a, B() as b: SUITE ``` is semantically equivalent to: ``` with A() as a: with B() as b: SUITE ``` Changed in version 3.1: Support for multiple context expressions. See also [**PEP 343**](https://www.python.org/dev/peps/pep-0343) - The “with” statement The specification, background, and examples for the Python [`with`](#with) statement. 8.6. Function definitions -------------------------- A function definition defines a user-defined function object (see section [The standard type hierarchy](datamodel#types)): ``` **funcdef** ::= [[decorators](#grammar-token-decorators)] "def" [funcname](#grammar-token-funcname) "(" [[parameter\_list](#grammar-token-parameter-list)] ")" ["->" [expression](expressions#grammar-token-expression)] ":" [suite](#grammar-token-suite) **decorators** ::= [decorator](#grammar-token-decorator)+ **decorator** ::= "@" [assignment\_expression](expressions#grammar-token-assignment-expression) NEWLINE **parameter\_list** ::= [defparameter](#grammar-token-defparameter) ("," [defparameter](#grammar-token-defparameter))* "," "/" ["," [[parameter\_list\_no\_posonly](#grammar-token-parameter-list-no-posonly)]] | [parameter\_list\_no\_posonly](#grammar-token-parameter-list-no-posonly) **parameter\_list\_no\_posonly** ::= [defparameter](#grammar-token-defparameter) ("," [defparameter](#grammar-token-defparameter))* ["," [[parameter\_list\_starargs](#grammar-token-parameter-list-starargs)]] | [parameter\_list\_starargs](#grammar-token-parameter-list-starargs) **parameter\_list\_starargs** ::= "*" [[parameter](#grammar-token-parameter)] ("," [defparameter](#grammar-token-defparameter))* ["," ["**" [parameter](#grammar-token-parameter) [","]]] | "**" [parameter](#grammar-token-parameter) [","] **parameter** ::= [identifier](lexical_analysis#grammar-token-identifier) [":" [expression](expressions#grammar-token-expression)] **defparameter** ::= [parameter](#grammar-token-parameter) ["=" [expression](expressions#grammar-token-expression)] **funcname** ::= [identifier](lexical_analysis#grammar-token-identifier) ``` A function definition is an executable statement. Its execution binds the function name in the current local namespace to a function object (a wrapper around the executable code for the function). This function object contains a reference to the current global namespace as the global namespace to be used when the function is called. The function definition does not execute the function body; this gets executed only when the function is called. [2](#id5) A function definition may be wrapped by one or more [decorator](../glossary#term-decorator) expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. The returned value is bound to the function name instead of the function object. Multiple decorators are applied in nested fashion. For example, the following code ``` @f1(arg) @f2 def func(): pass ``` is roughly equivalent to ``` def func(): pass func = f1(arg)(f2(func)) ``` except that the original function is not temporarily bound to the name `func`. Changed in version 3.9: Functions may be decorated with any valid [`assignment_expression`](expressions#grammar-token-assignment-expression). Previously, the grammar was much more restrictive; see [**PEP 614**](https://www.python.org/dev/peps/pep-0614) for details. When one or more [parameters](../glossary#term-parameter) have the form *parameter* `=` *expression*, the function is said to have “default parameter values.” For a parameter with a default value, the corresponding [argument](../glossary#term-argument) may be omitted from a call, in which case the parameter’s default value is substituted. If a parameter has a default value, all following parameters up until the “`*`” must also have a default value — this is a syntactic restriction that is not expressed by the grammar. **Default parameter values are evaluated from left to right when the function definition is executed.** This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use `None` as the default, and explicitly test for it in the body of the function, e.g.: ``` def whats_on_the_telly(penguin=None): if penguin is None: penguin = [] penguin.append("property of the zoo") return penguin ``` Function call semantics are described in more detail in section [Calls](expressions#calls). A function call always assigns values to all parameters mentioned in the parameter list, either from positional arguments, from keyword arguments, or from default values. If the form “`*identifier`” is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form “`**identifier`” is present, it is initialized to a new ordered mapping receiving any excess keyword arguments, defaulting to a new empty mapping of the same type. Parameters after “`*`” or “`*identifier`” are keyword-only parameters and may only be passed by keyword arguments. Parameters before “`/`” are positional-only parameters and may only be passed by positional arguments. Changed in version 3.8: The `/` function parameter syntax may be used to indicate positional-only parameters. See [**PEP 570**](https://www.python.org/dev/peps/pep-0570) for details. Parameters may have an [annotation](../glossary#term-function-annotation) of the form “`: expression`” following the parameter name. Any parameter may have an annotation, even those of the form `*identifier` or `**identifier`. Functions may have “return” annotation of the form “`-> expression`” after the parameter list. These annotations can be any valid Python expression. The presence of annotations does not change the semantics of a function. The annotation values are available as values of a dictionary keyed by the parameters’ names in the `__annotations__` attribute of the function object. If the `annotations` import from [`__future__`](../library/__future__#module-__future__ "__future__: Future statement definitions") is used, annotations are preserved as strings at runtime which enables postponed evaluation. Otherwise, they are evaluated when the function definition is executed. In this case annotations may be evaluated in a different order than they appear in the source code. It is also possible to create anonymous functions (functions not bound to a name), for immediate use in expressions. This uses lambda expressions, described in section [Lambdas](expressions#lambda). Note that the lambda expression is merely a shorthand for a simplified function definition; a function defined in a “[`def`](#def)” statement can be passed around or assigned to another name just like a function defined by a lambda expression. The “`def`” form is actually more powerful since it allows the execution of multiple statements and annotations. **Programmer’s note:** Functions are first-class objects. A “`def`” statement executed inside a function definition defines a local function that can be returned or passed around. Free variables used in the nested function can access the local variables of the function containing the def. See section [Naming and binding](executionmodel#naming) for details. See also [**PEP 3107**](https://www.python.org/dev/peps/pep-3107) - Function Annotations The original specification for function annotations. [**PEP 484**](https://www.python.org/dev/peps/pep-0484) - Type Hints Definition of a standard meaning for annotations: type hints. [**PEP 526**](https://www.python.org/dev/peps/pep-0526) - Syntax for Variable Annotations Ability to type hint variable declarations, including class variables and instance variables [**PEP 563**](https://www.python.org/dev/peps/pep-0563) - Postponed Evaluation of Annotations Support for forward references within annotations by preserving annotations in a string form at runtime instead of eager evaluation. 8.7. Class definitions ----------------------- A class definition defines a class object (see section [The standard type hierarchy](datamodel#types)): ``` **classdef** ::= [[decorators](#grammar-token-decorators)] "class" [classname](#grammar-token-classname) [[inheritance](#grammar-token-inheritance)] ":" [suite](#grammar-token-suite) **inheritance** ::= "(" [[argument\_list](expressions#grammar-token-argument-list)] ")" **classname** ::= [identifier](lexical_analysis#grammar-token-identifier) ``` A class definition is an executable statement. The inheritance list usually gives a list of base classes (see [Metaclasses](datamodel#metaclasses) for more advanced uses), so each item in the list should evaluate to a class object which allows subclassing. Classes without an inheritance list inherit, by default, from the base class [`object`](../library/functions#object "object"); hence, ``` class Foo: pass ``` is equivalent to ``` class Foo(object): pass ``` The class’s suite is then executed in a new execution frame (see [Naming and binding](executionmodel#naming)), using a newly created local namespace and the original global namespace. (Usually, the suite contains mostly function definitions.) When the class’s suite finishes execution, its execution frame is discarded but its local namespace is saved. [3](#id6) A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary. The class name is bound to this class object in the original local namespace. The order in which attributes are defined in the class body is preserved in the new class’s `__dict__`. Note that this is reliable only right after the class is created and only for classes that were defined using the definition syntax. Class creation can be customized heavily using [metaclasses](datamodel#metaclasses). Classes can also be decorated: just like when decorating functions, ``` @f1(arg) @f2 class Foo: pass ``` is roughly equivalent to ``` class Foo: pass Foo = f1(arg)(f2(Foo)) ``` The evaluation rules for the decorator expressions are the same as for function decorators. The result is then bound to the class name. Changed in version 3.9: Classes may be decorated with any valid [`assignment_expression`](expressions#grammar-token-assignment-expression). Previously, the grammar was much more restrictive; see [**PEP 614**](https://www.python.org/dev/peps/pep-0614) for details. **Programmer’s note:** Variables defined in the class definition are class attributes; they are shared by instances. Instance attributes can be set in a method with `self.name = value`. Both class and instance attributes are accessible through the notation “`self.name`”, and an instance attribute hides a class attribute with the same name when accessed in this way. Class attributes can be used as defaults for instance attributes, but using mutable values there can lead to unexpected results. [Descriptors](datamodel#descriptors) can be used to create instance variables with different implementation details. See also [**PEP 3115**](https://www.python.org/dev/peps/pep-3115) - Metaclasses in Python 3000 The proposal that changed the declaration of metaclasses to the current syntax, and the semantics for how classes with metaclasses are constructed. [**PEP 3129**](https://www.python.org/dev/peps/pep-3129) - Class Decorators The proposal that added class decorators. Function and method decorators were introduced in [**PEP 318**](https://www.python.org/dev/peps/pep-0318). 8.8. Coroutines ---------------- New in version 3.5. ### 8.8.1. Coroutine function definition ``` **async\_funcdef** ::= [[decorators](#grammar-token-decorators)] "async" "def" [funcname](#grammar-token-funcname) "(" [[parameter\_list](#grammar-token-parameter-list)] ")" ["->" [expression](expressions#grammar-token-expression)] ":" [suite](#grammar-token-suite) ``` Execution of Python coroutines can be suspended and resumed at many points (see [coroutine](../glossary#term-coroutine)). Inside the body of a coroutine function, `await` and `async` identifiers become reserved keywords; [`await`](expressions#await) expressions, [`async for`](#async-for) and [`async with`](#async-with) can only be used in coroutine function bodies. Functions defined with `async def` syntax are always coroutine functions, even if they do not contain `await` or `async` keywords. It is a [`SyntaxError`](../library/exceptions#SyntaxError "SyntaxError") to use a `yield from` expression inside the body of a coroutine function. An example of a coroutine function: ``` async def func(param1, param2): do_stuff() await some_coroutine() ``` ### 8.8.2. The `async for` statement ``` **async\_for\_stmt** ::= "async" [for\_stmt](#grammar-token-for-stmt) ``` An [asynchronous iterable](../glossary#term-asynchronous-iterable) provides an `__aiter__` method that directly returns an [asynchronous iterator](../glossary#term-asynchronous-iterator), which can call asynchronous code in its `__anext__` method. The `async for` statement allows convenient iteration over asynchronous iterables. The following code: ``` async for TARGET in ITER: SUITE else: SUITE2 ``` Is semantically equivalent to: ``` iter = (ITER) iter = type(iter).__aiter__(iter) running = True while running: try: TARGET = await type(iter).__anext__(iter) except StopAsyncIteration: running = False else: SUITE else: SUITE2 ``` See also [`__aiter__()`](datamodel#object.__aiter__ "object.__aiter__") and [`__anext__()`](datamodel#object.__anext__ "object.__anext__") for details. It is a [`SyntaxError`](../library/exceptions#SyntaxError "SyntaxError") to use an `async for` statement outside the body of a coroutine function. ### 8.8.3. The `async with` statement ``` **async\_with\_stmt** ::= "async" [with\_stmt](#grammar-token-with-stmt) ``` An [asynchronous context manager](../glossary#term-asynchronous-context-manager) is a [context manager](../glossary#term-context-manager) that is able to suspend execution in its *enter* and *exit* methods. The following code: ``` async with EXPRESSION as TARGET: SUITE ``` is semantically equivalent to: ``` manager = (EXPRESSION) aenter = type(manager).__aenter__ aexit = type(manager).__aexit__ value = await aenter(manager) hit_except = False try: TARGET = value SUITE except: hit_except = True if not await aexit(manager, *sys.exc_info()): raise finally: if not hit_except: await aexit(manager, None, None, None) ``` See also [`__aenter__()`](datamodel#object.__aenter__ "object.__aenter__") and [`__aexit__()`](datamodel#object.__aexit__ "object.__aexit__") for details. It is a [`SyntaxError`](../library/exceptions#SyntaxError "SyntaxError") to use an `async with` statement outside the body of a coroutine function. See also [**PEP 492**](https://www.python.org/dev/peps/pep-0492) - Coroutines with async and await syntax The proposal that made coroutines a proper standalone concept in Python, and added supporting syntax. #### Footnotes `1` The exception is propagated to the invocation stack unless there is a [`finally`](#finally) clause which happens to raise another exception. That new exception causes the old one to be lost. `2` A string literal appearing as the first statement in the function body is transformed into the function’s `__doc__` attribute and therefore the function’s [docstring](../glossary#term-docstring). `3` A string literal appearing as the first statement in the class body is transformed into the namespace’s `__doc__` item and therefore the class’s [docstring](../glossary#term-docstring).
programming_docs
python Data model Data model =========== 3.1. Objects, values and types ------------------------------- *Objects* are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects. (In a sense, and in conformance to Von Neumann’s model of a “stored program computer”, code is also represented by objects.) Every object has an identity, a type and a value. An object’s *identity* never changes once it has been created; you may think of it as the object’s address in memory. The ‘[`is`](expressions#is)’ operator compares the identity of two objects; the [`id()`](../library/functions#id "id") function returns an integer representing its identity. **CPython implementation detail:** For CPython, `id(x)` is the memory address where `x` is stored. An object’s type determines the operations that the object supports (e.g., “does it have a length?”) and also defines the possible values for objects of that type. The [`type()`](../library/functions#type "type") function returns an object’s type (which is an object itself). Like its identity, an object’s *type* is also unchangeable. [1](#id8) The *value* of some objects can change. Objects whose value can change are said to be *mutable*; objects whose value is unchangeable once they are created are called *immutable*. (The value of an immutable container object that contains a reference to a mutable object can change when the latter’s value is changed; however the container is still considered immutable, because the collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value, it is more subtle.) An object’s mutability is determined by its type; for instance, numbers, strings and tuples are immutable, while dictionaries and lists are mutable. Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether — it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable. **CPython implementation detail:** CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references. See the documentation of the [`gc`](../library/gc#module-gc "gc: Interface to the cycle-detecting garbage collector.") module for information on controlling the collection of cyclic garbage. Other implementations act differently and CPython may change. Do not depend on immediate finalization of objects when they become unreachable (so you should always close files explicitly). Note that the use of the implementation’s tracing or debugging facilities may keep objects alive that would normally be collectable. Also note that catching an exception with a ‘[`try`](compound_stmts#try)…[`except`](compound_stmts#except)’ statement may keep objects alive. Some objects contain references to “external” resources such as open files or windows. It is understood that these resources are freed when the object is garbage-collected, but since garbage collection is not guaranteed to happen, such objects also provide an explicit way to release the external resource, usually a `close()` method. Programs are strongly recommended to explicitly close such objects. The ‘[`try`](compound_stmts#try)…[`finally`](compound_stmts#finally)’ statement and the ‘[`with`](compound_stmts#with)’ statement provide convenient ways to do this. Some objects contain references to other objects; these are called *containers*. Examples of containers are tuples, lists and dictionaries. The references are part of a container’s value. In most cases, when we talk about the value of a container, we imply the values, not the identities of the contained objects; however, when we talk about the mutability of a container, only the identities of the immediately contained objects are implied. So, if an immutable container (like a tuple) contains a reference to a mutable object, its value changes if that mutable object is changed. Types affect almost all aspects of object behavior. Even the importance of object identity is affected in some sense: for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed. E.g., after `a = 1; b = 1`, `a` and `b` may or may not refer to the same object with the value one, depending on the implementation, but after `c = []; d = []`, `c` and `d` are guaranteed to refer to two different, unique, newly created empty lists. (Note that `c = d = []` assigns the same object to both `c` and `d`.) 3.2. The standard type hierarchy --------------------------------- Below is a list of the types that are built into Python. Extension modules (written in C, Java, or other languages, depending on the implementation) can define additional types. Future versions of Python may add types to the type hierarchy (e.g., rational numbers, efficiently stored arrays of integers, etc.), although such additions will often be provided via the standard library instead. Some of the type descriptions below contain a paragraph listing ‘special attributes.’ These are attributes that provide access to the implementation and are not intended for general use. Their definition may change in the future. None This type has a single value. There is a single object with this value. This object is accessed through the built-in name `None`. It is used to signify the absence of a value in many situations, e.g., it is returned from functions that don’t explicitly return anything. Its truth value is false. NotImplemented This type has a single value. There is a single object with this value. This object is accessed through the built-in name `NotImplemented`. Numeric methods and rich comparison methods should return this value if they do not implement the operation for the operands provided. (The interpreter will then try the reflected operation, or some other fallback, depending on the operator.) It should not be evaluated in a boolean context. See [Implementing the arithmetic operations](../library/numbers#implementing-the-arithmetic-operations) for more details. Changed in version 3.9: Evaluating `NotImplemented` in a boolean context is deprecated. While it currently evaluates as true, it will emit a [`DeprecationWarning`](../library/exceptions#DeprecationWarning "DeprecationWarning"). It will raise a [`TypeError`](../library/exceptions#TypeError "TypeError") in a future version of Python. Ellipsis This type has a single value. There is a single object with this value. This object is accessed through the literal `...` or the built-in name `Ellipsis`. Its truth value is true. [`numbers.Number`](../library/numbers#numbers.Number "numbers.Number") These are created by numeric literals and returned as results by arithmetic operators and arithmetic built-in functions. Numeric objects are immutable; once created their value never changes. Python numbers are of course strongly related to mathematical numbers, but subject to the limitations of numerical representation in computers. The string representations of the numeric classes, computed by [`__repr__()`](#object.__repr__ "object.__repr__") and [`__str__()`](#object.__str__ "object.__str__"), have the following properties: * They are valid numeric literals which, when passed to their class constructor, produce an object having the value of the original numeric. * The representation is in base 10, when possible. * Leading zeros, possibly excepting a single zero before a decimal point, are not shown. * Trailing zeros, possibly excepting a single zero after a decimal point, are not shown. * A sign is shown only when the number is negative. Python distinguishes between integers, floating point numbers, and complex numbers: [`numbers.Integral`](../library/numbers#numbers.Integral "numbers.Integral") These represent elements from the mathematical set of integers (positive and negative). There are two types of integers: `Integers (int)` These represent numbers in an unlimited range, subject to available (virtual) memory only. For the purpose of shift and mask operations, a binary representation is assumed, and negative numbers are represented in a variant of 2’s complement which gives the illusion of an infinite string of sign bits extending to the left. `Booleans (bool)` These represent the truth values False and True. The two objects representing the values `False` and `True` are the only Boolean objects. The Boolean type is a subtype of the integer type, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings `"False"` or `"True"` are returned, respectively. The rules for integer representation are intended to give the most meaningful interpretation of shift and mask operations involving negative integers. `numbers.Real (float)` These represent machine-level double precision floating point numbers. You are at the mercy of the underlying machine architecture (and C or Java implementation) for the accepted range and handling of overflow. Python does not support single-precision floating point numbers; the savings in processor and memory usage that are usually the reason for using these are dwarfed by the overhead of using objects in Python, so there is no reason to complicate the language with two kinds of floating point numbers. `numbers.Complex (complex)` These represent complex numbers as a pair of machine-level double precision floating point numbers. The same caveats apply as for floating point numbers. The real and imaginary parts of a complex number `z` can be retrieved through the read-only attributes `z.real` and `z.imag`. Sequences These represent finite ordered sets indexed by non-negative numbers. The built-in function [`len()`](../library/functions#len "len") returns the number of items of a sequence. When the length of a sequence is *n*, the index set contains the numbers 0, 1, …, *n*-1. Item *i* of sequence *a* is selected by `a[i]`. Sequences also support slicing: `a[i:j]` selects all items with index *k* such that *i* `<=` *k* `<` *j*. When used as an expression, a slice is a sequence of the same type. This implies that the index set is renumbered so that it starts at 0. Some sequences also support “extended slicing” with a third “step” parameter: `a[i:j:k]` selects all items of *a* with index *x* where `x = i + n*k`, *n* `>=` `0` and *i* `<=` *x* `<` *j*. Sequences are distinguished according to their mutability: Immutable sequences An object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be changed; however, the collection of objects directly referenced by an immutable object cannot change.) The following types are immutable sequences: Strings A string is a sequence of values that represent Unicode code points. All the code points in the range `U+0000 - U+10FFFF` can be represented in a string. Python doesn’t have a `char` type; instead, every code point in the string is represented as a string object with length `1`. The built-in function [`ord()`](../library/functions#ord "ord") converts a code point from its string form to an integer in the range `0 - 10FFFF`; [`chr()`](../library/functions#chr "chr") converts an integer in the range `0 - 10FFFF` to the corresponding length `1` string object. [`str.encode()`](../library/stdtypes#str.encode "str.encode") can be used to convert a [`str`](../library/stdtypes#str "str") to [`bytes`](../library/stdtypes#bytes "bytes") using the given text encoding, and [`bytes.decode()`](../library/stdtypes#bytes.decode "bytes.decode") can be used to achieve the opposite. Tuples The items of a tuple are arbitrary Python objects. Tuples of two or more items are formed by comma-separated lists of expressions. A tuple of one item (a ‘singleton’) can be formed by affixing a comma to an expression (an expression by itself does not create a tuple, since parentheses must be usable for grouping of expressions). An empty tuple can be formed by an empty pair of parentheses. Bytes A bytes object is an immutable array. The items are 8-bit bytes, represented by integers in the range 0 <= x < 256. Bytes literals (like `b'abc'`) and the built-in [`bytes()`](../library/stdtypes#bytes "bytes") constructor can be used to create bytes objects. Also, bytes objects can be decoded to strings via the [`decode()`](../library/stdtypes#bytes.decode "bytes.decode") method. Mutable sequences Mutable sequences can be changed after they are created. The subscription and slicing notations can be used as the target of assignment and [`del`](simple_stmts#del) (delete) statements. There are currently two intrinsic mutable sequence types: Lists The items of a list are arbitrary Python objects. Lists are formed by placing a comma-separated list of expressions in square brackets. (Note that there are no special cases needed to form lists of length 0 or 1.) Byte Arrays A bytearray object is a mutable array. They are created by the built-in [`bytearray()`](../library/stdtypes#bytearray "bytearray") constructor. Aside from being mutable (and hence unhashable), byte arrays otherwise provide the same interface and functionality as immutable [`bytes`](../library/stdtypes#bytes "bytes") objects. The extension module [`array`](../library/array#module-array "array: Space efficient arrays of uniformly typed numeric values.") provides an additional example of a mutable sequence type, as does the [`collections`](../library/collections#module-collections "collections: Container datatypes") module. Set types These represent unordered, finite sets of unique, immutable objects. As such, they cannot be indexed by any subscript. However, they can be iterated over, and the built-in function [`len()`](../library/functions#len "len") returns the number of items in a set. Common uses for sets are fast membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. For set elements, the same immutability rules apply as for dictionary keys. Note that numeric types obey the normal rules for numeric comparison: if two numbers compare equal (e.g., `1` and `1.0`), only one of them can be contained in a set. There are currently two intrinsic set types: Sets These represent a mutable set. They are created by the built-in [`set()`](../library/stdtypes#set "set") constructor and can be modified afterwards by several methods, such as `add()`. Frozen sets These represent an immutable set. They are created by the built-in [`frozenset()`](../library/stdtypes#frozenset "frozenset") constructor. As a frozenset is immutable and [hashable](../glossary#term-hashable), it can be used again as an element of another set, or as a dictionary key. Mappings These represent finite sets of objects indexed by arbitrary index sets. The subscript notation `a[k]` selects the item indexed by `k` from the mapping `a`; this can be used in expressions and as the target of assignments or [`del`](simple_stmts#del) statements. The built-in function [`len()`](../library/functions#len "len") returns the number of items in a mapping. There is currently a single intrinsic mapping type: Dictionaries These represent finite sets of objects indexed by nearly arbitrary values. The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of dictionaries requires a key’s hash value to remain constant. Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (e.g., `1` and `1.0`) then they can be used interchangeably to index the same dictionary entry. Dictionaries preserve insertion order, meaning that keys will be produced in the same order they were added sequentially over the dictionary. Replacing an existing key does not change the order, however removing a key and re-inserting it will add it to the end instead of keeping its old place. Dictionaries are mutable; they can be created by the `{...}` notation (see section [Dictionary displays](expressions#dict)). The extension modules [`dbm.ndbm`](../library/dbm#module-dbm.ndbm "dbm.ndbm: The standard \"database\" interface, based on ndbm. (Unix)") and [`dbm.gnu`](../library/dbm#module-dbm.gnu "dbm.gnu: GNU's reinterpretation of dbm. (Unix)") provide additional examples of mapping types, as does the [`collections`](../library/collections#module-collections "collections: Container datatypes") module. Changed in version 3.7: Dictionaries did not preserve insertion order in versions of Python before 3.6. In CPython 3.6, insertion order was preserved, but it was considered an implementation detail at that time rather than a language guarantee. Callable types These are the types to which the function call operation (see section [Calls](expressions#calls)) can be applied: User-defined functions A user-defined function object is created by a function definition (see section [Function definitions](compound_stmts#function)). It should be called with an argument list containing the same number of items as the function’s formal parameter list. Special attributes: | Attribute | Meaning | | | --- | --- | --- | | `__doc__` | The function’s documentation string, or `None` if unavailable; not inherited by subclasses. | Writable | | [`__name__`](../library/stdtypes#definition.__name__ "definition.__name__") | The function’s name. | Writable | | [`__qualname__`](../library/stdtypes#definition.__qualname__ "definition.__qualname__") | The function’s [qualified name](../glossary#term-qualified-name). New in version 3.3. | Writable | | `__module__` | The name of the module the function was defined in, or `None` if unavailable. | Writable | | `__defaults__` | A tuple containing default argument values for those arguments that have defaults, or `None` if no arguments have a default value. | Writable | | `__code__` | The code object representing the compiled function body. | Writable | | `__globals__` | A reference to the dictionary that holds the function’s global variables — the global namespace of the module in which the function was defined. | Read-only | | [`__dict__`](../library/stdtypes#object.__dict__ "object.__dict__") | The namespace supporting arbitrary function attributes. | Writable | | `__closure__` | `None` or a tuple of cells that contain bindings for the function’s free variables. See below for information on the `cell_contents` attribute. | Read-only | | `__annotations__` | A dict containing annotations of parameters. The keys of the dict are the parameter names, and `'return'` for the return annotation, if provided. | Writable | | `__kwdefaults__` | A dict containing defaults for keyword-only parameters. | Writable | Most of the attributes labelled “Writable” check the type of the assigned value. Function objects also support getting and setting arbitrary attributes, which can be used, for example, to attach metadata to functions. Regular attribute dot-notation is used to get and set such attributes. *Note that the current implementation only supports function attributes on user-defined functions. Function attributes on built-in functions may be supported in the future.* A cell object has the attribute `cell_contents`. This can be used to get the value of the cell, as well as set the value. Additional information about a function’s definition can be retrieved from its code object; see the description of internal types below. The [`cell`](../library/types#types.CellType "types.CellType") type can be accessed in the [`types`](../library/types#module-types "types: Names for built-in types.") module. Instance methods An instance method object combines a class, a class instance and any callable object (normally a user-defined function). Special read-only attributes: `__self__` is the class instance object, `__func__` is the function object; `__doc__` is the method’s documentation (same as `__func__.__doc__`); [`__name__`](../library/stdtypes#definition.__name__ "definition.__name__") is the method name (same as `__func__.__name__`); `__module__` is the name of the module the method was defined in, or `None` if unavailable. Methods also support accessing (but not setting) the arbitrary function attributes on the underlying function object. User-defined method objects may be created when getting an attribute of a class (perhaps via an instance of that class), if that attribute is a user-defined function object or a class method object. When an instance method object is created by retrieving a user-defined function object from a class via one of its instances, its `__self__` attribute is the instance, and the method object is said to be bound. The new method’s `__func__` attribute is the original function object. When an instance method object is created by retrieving a class method object from a class or instance, its `__self__` attribute is the class itself, and its `__func__` attribute is the function object underlying the class method. When an instance method object is called, the underlying function (`__func__`) is called, inserting the class instance (`__self__`) in front of the argument list. For instance, when `C` is a class which contains a definition for a function `f()`, and `x` is an instance of `C`, calling `x.f(1)` is equivalent to calling `C.f(x, 1)`. When an instance method object is derived from a class method object, the “class instance” stored in `__self__` will actually be the class itself, so that calling either `x.f(1)` or `C.f(1)` is equivalent to calling `f(C,1)` where `f` is the underlying function. Note that the transformation from function object to instance method object happens each time the attribute is retrieved from the instance. In some cases, a fruitful optimization is to assign the attribute to a local variable and call that local variable. Also notice that this transformation only happens for user-defined functions; other callable objects (and all non-callable objects) are retrieved without transformation. It is also important to note that user-defined functions which are attributes of a class instance are not converted to bound methods; this *only* happens when the function is an attribute of the class. Generator functions A function or method which uses the [`yield`](simple_stmts#yield) statement (see section [The yield statement](simple_stmts#yield)) is called a *generator function*. Such a function, when called, always returns an iterator object which can be used to execute the body of the function: calling the iterator’s [`iterator.__next__()`](../library/stdtypes#iterator.__next__ "iterator.__next__") method will cause the function to execute until it provides a value using the `yield` statement. When the function executes a [`return`](simple_stmts#return) statement or falls off the end, a [`StopIteration`](../library/exceptions#StopIteration "StopIteration") exception is raised and the iterator will have reached the end of the set of values to be returned. Coroutine functions A function or method which is defined using [`async def`](compound_stmts#async-def) is called a *coroutine function*. Such a function, when called, returns a [coroutine](../glossary#term-coroutine) object. It may contain [`await`](expressions#await) expressions, as well as [`async with`](compound_stmts#async-with) and [`async for`](compound_stmts#async-for) statements. See also the [Coroutine Objects](#coroutine-objects) section. Asynchronous generator functions A function or method which is defined using [`async def`](compound_stmts#async-def) and which uses the [`yield`](simple_stmts#yield) statement is called a *asynchronous generator function*. Such a function, when called, returns an asynchronous iterator object which can be used in an [`async for`](compound_stmts#async-for) statement to execute the body of the function. Calling the asynchronous iterator’s [`aiterator.__anext__`](#object.__anext__ "object.__anext__") method will return an [awaitable](../glossary#term-awaitable) which when awaited will execute until it provides a value using the [`yield`](simple_stmts#yield) expression. When the function executes an empty [`return`](simple_stmts#return) statement or falls off the end, a [`StopAsyncIteration`](../library/exceptions#StopAsyncIteration "StopAsyncIteration") exception is raised and the asynchronous iterator will have reached the end of the set of values to be yielded. Built-in functions A built-in function object is a wrapper around a C function. Examples of built-in functions are [`len()`](../library/functions#len "len") and [`math.sin()`](../library/math#math.sin "math.sin") ([`math`](../library/math#module-math "math: Mathematical functions (sin() etc.).") is a standard built-in module). The number and type of the arguments are determined by the C function. Special read-only attributes: `__doc__` is the function’s documentation string, or `None` if unavailable; [`__name__`](../library/stdtypes#definition.__name__ "definition.__name__") is the function’s name; `__self__` is set to `None` (but see the next item); `__module__` is the name of the module the function was defined in or `None` if unavailable. Built-in methods This is really a different disguise of a built-in function, this time containing an object passed to the C function as an implicit extra argument. An example of a built-in method is `alist.append()`, assuming *alist* is a list object. In this case, the special read-only attribute `__self__` is set to the object denoted by *alist*. Classes Classes are callable. These objects normally act as factories for new instances of themselves, but variations are possible for class types that override [`__new__()`](#object.__new__ "object.__new__"). The arguments of the call are passed to [`__new__()`](#object.__new__ "object.__new__") and, in the typical case, to [`__init__()`](#object.__init__ "object.__init__") to initialize the new instance. Class Instances Instances of arbitrary classes can be made callable by defining a [`__call__()`](#object.__call__ "object.__call__") method in their class. Modules Modules are a basic organizational unit of Python code, and are created by the [import system](import#importsystem) as invoked either by the [`import`](simple_stmts#import) statement, or by calling functions such as [`importlib.import_module()`](../library/importlib#importlib.import_module "importlib.import_module") and built-in [`__import__()`](../library/functions#__import__ "__import__"). A module object has a namespace implemented by a dictionary object (this is the dictionary referenced by the `__globals__` attribute of functions defined in the module). Attribute references are translated to lookups in this dictionary, e.g., `m.x` is equivalent to `m.__dict__["x"]`. A module object does not contain the code object used to initialize the module (since it isn’t needed once the initialization is done). Attribute assignment updates the module’s namespace dictionary, e.g., `m.x = 1` is equivalent to `m.__dict__["x"] = 1`. Predefined (writable) attributes: [`__name__`](import#__name__ "__name__") is the module’s name; `__doc__` is the module’s documentation string, or `None` if unavailable; `__annotations__` (optional) is a dictionary containing [variable annotations](../glossary#term-variable-annotation) collected during module body execution; [`__file__`](import#__file__ "__file__") is the pathname of the file from which the module was loaded, if it was loaded from a file. The [`__file__`](import#__file__ "__file__") attribute may be missing for certain types of modules, such as C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file. Special read-only attribute: [`__dict__`](../library/stdtypes#object.__dict__ "object.__dict__") is the module’s namespace as a dictionary object. **CPython implementation detail:** Because of the way CPython clears module dictionaries, the module dictionary will be cleared when the module falls out of scope even if the dictionary still has live references. To avoid this, copy the dictionary or keep the module around while using its dictionary directly. Custom classes Custom class types are typically created by class definitions (see section [Class definitions](compound_stmts#class)). A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., `C.x` is translated to `C.__dict__["x"]` (although there are a number of hooks which allow for other means of locating attributes). When the attribute name is not found there, the attribute search continues in the base classes. This search of the base classes uses the C3 method resolution order which behaves correctly even in the presence of ‘diamond’ inheritance structures where there are multiple inheritance paths leading back to a common ancestor. Additional details on the C3 MRO used by Python can be found in the documentation accompanying the 2.3 release at <https://www.python.org/download/releases/2.3/mro/>. When a class attribute reference (for class `C`, say) would yield a class method object, it is transformed into an instance method object whose `__self__` attribute is `C`. When it would yield a static method object, it is transformed into the object wrapped by the static method object. See section [Implementing Descriptors](#descriptors) for another way in which attributes retrieved from a class may differ from those actually contained in its [`__dict__`](../library/stdtypes#object.__dict__ "object.__dict__"). Class attribute assignments update the class’s dictionary, never the dictionary of a base class. A class object can be called (see above) to yield a class instance (see below). Special attributes: [`__name__`](../library/stdtypes#definition.__name__ "definition.__name__") is the class name; `__module__` is the module name in which the class was defined; [`__dict__`](../library/stdtypes#object.__dict__ "object.__dict__") is the dictionary containing the class’s namespace; [`__bases__`](../library/stdtypes#class.__bases__ "class.__bases__") is a tuple containing the base classes, in the order of their occurrence in the base class list; `__doc__` is the class’s documentation string, or `None` if undefined; `__annotations__` (optional) is a dictionary containing [variable annotations](../glossary#term-variable-annotation) collected during class body execution. Class instances A class instance is created by calling a class object (see above). A class instance has a namespace implemented as a dictionary which is the first place in which attribute references are searched. When an attribute is not found there, and the instance’s class has an attribute by that name, the search continues with the class attributes. If a class attribute is found that is a user-defined function object, it is transformed into an instance method object whose `__self__` attribute is the instance. Static method and class method objects are also transformed; see above under “Classes”. See section [Implementing Descriptors](#descriptors) for another way in which attributes of a class retrieved via its instances may differ from the objects actually stored in the class’s [`__dict__`](../library/stdtypes#object.__dict__ "object.__dict__"). If no class attribute is found, and the object’s class has a [`__getattr__()`](#object.__getattr__ "object.__getattr__") method, that is called to satisfy the lookup. Attribute assignments and deletions update the instance’s dictionary, never a class’s dictionary. If the class has a [`__setattr__()`](#object.__setattr__ "object.__setattr__") or [`__delattr__()`](#object.__delattr__ "object.__delattr__") method, this is called instead of updating the instance dictionary directly. Class instances can pretend to be numbers, sequences, or mappings if they have methods with certain special names. See section [Special method names](#specialnames). Special attributes: [`__dict__`](../library/stdtypes#object.__dict__ "object.__dict__") is the attribute dictionary; [`__class__`](../library/stdtypes#instance.__class__ "instance.__class__") is the instance’s class. I/O objects (also known as file objects) A [file object](../glossary#term-file-object) represents an open file. Various shortcuts are available to create file objects: the [`open()`](../library/functions#open "open") built-in function, and also [`os.popen()`](../library/os#os.popen "os.popen"), [`os.fdopen()`](../library/os#os.fdopen "os.fdopen"), and the [`makefile()`](../library/socket#socket.socket.makefile "socket.socket.makefile") method of socket objects (and perhaps by other functions or methods provided by extension modules). The objects `sys.stdin`, `sys.stdout` and `sys.stderr` are initialized to file objects corresponding to the interpreter’s standard input, output and error streams; they are all open in text mode and therefore follow the interface defined by the [`io.TextIOBase`](../library/io#io.TextIOBase "io.TextIOBase") abstract class. Internal types A few types used internally by the interpreter are exposed to the user. Their definitions may change with future versions of the interpreter, but they are mentioned here for completeness. Code objects Code objects represent *byte-compiled* executable Python code, or [bytecode](../glossary#term-bytecode). The difference between a code object and a function object is that the function object contains an explicit reference to the function’s globals (the module in which it was defined), while a code object contains no context; also the default argument values are stored in the function object, not in the code object (because they represent values calculated at run-time). Unlike function objects, code objects are immutable and contain no references (directly or indirectly) to mutable objects. Special read-only attributes: `co_name` gives the function name; `co_argcount` is the total number of positional arguments (including positional-only arguments and arguments with default values); `co_posonlyargcount` is the number of positional-only arguments (including arguments with default values); `co_kwonlyargcount` is the number of keyword-only arguments (including arguments with default values); `co_nlocals` is the number of local variables used by the function (including arguments); `co_varnames` is a tuple containing the names of the local variables (starting with the argument names); `co_cellvars` is a tuple containing the names of local variables that are referenced by nested functions; `co_freevars` is a tuple containing the names of free variables; `co_code` is a string representing the sequence of bytecode instructions; `co_consts` is a tuple containing the literals used by the bytecode; `co_names` is a tuple containing the names used by the bytecode; `co_filename` is the filename from which the code was compiled; `co_firstlineno` is the first line number of the function; `co_lnotab` is a string encoding the mapping from bytecode offsets to line numbers (for details see the source code of the interpreter); `co_stacksize` is the required stack size; `co_flags` is an integer encoding a number of flags for the interpreter. The following flag bits are defined for `co_flags`: bit `0x04` is set if the function uses the `*arguments` syntax to accept an arbitrary number of positional arguments; bit `0x08` is set if the function uses the `**keywords` syntax to accept arbitrary keyword arguments; bit `0x20` is set if the function is a generator. Future feature declarations (`from __future__ import division`) also use bits in `co_flags` to indicate whether a code object was compiled with a particular feature enabled: bit `0x2000` is set if the function was compiled with future division enabled; bits `0x10` and `0x1000` were used in earlier versions of Python. Other bits in `co_flags` are reserved for internal use. If a code object represents a function, the first item in `co_consts` is the documentation string of the function, or `None` if undefined. Frame objects Frame objects represent execution frames. They may occur in traceback objects (see below), and are also passed to registered trace functions. Special read-only attributes: `f_back` is to the previous stack frame (towards the caller), or `None` if this is the bottom stack frame; `f_code` is the code object being executed in this frame; `f_locals` is the dictionary used to look up local variables; `f_globals` is used for global variables; `f_builtins` is used for built-in (intrinsic) names; `f_lasti` gives the precise instruction (this is an index into the bytecode string of the code object). Accessing `f_code` raises an [auditing event](../library/sys#auditing) `object.__getattr__` with arguments `obj` and `"f_code"`. Special writable attributes: `f_trace`, if not `None`, is a function called for various events during code execution (this is used by the debugger). Normally an event is triggered for each new source line - this can be disabled by setting `f_trace_lines` to [`False`](../library/constants#False "False"). Implementations *may* allow per-opcode events to be requested by setting `f_trace_opcodes` to [`True`](../library/constants#True "True"). Note that this may lead to undefined interpreter behaviour if exceptions raised by the trace function escape to the function being traced. `f_lineno` is the current line number of the frame — writing to this from within a trace function jumps to the given line (only for the bottom-most frame). A debugger can implement a Jump command (aka Set Next Statement) by writing to f\_lineno. Frame objects support one method: `frame.clear()` This method clears all references to local variables held by the frame. Also, if the frame belonged to a generator, the generator is finalized. This helps break reference cycles involving frame objects (for example when catching an exception and storing its traceback for later use). [`RuntimeError`](../library/exceptions#RuntimeError "RuntimeError") is raised if the frame is currently executing. New in version 3.4. Traceback objects Traceback objects represent a stack trace of an exception. A traceback object is implicitly created when an exception occurs, and may also be explicitly created by calling [`types.TracebackType`](../library/types#types.TracebackType "types.TracebackType"). For implicitly created tracebacks, when the search for an exception handler unwinds the execution stack, at each unwound level a traceback object is inserted in front of the current traceback. When an exception handler is entered, the stack trace is made available to the program. (See section [The try statement](compound_stmts#try).) It is accessible as the third item of the tuple returned by `sys.exc_info()`, and as the `__traceback__` attribute of the caught exception. When the program contains no suitable handler, the stack trace is written (nicely formatted) to the standard error stream; if the interpreter is interactive, it is also made available to the user as `sys.last_traceback`. For explicitly created tracebacks, it is up to the creator of the traceback to determine how the `tb_next` attributes should be linked to form a full stack trace. Special read-only attributes: `tb_frame` points to the execution frame of the current level; `tb_lineno` gives the line number where the exception occurred; `tb_lasti` indicates the precise instruction. The line number and last instruction in the traceback may differ from the line number of its frame object if the exception occurred in a [`try`](compound_stmts#try) statement with no matching except clause or with a finally clause. Accessing `tb_frame` raises an [auditing event](../library/sys#auditing) `object.__getattr__` with arguments `obj` and `"tb_frame"`. Special writable attribute: `tb_next` is the next level in the stack trace (towards the frame where the exception occurred), or `None` if there is no next level. Changed in version 3.7: Traceback objects can now be explicitly instantiated from Python code, and the `tb_next` attribute of existing instances can be updated. Slice objects Slice objects are used to represent slices for [`__getitem__()`](#object.__getitem__ "object.__getitem__") methods. They are also created by the built-in [`slice()`](../library/functions#slice "slice") function. Special read-only attributes: `start` is the lower bound; `stop` is the upper bound; `step` is the step value; each is `None` if omitted. These attributes can have any type. Slice objects support one method: `slice.indices(self, length)` This method takes a single integer argument *length* and computes information about the slice that the slice object would describe if applied to a sequence of *length* items. It returns a tuple of three integers; respectively these are the *start* and *stop* indices and the *step* or stride length of the slice. Missing or out-of-bounds indices are handled in a manner consistent with regular slices. Static method objects Static method objects provide a way of defeating the transformation of function objects to method objects described above. A static method object is a wrapper around any other object, usually a user-defined method object. When a static method object is retrieved from a class or a class instance, the object actually returned is the wrapped object, which is not subject to any further transformation. Static method objects are not themselves callable, although the objects they wrap usually are. Static method objects are created by the built-in [`staticmethod()`](../library/functions#staticmethod "staticmethod") constructor. Class method objects A class method object, like a static method object, is a wrapper around another object that alters the way in which that object is retrieved from classes and class instances. The behaviour of class method objects upon such retrieval is described above, under “User-defined methods”. Class method objects are created by the built-in [`classmethod()`](../library/functions#classmethod "classmethod") constructor. 3.3. Special method names -------------------------- A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. This is Python’s approach to *operator overloading*, allowing classes to define their own behavior with respect to language operators. For instance, if a class defines a method named [`__getitem__()`](#object.__getitem__ "object.__getitem__"), and `x` is an instance of this class, then `x[i]` is roughly equivalent to `type(x).__getitem__(x, i)`. Except where mentioned, attempts to execute an operation raise an exception when no appropriate method is defined (typically [`AttributeError`](../library/exceptions#AttributeError "AttributeError") or [`TypeError`](../library/exceptions#TypeError "TypeError")). Setting a special method to `None` indicates that the corresponding operation is not available. For example, if a class sets [`__iter__()`](#object.__iter__ "object.__iter__") to `None`, the class is not iterable, so calling [`iter()`](../library/functions#iter "iter") on its instances will raise a [`TypeError`](../library/exceptions#TypeError "TypeError") (without falling back to [`__getitem__()`](#object.__getitem__ "object.__getitem__")). [2](#id9) When implementing a class that emulates any built-in type, it is important that the emulation only be implemented to the degree that it makes sense for the object being modelled. For example, some sequences may work well with retrieval of individual elements, but extracting a slice may not make sense. (One example of this is the `NodeList` interface in the W3C’s Document Object Model.) ### 3.3.1. Basic customization `object.__new__(cls[, ...])` Called to create a new instance of class *cls*. [`__new__()`](#object.__new__ "object.__new__") is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. The remaining arguments are those passed to the object constructor expression (the call to the class). The return value of [`__new__()`](#object.__new__ "object.__new__") should be the new object instance (usually an instance of *cls*). Typical implementations create a new instance of the class by invoking the superclass’s [`__new__()`](#object.__new__ "object.__new__") method using `super().__new__(cls[, ...])` with appropriate arguments and then modifying the newly-created instance as necessary before returning it. If [`__new__()`](#object.__new__ "object.__new__") is invoked during object construction and it returns an instance of *cls*, then the new instance’s [`__init__()`](#object.__init__ "object.__init__") method will be invoked like `__init__(self[, ...])`, where *self* is the new instance and the remaining arguments are the same as were passed to the object constructor. If [`__new__()`](#object.__new__ "object.__new__") does not return an instance of *cls*, then the new instance’s [`__init__()`](#object.__init__ "object.__init__") method will not be invoked. [`__new__()`](#object.__new__ "object.__new__") is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation. `object.__init__(self[, ...])` Called after the instance has been created (by [`__new__()`](#object.__new__ "object.__new__")), but before it is returned to the caller. The arguments are those passed to the class constructor expression. If a base class has an [`__init__()`](#object.__init__ "object.__init__") method, the derived class’s [`__init__()`](#object.__init__ "object.__init__") method, if any, must explicitly call it to ensure proper initialization of the base class part of the instance; for example: `super().__init__([args...])`. Because [`__new__()`](#object.__new__ "object.__new__") and [`__init__()`](#object.__init__ "object.__init__") work together in constructing objects ([`__new__()`](#object.__new__ "object.__new__") to create it, and [`__init__()`](#object.__init__ "object.__init__") to customize it), no non-`None` value may be returned by [`__init__()`](#object.__init__ "object.__init__"); doing so will cause a [`TypeError`](../library/exceptions#TypeError "TypeError") to be raised at runtime. `object.__del__(self)` Called when the instance is about to be destroyed. This is also called a finalizer or (improperly) a destructor. If a base class has a [`__del__()`](#object.__del__ "object.__del__") method, the derived class’s [`__del__()`](#object.__del__ "object.__del__") method, if any, must explicitly call it to ensure proper deletion of the base class part of the instance. It is possible (though not recommended!) for the [`__del__()`](#object.__del__ "object.__del__") method to postpone destruction of the instance by creating a new reference to it. This is called object *resurrection*. It is implementation-dependent whether [`__del__()`](#object.__del__ "object.__del__") is called a second time when a resurrected object is about to be destroyed; the current [CPython](../glossary#term-cpython) implementation only calls it once. It is not guaranteed that [`__del__()`](#object.__del__ "object.__del__") methods are called for objects that still exist when the interpreter exits. Note `del x` doesn’t directly call `x.__del__()` — the former decrements the reference count for `x` by one, and the latter is only called when `x`’s reference count reaches zero. **CPython implementation detail:** It is possible for a reference cycle to prevent the reference count of an object from going to zero. In this case, the cycle will be later detected and deleted by the [cyclic garbage collector](../glossary#term-garbage-collection). A common cause of reference cycles is when an exception has been caught in a local variable. The frame’s locals then reference the exception, which references its own traceback, which references the locals of all frames caught in the traceback. See also Documentation for the [`gc`](../library/gc#module-gc "gc: Interface to the cycle-detecting garbage collector.") module. Warning Due to the precarious circumstances under which [`__del__()`](#object.__del__ "object.__del__") methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to `sys.stderr` instead. In particular: * [`__del__()`](#object.__del__ "object.__del__") can be invoked when arbitrary code is being executed, including from any arbitrary thread. If [`__del__()`](#object.__del__ "object.__del__") needs to take a lock or invoke any other blocking resource, it may deadlock as the resource may already be taken by the code that gets interrupted to execute [`__del__()`](#object.__del__ "object.__del__"). * [`__del__()`](#object.__del__ "object.__del__") can be executed during interpreter shutdown. As a consequence, the global variables it needs to access (including other modules) may already have been deleted or set to `None`. Python guarantees that globals whose name begins with a single underscore are deleted from their module before other globals are deleted; if no other references to such globals exist, this may help in assuring that imported modules are still available at the time when the [`__del__()`](#object.__del__ "object.__del__") method is called. `object.__repr__(self)` Called by the [`repr()`](../library/functions#repr "repr") built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form `<...some useful description...>` should be returned. The return value must be a string object. If a class defines [`__repr__()`](#object.__repr__ "object.__repr__") but not [`__str__()`](#object.__str__ "object.__str__"), then [`__repr__()`](#object.__repr__ "object.__repr__") is also used when an “informal” string representation of instances of that class is required. This is typically used for debugging, so it is important that the representation is information-rich and unambiguous. `object.__str__(self)` Called by [`str(object)`](../library/stdtypes#str "str") and the built-in functions [`format()`](../library/functions#format "format") and [`print()`](../library/functions#print "print") to compute the “informal” or nicely printable string representation of an object. The return value must be a [string](../library/stdtypes#textseq) object. This method differs from [`object.__repr__()`](#object.__repr__ "object.__repr__") in that there is no expectation that [`__str__()`](#object.__str__ "object.__str__") return a valid Python expression: a more convenient or concise representation can be used. The default implementation defined by the built-in type [`object`](../library/functions#object "object") calls [`object.__repr__()`](#object.__repr__ "object.__repr__"). `object.__bytes__(self)` Called by [bytes](../library/functions#func-bytes) to compute a byte-string representation of an object. This should return a [`bytes`](../library/stdtypes#bytes "bytes") object. `object.__format__(self, format_spec)` Called by the [`format()`](../library/functions#format "format") built-in function, and by extension, evaluation of [formatted string literals](lexical_analysis#f-strings) and the [`str.format()`](../library/stdtypes#str.format "str.format") method, to produce a “formatted” string representation of an object. The *format\_spec* argument is a string that contains a description of the formatting options desired. The interpretation of the *format\_spec* argument is up to the type implementing [`__format__()`](#object.__format__ "object.__format__"), however most classes will either delegate formatting to one of the built-in types, or use a similar formatting option syntax. See [Format Specification Mini-Language](../library/string#formatspec) for a description of the standard formatting syntax. The return value must be a string object. Changed in version 3.4: The \_\_format\_\_ method of `object` itself raises a [`TypeError`](../library/exceptions#TypeError "TypeError") if passed any non-empty string. Changed in version 3.7: `object.__format__(x, '')` is now equivalent to `str(x)` rather than `format(str(x), '')`. `object.__lt__(self, other)` `object.__le__(self, other)` `object.__eq__(self, other)` `object.__ne__(self, other)` `object.__gt__(self, other)` `object.__ge__(self, other)` These are the so-called “rich comparison” methods. The correspondence between operator symbols and method names is as follows: `x<y` calls `x.__lt__(y)`, `x<=y` calls `x.__le__(y)`, `x==y` calls `x.__eq__(y)`, `x!=y` calls `x.__ne__(y)`, `x>y` calls `x.__gt__(y)`, and `x>=y` calls `x.__ge__(y)`. A rich comparison method may return the singleton `NotImplemented` if it does not implement the operation for a given pair of arguments. By convention, `False` and `True` are returned for a successful comparison. However, these methods can return any value, so if the comparison operator is used in a Boolean context (e.g., in the condition of an `if` statement), Python will call [`bool()`](../library/functions#bool "bool") on the value to determine if the result is true or false. By default, `object` implements [`__eq__()`](#object.__eq__ "object.__eq__") by using `is`, returning `NotImplemented` in the case of a false comparison: `True if x is y else NotImplemented`. For [`__ne__()`](#object.__ne__ "object.__ne__"), by default it delegates to [`__eq__()`](#object.__eq__ "object.__eq__") and inverts the result unless it is `NotImplemented`. There are no other implied relationships among the comparison operators or default implementations; for example, the truth of `(x<y or x==y)` does not imply `x<=y`. To automatically generate ordering operations from a single root operation, see [`functools.total_ordering()`](../library/functools#functools.total_ordering "functools.total_ordering"). See the paragraph on [`__hash__()`](#object.__hash__ "object.__hash__") for some important notes on creating [hashable](../glossary#term-hashable) objects which support custom comparison operations and are usable as dictionary keys. There are no swapped-argument versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather, [`__lt__()`](#object.__lt__ "object.__lt__") and [`__gt__()`](#object.__gt__ "object.__gt__") are each other’s reflection, [`__le__()`](#object.__le__ "object.__le__") and [`__ge__()`](#object.__ge__ "object.__ge__") are each other’s reflection, and [`__eq__()`](#object.__eq__ "object.__eq__") and [`__ne__()`](#object.__ne__ "object.__ne__") are their own reflection. If the operands are of different types, and right operand’s type is a direct or indirect subclass of the left operand’s type, the reflected method of the right operand has priority, otherwise the left operand’s method has priority. Virtual subclassing is not considered. `object.__hash__(self)` Called by built-in function [`hash()`](../library/functions#hash "hash") and for operations on members of hashed collections including [`set`](../library/stdtypes#set "set"), [`frozenset`](../library/stdtypes#frozenset "frozenset"), and [`dict`](../library/stdtypes#dict "dict"). The `__hash__()` method should return an integer. The only required property is that objects which compare equal have the same hash value; it is advised to mix together the hash values of the components of the object that also play a part in comparison of objects by packing them into a tuple and hashing the tuple. Example: ``` def __hash__(self): return hash((self.name, self.nick, self.color)) ``` Note [`hash()`](../library/functions#hash "hash") truncates the value returned from an object’s custom [`__hash__()`](#object.__hash__ "object.__hash__") method to the size of a [`Py_ssize_t`](../c-api/intro#c.Py_ssize_t "Py_ssize_t"). This is typically 8 bytes on 64-bit builds and 4 bytes on 32-bit builds. If an object’s [`__hash__()`](#object.__hash__ "object.__hash__") must interoperate on builds of different bit sizes, be sure to check the width on all supported builds. An easy way to do this is with `python -c "import sys; print(sys.hash_info.width)"`. If a class does not define an [`__eq__()`](#object.__eq__ "object.__eq__") method it should not define a [`__hash__()`](#object.__hash__ "object.__hash__") operation either; if it defines [`__eq__()`](#object.__eq__ "object.__eq__") but not [`__hash__()`](#object.__hash__ "object.__hash__"), its instances will not be usable as items in hashable collections. If a class defines mutable objects and implements an [`__eq__()`](#object.__eq__ "object.__eq__") method, it should not implement [`__hash__()`](#object.__hash__ "object.__hash__"), since the implementation of hashable collections requires that a key’s hash value is immutable (if the object’s hash value changes, it will be in the wrong hash bucket). User-defined classes have [`__eq__()`](#object.__eq__ "object.__eq__") and [`__hash__()`](#object.__hash__ "object.__hash__") methods by default; with them, all objects compare unequal (except with themselves) and `x.__hash__()` returns an appropriate value such that `x == y` implies both that `x is y` and `hash(x) == hash(y)`. A class that overrides [`__eq__()`](#object.__eq__ "object.__eq__") and does not define [`__hash__()`](#object.__hash__ "object.__hash__") will have its [`__hash__()`](#object.__hash__ "object.__hash__") implicitly set to `None`. When the [`__hash__()`](#object.__hash__ "object.__hash__") method of a class is `None`, instances of the class will raise an appropriate [`TypeError`](../library/exceptions#TypeError "TypeError") when a program attempts to retrieve their hash value, and will also be correctly identified as unhashable when checking `isinstance(obj, collections.abc.Hashable)`. If a class that overrides [`__eq__()`](#object.__eq__ "object.__eq__") needs to retain the implementation of [`__hash__()`](#object.__hash__ "object.__hash__") from a parent class, the interpreter must be told this explicitly by setting `__hash__ = <ParentClass>.__hash__`. If a class that does not override [`__eq__()`](#object.__eq__ "object.__eq__") wishes to suppress hash support, it should include `__hash__ = None` in the class definition. A class which defines its own [`__hash__()`](#object.__hash__ "object.__hash__") that explicitly raises a [`TypeError`](../library/exceptions#TypeError "TypeError") would be incorrectly identified as hashable by an `isinstance(obj, collections.abc.Hashable)` call. Note By default, the [`__hash__()`](#object.__hash__ "object.__hash__") values of str and bytes objects are “salted” with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python. This is intended to provide protection against a denial-of-service caused by carefully-chosen inputs that exploit the worst case performance of a dict insertion, O(n2) complexity. See <http://www.ocert.org/advisories/ocert-2011-003.html> for details. Changing hash values affects the iteration order of sets. Python has never made guarantees about this ordering (and it typically varies between 32-bit and 64-bit builds). See also [`PYTHONHASHSEED`](../using/cmdline#envvar-PYTHONHASHSEED). Changed in version 3.3: Hash randomization is enabled by default. `object.__bool__(self)` Called to implement truth value testing and the built-in operation `bool()`; should return `False` or `True`. When this method is not defined, [`__len__()`](#object.__len__ "object.__len__") is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither [`__len__()`](#object.__len__ "object.__len__") nor [`__bool__()`](#object.__bool__ "object.__bool__"), all its instances are considered true. ### 3.3.2. Customizing attribute access The following methods can be defined to customize the meaning of attribute access (use of, assignment to, or deletion of `x.name`) for class instances. `object.__getattr__(self, name)` Called when the default attribute access fails with an [`AttributeError`](../library/exceptions#AttributeError "AttributeError") (either [`__getattribute__()`](#object.__getattribute__ "object.__getattribute__") raises an [`AttributeError`](../library/exceptions#AttributeError "AttributeError") because *name* is not an instance attribute or an attribute in the class tree for `self`; or [`__get__()`](#object.__get__ "object.__get__") of a *name* property raises [`AttributeError`](../library/exceptions#AttributeError "AttributeError")). This method should either return the (computed) attribute value or raise an [`AttributeError`](../library/exceptions#AttributeError "AttributeError") exception. Note that if the attribute is found through the normal mechanism, [`__getattr__()`](#object.__getattr__ "object.__getattr__") is not called. (This is an intentional asymmetry between [`__getattr__()`](#object.__getattr__ "object.__getattr__") and [`__setattr__()`](#object.__setattr__ "object.__setattr__").) This is done both for efficiency reasons and because otherwise [`__getattr__()`](#object.__getattr__ "object.__getattr__") would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the [`__getattribute__()`](#object.__getattribute__ "object.__getattribute__") method below for a way to actually get total control over attribute access. `object.__getattribute__(self, name)` Called unconditionally to implement attribute accesses for instances of the class. If the class also defines [`__getattr__()`](#object.__getattr__ "object.__getattr__"), the latter will not be called unless [`__getattribute__()`](#object.__getattribute__ "object.__getattribute__") either calls it explicitly or raises an [`AttributeError`](../library/exceptions#AttributeError "AttributeError"). This method should return the (computed) attribute value or raise an [`AttributeError`](../library/exceptions#AttributeError "AttributeError") exception. In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, `object.__getattribute__(self, name)`. Note This method may still be bypassed when looking up special methods as the result of implicit invocation via language syntax or built-in functions. See [Special method lookup](#special-lookup). For certain sensitive attribute accesses, raises an [auditing event](../library/sys#auditing) `object.__getattr__` with arguments `obj` and `name`. `object.__setattr__(self, name, value)` Called when an attribute assignment is attempted. This is called instead of the normal mechanism (i.e. store the value in the instance dictionary). *name* is the attribute name, *value* is the value to be assigned to it. If [`__setattr__()`](#object.__setattr__ "object.__setattr__") wants to assign to an instance attribute, it should call the base class method with the same name, for example, `object.__setattr__(self, name, value)`. For certain sensitive attribute assignments, raises an [auditing event](../library/sys#auditing) `object.__setattr__` with arguments `obj`, `name`, `value`. `object.__delattr__(self, name)` Like [`__setattr__()`](#object.__setattr__ "object.__setattr__") but for attribute deletion instead of assignment. This should only be implemented if `del obj.name` is meaningful for the object. For certain sensitive attribute deletions, raises an [auditing event](../library/sys#auditing) `object.__delattr__` with arguments `obj` and `name`. `object.__dir__(self)` Called when [`dir()`](../library/functions#dir "dir") is called on the object. A sequence must be returned. [`dir()`](../library/functions#dir "dir") converts the returned sequence to a list and sorts it. #### 3.3.2.1. Customizing module attribute access Special names `__getattr__` and `__dir__` can be also used to customize access to module attributes. The `__getattr__` function at the module level should accept one argument which is the name of an attribute and return the computed value or raise an [`AttributeError`](../library/exceptions#AttributeError "AttributeError"). If an attribute is not found on a module object through the normal lookup, i.e. [`object.__getattribute__()`](#object.__getattribute__ "object.__getattribute__"), then `__getattr__` is searched in the module `__dict__` before raising an [`AttributeError`](../library/exceptions#AttributeError "AttributeError"). If found, it is called with the attribute name and the result is returned. The `__dir__` function should accept no arguments, and return a sequence of strings that represents the names accessible on module. If present, this function overrides the standard [`dir()`](../library/functions#dir "dir") search on a module. For a more fine grained customization of the module behavior (setting attributes, properties, etc.), one can set the `__class__` attribute of a module object to a subclass of [`types.ModuleType`](../library/types#types.ModuleType "types.ModuleType"). For example: ``` import sys from types import ModuleType class VerboseModule(ModuleType): def __repr__(self): return f'Verbose {self.__name__}' def __setattr__(self, attr, value): print(f'Setting {attr}...') super().__setattr__(attr, value) sys.modules[__name__].__class__ = VerboseModule ``` Note Defining module `__getattr__` and setting module `__class__` only affect lookups made using the attribute access syntax – directly accessing the module globals (whether by code within the module, or via a reference to the module’s globals dictionary) is unaffected. Changed in version 3.5: `__class__` module attribute is now writable. New in version 3.7: `__getattr__` and `__dir__` module attributes. See also [**PEP 562**](https://www.python.org/dev/peps/pep-0562) - Module \_\_getattr\_\_ and \_\_dir\_\_ Describes the `__getattr__` and `__dir__` functions on modules. #### 3.3.2.2. Implementing Descriptors The following methods only apply when an instance of the class containing the method (a so-called *descriptor* class) appears in an *owner* class (the descriptor must be in either the owner’s class dictionary or in the class dictionary for one of its parents). In the examples below, “the attribute” refers to the attribute whose name is the key of the property in the owner class’ [`__dict__`](../library/stdtypes#object.__dict__ "object.__dict__"). `object.__get__(self, instance, owner=None)` Called to get the attribute of the owner class (class attribute access) or of an instance of that class (instance attribute access). The optional *owner* argument is the owner class, while *instance* is the instance that the attribute was accessed through, or `None` when the attribute is accessed through the *owner*. This method should return the computed attribute value or raise an [`AttributeError`](../library/exceptions#AttributeError "AttributeError") exception. [**PEP 252**](https://www.python.org/dev/peps/pep-0252) specifies that [`__get__()`](#object.__get__ "object.__get__") is callable with one or two arguments. Python’s own built-in descriptors support this specification; however, it is likely that some third-party tools have descriptors that require both arguments. Python’s own [`__getattribute__()`](#object.__getattribute__ "object.__getattribute__") implementation always passes in both arguments whether they are required or not. `object.__set__(self, instance, value)` Called to set the attribute on an instance *instance* of the owner class to a new value, *value*. Note, adding [`__set__()`](#object.__set__ "object.__set__") or [`__delete__()`](#object.__delete__ "object.__delete__") changes the kind of descriptor to a “data descriptor”. See [Invoking Descriptors](#descriptor-invocation) for more details. `object.__delete__(self, instance)` Called to delete the attribute on an instance *instance* of the owner class. `object.__set_name__(self, owner, name)` Called at the time the owning class *owner* is created. The descriptor has been assigned to *name*. Note [`__set_name__()`](#object.__set_name__ "object.__set_name__") is only called implicitly as part of the [`type`](../library/functions#type "type") constructor, so it will need to be called explicitly with the appropriate parameters when a descriptor is added to a class after initial creation: ``` class A: pass descr = custom_descriptor() A.attr = descr descr.__set_name__(A, 'attr') ``` See [Creating the class object](#class-object-creation) for more details. New in version 3.6. The attribute `__objclass__` is interpreted by the [`inspect`](../library/inspect#module-inspect "inspect: Extract information and source code from live objects.") module as specifying the class where this object was defined (setting this appropriately can assist in runtime introspection of dynamic class attributes). For callables, it may indicate that an instance of the given type (or a subclass) is expected or required as the first positional argument (for example, CPython sets this attribute for unbound methods that are implemented in C). #### 3.3.2.3. Invoking Descriptors In general, a descriptor is an object attribute with “binding behavior”, one whose attribute access has been overridden by methods in the descriptor protocol: [`__get__()`](#object.__get__ "object.__get__"), [`__set__()`](#object.__set__ "object.__set__"), and [`__delete__()`](#object.__delete__ "object.__delete__"). If any of those methods are defined for an object, it is said to be a descriptor. The default behavior for attribute access is to get, set, or delete the attribute from an object’s dictionary. For instance, `a.x` has a lookup chain starting with `a.__dict__['x']`, then `type(a).__dict__['x']`, and continuing through the base classes of `type(a)` excluding metaclasses. However, if the looked-up value is an object defining one of the descriptor methods, then Python may override the default behavior and invoke the descriptor method instead. Where this occurs in the precedence chain depends on which descriptor methods were defined and how they were called. The starting point for descriptor invocation is a binding, `a.x`. How the arguments are assembled depends on `a`: Direct Call The simplest and least common call is when user code directly invokes a descriptor method: `x.__get__(a)`. Instance Binding If binding to an object instance, `a.x` is transformed into the call: `type(a).__dict__['x'].__get__(a, type(a))`. Class Binding If binding to a class, `A.x` is transformed into the call: `A.__dict__['x'].__get__(None, A)`. Super Binding If `a` is an instance of [`super`](../library/functions#super "super"), then the binding `super(B, obj).m()` searches `obj.__class__.__mro__` for the base class `A` immediately following `B` and then invokes the descriptor with the call: `A.__dict__['m'].__get__(obj, obj.__class__)`. For instance bindings, the precedence of descriptor invocation depends on which descriptor methods are defined. A descriptor can define any combination of [`__get__()`](#object.__get__ "object.__get__"), [`__set__()`](#object.__set__ "object.__set__") and [`__delete__()`](#object.__delete__ "object.__delete__"). If it does not define [`__get__()`](#object.__get__ "object.__get__"), then accessing the attribute will return the descriptor object itself unless there is a value in the object’s instance dictionary. If the descriptor defines [`__set__()`](#object.__set__ "object.__set__") and/or [`__delete__()`](#object.__delete__ "object.__delete__"), it is a data descriptor; if it defines neither, it is a non-data descriptor. Normally, data descriptors define both [`__get__()`](#object.__get__ "object.__get__") and [`__set__()`](#object.__set__ "object.__set__"), while non-data descriptors have just the [`__get__()`](#object.__get__ "object.__get__") method. Data descriptors with [`__get__()`](#object.__get__ "object.__get__") and [`__set__()`](#object.__set__ "object.__set__") (and/or [`__delete__()`](#object.__delete__ "object.__delete__")) defined always override a redefinition in an instance dictionary. In contrast, non-data descriptors can be overridden by instances. Python methods (including those decorated with [`@staticmethod`](../library/functions#staticmethod "staticmethod") and [`@classmethod`](../library/functions#classmethod "classmethod")) are implemented as non-data descriptors. Accordingly, instances can redefine and override methods. This allows individual instances to acquire behaviors that differ from other instances of the same class. The [`property()`](../library/functions#property "property") function is implemented as a data descriptor. Accordingly, instances cannot override the behavior of a property. #### 3.3.2.4. \_\_slots\_\_ *\_\_slots\_\_* allow us to explicitly declare data members (like properties) and deny the creation of [`__dict__`](../library/stdtypes#object.__dict__ "object.__dict__") and *\_\_weakref\_\_* (unless explicitly declared in *\_\_slots\_\_* or available in a parent.) The space saved over using [`__dict__`](../library/stdtypes#object.__dict__ "object.__dict__") can be significant. Attribute lookup speed can be significantly improved as well. `object.__slots__` This class variable can be assigned a string, iterable, or sequence of strings with variable names used by instances. *\_\_slots\_\_* reserves space for the declared variables and prevents the automatic creation of [`__dict__`](../library/stdtypes#object.__dict__ "object.__dict__") and *\_\_weakref\_\_* for each instance. ##### 3.3.2.4.1. Notes on using *\_\_slots\_\_* * When inheriting from a class without *\_\_slots\_\_*, the [`__dict__`](../library/stdtypes#object.__dict__ "object.__dict__") and *\_\_weakref\_\_* attribute of the instances will always be accessible. * Without a [`__dict__`](../library/stdtypes#object.__dict__ "object.__dict__") variable, instances cannot be assigned new variables not listed in the *\_\_slots\_\_* definition. Attempts to assign to an unlisted variable name raises [`AttributeError`](../library/exceptions#AttributeError "AttributeError"). If dynamic assignment of new variables is desired, then add `'__dict__'` to the sequence of strings in the *\_\_slots\_\_* declaration. * Without a *\_\_weakref\_\_* variable for each instance, classes defining *\_\_slots\_\_* do not support [`weak references`](../library/weakref#module-weakref "weakref: Support for weak references and weak dictionaries.") to its instances. If weak reference support is needed, then add `'__weakref__'` to the sequence of strings in the *\_\_slots\_\_* declaration. * *\_\_slots\_\_* are implemented at the class level by creating [descriptors](#descriptors) for each variable name. As a result, class attributes cannot be used to set default values for instance variables defined by *\_\_slots\_\_*; otherwise, the class attribute would overwrite the descriptor assignment. * The action of a *\_\_slots\_\_* declaration is not limited to the class where it is defined. *\_\_slots\_\_* declared in parents are available in child classes. However, child subclasses will get a [`__dict__`](../library/stdtypes#object.__dict__ "object.__dict__") and *\_\_weakref\_\_* unless they also define *\_\_slots\_\_* (which should only contain names of any *additional* slots). * If a class defines a slot also defined in a base class, the instance variable defined by the base class slot is inaccessible (except by retrieving its descriptor directly from the base class). This renders the meaning of the program undefined. In the future, a check may be added to prevent this. * Nonempty *\_\_slots\_\_* does not work for classes derived from “variable-length” built-in types such as [`int`](../library/functions#int "int"), [`bytes`](../library/stdtypes#bytes "bytes") and [`tuple`](../library/stdtypes#tuple "tuple"). * Any non-string [iterable](../glossary#term-iterable) may be assigned to *\_\_slots\_\_*. * If a [`dictionary`](../library/stdtypes#dict "dict") is used to assign *\_\_slots\_\_*, the dictionary keys will be used as the slot names. The values of the dictionary can be used to provide per-attribute docstrings that will be recognised by [`inspect.getdoc()`](../library/inspect#inspect.getdoc "inspect.getdoc") and displayed in the output of [`help()`](../library/functions#help "help"). * [`__class__`](../library/stdtypes#instance.__class__ "instance.__class__") assignment works only if both classes have the same *\_\_slots\_\_*. * [Multiple inheritance](../tutorial/classes#tut-multiple) with multiple slotted parent classes can be used, but only one parent is allowed to have attributes created by slots (the other bases must have empty slot layouts) - violations raise [`TypeError`](../library/exceptions#TypeError "TypeError"). * If an [iterator](../glossary#term-iterator) is used for *\_\_slots\_\_* then a [descriptor](../glossary#term-descriptor) is created for each of the iterator’s values. However, the *\_\_slots\_\_* attribute will be an empty iterator. ### 3.3.3. Customizing class creation Whenever a class inherits from another class, [`__init_subclass__()`](#object.__init_subclass__ "object.__init_subclass__") is called on the parent class. This way, it is possible to write classes which change the behavior of subclasses. This is closely related to class decorators, but where class decorators only affect the specific class they’re applied to, `__init_subclass__` solely applies to future subclasses of the class defining the method. `classmethod object.__init_subclass__(cls)` This method is called whenever the containing class is subclassed. *cls* is then the new subclass. If defined as a normal instance method, this method is implicitly converted to a class method. Keyword arguments which are given to a new class are passed to the parent’s class `__init_subclass__`. For compatibility with other classes using `__init_subclass__`, one should take out the needed keyword arguments and pass the others over to the base class, as in: ``` class Philosopher: def __init_subclass__(cls, /, default_name, **kwargs): super().__init_subclass__(**kwargs) cls.default_name = default_name class AustralianPhilosopher(Philosopher, default_name="Bruce"): pass ``` The default implementation `object.__init_subclass__` does nothing, but raises an error if it is called with any arguments. Note The metaclass hint `metaclass` is consumed by the rest of the type machinery, and is never passed to `__init_subclass__` implementations. The actual metaclass (rather than the explicit hint) can be accessed as `type(cls)`. New in version 3.6. #### 3.3.3.1. Metaclasses By default, classes are constructed using [`type()`](../library/functions#type "type"). The class body is executed in a new namespace and the class name is bound locally to the result of `type(name, bases, namespace)`. The class creation process can be customized by passing the `metaclass` keyword argument in the class definition line, or by inheriting from an existing class that included such an argument. In the following example, both `MyClass` and `MySubclass` are instances of `Meta`: ``` class Meta(type): pass class MyClass(metaclass=Meta): pass class MySubclass(MyClass): pass ``` Any other keyword arguments that are specified in the class definition are passed through to all metaclass operations described below. When a class definition is executed, the following steps occur: * MRO entries are resolved; * the appropriate metaclass is determined; * the class namespace is prepared; * the class body is executed; * the class object is created. #### 3.3.3.2. Resolving MRO entries If a base that appears in class definition is not an instance of [`type`](../library/functions#type "type"), then an `__mro_entries__` method is searched on it. If found, it is called with the original bases tuple. This method must return a tuple of classes that will be used instead of this base. The tuple may be empty, in such case the original base is ignored. See also [**PEP 560**](https://www.python.org/dev/peps/pep-0560) - Core support for typing module and generic types #### 3.3.3.3. Determining the appropriate metaclass The appropriate metaclass for a class definition is determined as follows: * if no bases and no explicit metaclass are given, then [`type()`](../library/functions#type "type") is used; * if an explicit metaclass is given and it is *not* an instance of [`type()`](../library/functions#type "type"), then it is used directly as the metaclass; * if an instance of [`type()`](../library/functions#type "type") is given as the explicit metaclass, or bases are defined, then the most derived metaclass is used. The most derived metaclass is selected from the explicitly specified metaclass (if any) and the metaclasses (i.e. `type(cls)`) of all specified base classes. The most derived metaclass is one which is a subtype of *all* of these candidate metaclasses. If none of the candidate metaclasses meets that criterion, then the class definition will fail with `TypeError`. #### 3.3.3.4. Preparing the class namespace Once the appropriate metaclass has been identified, then the class namespace is prepared. If the metaclass has a `__prepare__` attribute, it is called as `namespace = metaclass.__prepare__(name, bases, **kwds)` (where the additional keyword arguments, if any, come from the class definition). The `__prepare__` method should be implemented as a [`classmethod`](../library/functions#classmethod "classmethod"). The namespace returned by `__prepare__` is passed in to `__new__`, but when the final class object is created the namespace is copied into a new `dict`. If the metaclass has no `__prepare__` attribute, then the class namespace is initialised as an empty ordered mapping. See also [**PEP 3115**](https://www.python.org/dev/peps/pep-3115) - Metaclasses in Python 3000 Introduced the `__prepare__` namespace hook #### 3.3.3.5. Executing the class body The class body is executed (approximately) as `exec(body, globals(), namespace)`. The key difference from a normal call to [`exec()`](../library/functions#exec "exec") is that lexical scoping allows the class body (including any methods) to reference names from the current and outer scopes when the class definition occurs inside a function. However, even when the class definition occurs inside the function, methods defined inside the class still cannot see names defined at the class scope. Class variables must be accessed through the first parameter of instance or class methods, or through the implicit lexically scoped `__class__` reference described in the next section. #### 3.3.3.6. Creating the class object Once the class namespace has been populated by executing the class body, the class object is created by calling `metaclass(name, bases, namespace, **kwds)` (the additional keywords passed here are the same as those passed to `__prepare__`). This class object is the one that will be referenced by the zero-argument form of [`super()`](../library/functions#super "super"). `__class__` is an implicit closure reference created by the compiler if any methods in a class body refer to either `__class__` or `super`. This allows the zero argument form of [`super()`](../library/functions#super "super") to correctly identify the class being defined based on lexical scoping, while the class or instance that was used to make the current call is identified based on the first argument passed to the method. **CPython implementation detail:** In CPython 3.6 and later, the `__class__` cell is passed to the metaclass as a `__classcell__` entry in the class namespace. If present, this must be propagated up to the `type.__new__` call in order for the class to be initialised correctly. Failing to do so will result in a [`RuntimeError`](../library/exceptions#RuntimeError "RuntimeError") in Python 3.8. When using the default metaclass [`type`](../library/functions#type "type"), or any metaclass that ultimately calls `type.__new__`, the following additional customisation steps are invoked after creating the class object: * first, `type.__new__` collects all of the descriptors in the class namespace that define a [`__set_name__()`](#object.__set_name__ "object.__set_name__") method; * second, all of these `__set_name__` methods are called with the class being defined and the assigned name of that particular descriptor; * finally, the [`__init_subclass__()`](#object.__init_subclass__ "object.__init_subclass__") hook is called on the immediate parent of the new class in its method resolution order. After the class object is created, it is passed to the class decorators included in the class definition (if any) and the resulting object is bound in the local namespace as the defined class. When a new class is created by `type.__new__`, the object provided as the namespace parameter is copied to a new ordered mapping and the original object is discarded. The new copy is wrapped in a read-only proxy, which becomes the [`__dict__`](../library/stdtypes#object.__dict__ "object.__dict__") attribute of the class object. See also [**PEP 3135**](https://www.python.org/dev/peps/pep-3135) - New super Describes the implicit `__class__` closure reference #### 3.3.3.7. Uses for metaclasses The potential uses for metaclasses are boundless. Some ideas that have been explored include enum, logging, interface checking, automatic delegation, automatic property creation, proxies, frameworks, and automatic resource locking/synchronization. ### 3.3.4. Customizing instance and subclass checks The following methods are used to override the default behavior of the [`isinstance()`](../library/functions#isinstance "isinstance") and [`issubclass()`](../library/functions#issubclass "issubclass") built-in functions. In particular, the metaclass [`abc.ABCMeta`](../library/abc#abc.ABCMeta "abc.ABCMeta") implements these methods in order to allow the addition of Abstract Base Classes (ABCs) as “virtual base classes” to any class or type (including built-in types), including other ABCs. `class.__instancecheck__(self, instance)` Return true if *instance* should be considered a (direct or indirect) instance of *class*. If defined, called to implement `isinstance(instance, class)`. `class.__subclasscheck__(self, subclass)` Return true if *subclass* should be considered a (direct or indirect) subclass of *class*. If defined, called to implement `issubclass(subclass, class)`. Note that these methods are looked up on the type (metaclass) of a class. They cannot be defined as class methods in the actual class. This is consistent with the lookup of special methods that are called on instances, only in this case the instance is itself a class. See also [**PEP 3119**](https://www.python.org/dev/peps/pep-3119) - Introducing Abstract Base Classes Includes the specification for customizing [`isinstance()`](../library/functions#isinstance "isinstance") and [`issubclass()`](../library/functions#issubclass "issubclass") behavior through [`__instancecheck__()`](#class.__instancecheck__ "class.__instancecheck__") and [`__subclasscheck__()`](#class.__subclasscheck__ "class.__subclasscheck__"), with motivation for this functionality in the context of adding Abstract Base Classes (see the [`abc`](../library/abc#module-abc "abc: Abstract base classes according to :pep:`3119`.") module) to the language. ### 3.3.5. Emulating generic types When using [type annotations](../glossary#term-annotation), it is often useful to *parameterize* a [generic type](../glossary#term-generic-type) using Python’s square-brackets notation. For example, the annotation `list[int]` might be used to signify a [`list`](../library/stdtypes#list "list") in which all the elements are of type [`int`](../library/functions#int "int"). See also [**PEP 484**](https://www.python.org/dev/peps/pep-0484) - Type Hints Introducing Python’s framework for type annotations [Generic Alias Types](../library/stdtypes#types-genericalias) Documentation for objects representing parameterized generic classes `Generics, user-defined generics and` [`typing.Generic`](../library/typing#typing.Generic "typing.Generic") Documentation on how to implement generic classes that can be parameterized at runtime and understood by static type-checkers. A class can *generally* only be parameterized if it defines the special class method `__class_getitem__()`. `classmethod object.__class_getitem__(cls, key)` Return an object representing the specialization of a generic class by type arguments found in *key*. When defined on a class, `__class_getitem__()` is automatically a class method. As such, there is no need for it to be decorated with [`@classmethod`](../library/functions#classmethod "classmethod") when it is defined. #### 3.3.5.1. The purpose of *\_\_class\_getitem\_\_* The purpose of [`__class_getitem__()`](#object.__class_getitem__ "object.__class_getitem__") is to allow runtime parameterization of standard-library generic classes in order to more easily apply [type hints](../glossary#term-type-hint) to these classes. To implement custom generic classes that can be parameterized at runtime and understood by static type-checkers, users should either inherit from a standard library class that already implements [`__class_getitem__()`](#object.__class_getitem__ "object.__class_getitem__"), or inherit from [`typing.Generic`](../library/typing#typing.Generic "typing.Generic"), which has its own implementation of `__class_getitem__()`. Custom implementations of [`__class_getitem__()`](#object.__class_getitem__ "object.__class_getitem__") on classes defined outside of the standard library may not be understood by third-party type-checkers such as mypy. Using `__class_getitem__()` on any class for purposes other than type hinting is discouraged. #### 3.3.5.2. *\_\_class\_getitem\_\_* versus *\_\_getitem\_\_* Usually, the [subscription](expressions#subscriptions) of an object using square brackets will call the [`__getitem__()`](#object.__getitem__ "object.__getitem__") instance method defined on the object’s class. However, if the object being subscribed is itself a class, the class method [`__class_getitem__()`](#object.__class_getitem__ "object.__class_getitem__") may be called instead. `__class_getitem__()` should return a [GenericAlias](../library/stdtypes#types-genericalias) object if it is properly defined. Presented with the [expression](../glossary#term-expression) `obj[x]`, the Python interpreter follows something like the following process to decide whether [`__getitem__()`](#object.__getitem__ "object.__getitem__") or [`__class_getitem__()`](#object.__class_getitem__ "object.__class_getitem__") should be called: ``` from inspect import isclass def subscribe(obj, x): """Return the result of the expression `obj[x]`""" class_of_obj = type(obj) # If the class of obj defines __getitem__, # call class_of_obj.__getitem__(obj, x) if hasattr(class_of_obj, '__getitem__'): return class_of_obj.__getitem__(obj, x) # Else, if obj is a class and defines __class_getitem__, # call obj.__class_getitem__(x) elif isclass(obj) and hasattr(obj, '__class_getitem__'): return obj.__class_getitem__(x) # Else, raise an exception else: raise TypeError( f"'{class_of_obj.__name__}' object is not subscriptable" ) ``` In Python, all classes are themselves instances of other classes. The class of a class is known as that class’s [metaclass](../glossary#term-metaclass), and most classes have the [`type`](../library/functions#type "type") class as their metaclass. [`type`](../library/functions#type "type") does not define [`__getitem__()`](#object.__getitem__ "object.__getitem__"), meaning that expressions such as `list[int]`, `dict[str, float]` and `tuple[str, bytes]` all result in [`__class_getitem__()`](#object.__class_getitem__ "object.__class_getitem__") being called: ``` >>> # list has class "type" as its metaclass, like most classes: >>> type(list) <class 'type'> >>> type(dict) == type(list) == type(tuple) == type(str) == type(bytes) True >>> # "list[int]" calls "list.__class_getitem__(int)" >>> list[int] list[int] >>> # list.__class_getitem__ returns a GenericAlias object: >>> type(list[int]) <class 'types.GenericAlias'> ``` However, if a class has a custom metaclass that defines [`__getitem__()`](#object.__getitem__ "object.__getitem__"), subscribing the class may result in different behaviour. An example of this can be found in the [`enum`](../library/enum#module-enum "enum: Implementation of an enumeration class.") module: ``` >>> from enum import Enum >>> class Menu(Enum): ... """A breakfast menu""" ... SPAM = 'spam' ... BACON = 'bacon' ... >>> # Enum classes have a custom metaclass: >>> type(Menu) <class 'enum.EnumMeta'> >>> # EnumMeta defines __getitem__, >>> # so __class_getitem__ is not called, >>> # and the result is not a GenericAlias object: >>> Menu['SPAM'] <Menu.SPAM: 'spam'> >>> type(Menu['SPAM']) <enum 'Menu'> ``` See also [**PEP 560**](https://www.python.org/dev/peps/pep-0560) - Core Support for typing module and generic types Introducing [`__class_getitem__()`](#object.__class_getitem__ "object.__class_getitem__"), and outlining when a [subscription](expressions#subscriptions) results in `__class_getitem__()` being called instead of [`__getitem__()`](#object.__getitem__ "object.__getitem__") ### 3.3.6. Emulating callable objects `object.__call__(self[, args...])` Called when the instance is “called” as a function; if this method is defined, `x(arg1, arg2, ...)` roughly translates to `type(x).__call__(x, arg1, ...)`. ### 3.3.7. Emulating container types The following methods can be defined to implement container objects. Containers usually are [sequences](../glossary#term-sequence) (such as [`lists`](../library/stdtypes#list "list") or [`tuples`](../library/stdtypes#tuple "tuple")) or [mappings](../glossary#term-mapping) (like [`dictionaries`](../library/stdtypes#dict "dict")), but can represent other containers as well. The first set of methods is used either to emulate a sequence or to emulate a mapping; the difference is that for a sequence, the allowable keys should be the integers *k* for which `0 <= k < N` where *N* is the length of the sequence, or [`slice`](../library/functions#slice "slice") objects, which define a range of items. It is also recommended that mappings provide the methods `keys()`, `values()`, `items()`, `get()`, `clear()`, `setdefault()`, `pop()`, `popitem()`, `copy()`, and `update()` behaving similar to those for Python’s standard [`dictionary`](../library/stdtypes#dict "dict") objects. The [`collections.abc`](../library/collections.abc#module-collections.abc "collections.abc: Abstract base classes for containers") module provides a [`MutableMapping`](../library/collections.abc#collections.abc.MutableMapping "collections.abc.MutableMapping") [abstract base class](../glossary#term-abstract-base-class) to help create those methods from a base set of [`__getitem__()`](#object.__getitem__ "object.__getitem__"), [`__setitem__()`](#object.__setitem__ "object.__setitem__"), [`__delitem__()`](#object.__delitem__ "object.__delitem__"), and `keys()`. Mutable sequences should provide methods `append()`, `count()`, `index()`, `extend()`, `insert()`, `pop()`, `remove()`, `reverse()` and `sort()`, like Python standard [`list`](../library/stdtypes#list "list") objects. Finally, sequence types should implement addition (meaning concatenation) and multiplication (meaning repetition) by defining the methods [`__add__()`](#object.__add__ "object.__add__"), [`__radd__()`](#object.__radd__ "object.__radd__"), [`__iadd__()`](#object.__iadd__ "object.__iadd__"), [`__mul__()`](#object.__mul__ "object.__mul__"), [`__rmul__()`](#object.__rmul__ "object.__rmul__") and [`__imul__()`](#object.__imul__ "object.__imul__") described below; they should not define other numerical operators. It is recommended that both mappings and sequences implement the [`__contains__()`](#object.__contains__ "object.__contains__") method to allow efficient use of the `in` operator; for mappings, `in` should search the mapping’s keys; for sequences, it should search through the values. It is further recommended that both mappings and sequences implement the [`__iter__()`](#object.__iter__ "object.__iter__") method to allow efficient iteration through the container; for mappings, [`__iter__()`](#object.__iter__ "object.__iter__") should iterate through the object’s keys; for sequences, it should iterate through the values. `object.__len__(self)` Called to implement the built-in function [`len()`](../library/functions#len "len"). Should return the length of the object, an integer `>=` 0. Also, an object that doesn’t define a [`__bool__()`](#object.__bool__ "object.__bool__") method and whose [`__len__()`](#object.__len__ "object.__len__") method returns zero is considered to be false in a Boolean context. **CPython implementation detail:** In CPython, the length is required to be at most [`sys.maxsize`](../library/sys#sys.maxsize "sys.maxsize"). If the length is larger than `sys.maxsize` some features (such as [`len()`](../library/functions#len "len")) may raise [`OverflowError`](../library/exceptions#OverflowError "OverflowError"). To prevent raising `OverflowError` by truth value testing, an object must define a [`__bool__()`](#object.__bool__ "object.__bool__") method. `object.__length_hint__(self)` Called to implement [`operator.length_hint()`](../library/operator#operator.length_hint "operator.length_hint"). Should return an estimated length for the object (which may be greater or less than the actual length). The length must be an integer `>=` 0. The return value may also be [`NotImplemented`](../library/constants#NotImplemented "NotImplemented"), which is treated the same as if the `__length_hint__` method didn’t exist at all. This method is purely an optimization and is never required for correctness. New in version 3.4. Note Slicing is done exclusively with the following three methods. A call like ``` a[1:2] = b ``` is translated to ``` a[slice(1, 2, None)] = b ``` and so forth. Missing slice items are always filled in with `None`. `object.__getitem__(self, key)` Called to implement evaluation of `self[key]`. For [sequence](../glossary#term-sequence) types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a [sequence](../glossary#term-sequence) type) is up to the [`__getitem__()`](#object.__getitem__ "object.__getitem__") method. If *key* is of an inappropriate type, [`TypeError`](../library/exceptions#TypeError "TypeError") may be raised; if of a value outside the set of indexes for the sequence (after any special interpretation of negative values), [`IndexError`](../library/exceptions#IndexError "IndexError") should be raised. For [mapping](../glossary#term-mapping) types, if *key* is missing (not in the container), [`KeyError`](../library/exceptions#KeyError "KeyError") should be raised. Note [`for`](compound_stmts#for) loops expect that an [`IndexError`](../library/exceptions#IndexError "IndexError") will be raised for illegal indexes to allow proper detection of the end of the sequence. Note When [subscripting](expressions#subscriptions) a *class*, the special class method [`__class_getitem__()`](#object.__class_getitem__ "object.__class_getitem__") may be called instead of `__getitem__()`. See [\_\_class\_getitem\_\_ versus \_\_getitem\_\_](#classgetitem-versus-getitem) for more details. `object.__setitem__(self, key, value)` Called to implement assignment to `self[key]`. Same note as for [`__getitem__()`](#object.__getitem__ "object.__getitem__"). This should only be implemented for mappings if the objects support changes to the values for keys, or if new keys can be added, or for sequences if elements can be replaced. The same exceptions should be raised for improper *key* values as for the [`__getitem__()`](#object.__getitem__ "object.__getitem__") method. `object.__delitem__(self, key)` Called to implement deletion of `self[key]`. Same note as for [`__getitem__()`](#object.__getitem__ "object.__getitem__"). This should only be implemented for mappings if the objects support removal of keys, or for sequences if elements can be removed from the sequence. The same exceptions should be raised for improper *key* values as for the [`__getitem__()`](#object.__getitem__ "object.__getitem__") method. `object.__missing__(self, key)` Called by [`dict`](../library/stdtypes#dict "dict").[`__getitem__()`](#object.__getitem__ "object.__getitem__") to implement `self[key]` for dict subclasses when key is not in the dictionary. `object.__iter__(self)` This method is called when an iterator is required for a container. This method should return a new iterator object that can iterate over all the objects in the container. For mappings, it should iterate over the keys of the container. Iterator objects also need to implement this method; they are required to return themselves. For more information on iterator objects, see [Iterator Types](../library/stdtypes#typeiter). `object.__reversed__(self)` Called (if present) by the [`reversed()`](../library/functions#reversed "reversed") built-in to implement reverse iteration. It should return a new iterator object that iterates over all the objects in the container in reverse order. If the [`__reversed__()`](#object.__reversed__ "object.__reversed__") method is not provided, the [`reversed()`](../library/functions#reversed "reversed") built-in will fall back to using the sequence protocol ([`__len__()`](#object.__len__ "object.__len__") and [`__getitem__()`](#object.__getitem__ "object.__getitem__")). Objects that support the sequence protocol should only provide [`__reversed__()`](#object.__reversed__ "object.__reversed__") if they can provide an implementation that is more efficient than the one provided by [`reversed()`](../library/functions#reversed "reversed"). The membership test operators ([`in`](expressions#in) and [`not in`](expressions#not-in)) are normally implemented as an iteration through a container. However, container objects can supply the following special method with a more efficient implementation, which also does not require the object be iterable. `object.__contains__(self, item)` Called to implement membership test operators. Should return true if *item* is in *self*, false otherwise. For mapping objects, this should consider the keys of the mapping rather than the values or the key-item pairs. For objects that don’t define [`__contains__()`](#object.__contains__ "object.__contains__"), the membership test first tries iteration via [`__iter__()`](#object.__iter__ "object.__iter__"), then the old sequence iteration protocol via [`__getitem__()`](#object.__getitem__ "object.__getitem__"), see [this section in the language reference](expressions#membership-test-details). ### 3.3.8. Emulating numeric types The following methods can be defined to emulate numeric objects. Methods corresponding to operations that are not supported by the particular kind of number implemented (e.g., bitwise operations for non-integral numbers) should be left undefined. `object.__add__(self, other)` `object.__sub__(self, other)` `object.__mul__(self, other)` `object.__matmul__(self, other)` `object.__truediv__(self, other)` `object.__floordiv__(self, other)` `object.__mod__(self, other)` `object.__divmod__(self, other)` `object.__pow__(self, other[, modulo])` `object.__lshift__(self, other)` `object.__rshift__(self, other)` `object.__and__(self, other)` `object.__xor__(self, other)` `object.__or__(self, other)` These methods are called to implement the binary arithmetic operations (`+`, `-`, `*`, `@`, `/`, `//`, `%`, [`divmod()`](../library/functions#divmod "divmod"), [`pow()`](../library/functions#pow "pow"), `**`, `<<`, `>>`, `&`, `^`, `|`). For instance, to evaluate the expression `x + y`, where *x* is an instance of a class that has an [`__add__()`](#object.__add__ "object.__add__") method, `x.__add__(y)` is called. The [`__divmod__()`](#object.__divmod__ "object.__divmod__") method should be the equivalent to using [`__floordiv__()`](#object.__floordiv__ "object.__floordiv__") and [`__mod__()`](#object.__mod__ "object.__mod__"); it should not be related to [`__truediv__()`](#object.__truediv__ "object.__truediv__"). Note that [`__pow__()`](#object.__pow__ "object.__pow__") should be defined to accept an optional third argument if the ternary version of the built-in [`pow()`](../library/functions#pow "pow") function is to be supported. If one of those methods does not support the operation with the supplied arguments, it should return `NotImplemented`. `object.__radd__(self, other)` `object.__rsub__(self, other)` `object.__rmul__(self, other)` `object.__rmatmul__(self, other)` `object.__rtruediv__(self, other)` `object.__rfloordiv__(self, other)` `object.__rmod__(self, other)` `object.__rdivmod__(self, other)` `object.__rpow__(self, other[, modulo])` `object.__rlshift__(self, other)` `object.__rrshift__(self, other)` `object.__rand__(self, other)` `object.__rxor__(self, other)` `object.__ror__(self, other)` These methods are called to implement the binary arithmetic operations (`+`, `-`, `*`, `@`, `/`, `//`, `%`, [`divmod()`](../library/functions#divmod "divmod"), [`pow()`](../library/functions#pow "pow"), `**`, `<<`, `>>`, `&`, `^`, `|`) with reflected (swapped) operands. These functions are only called if the left operand does not support the corresponding operation [3](#id10) and the operands are of different types. [4](#id11) For instance, to evaluate the expression `x - y`, where *y* is an instance of a class that has an [`__rsub__()`](#object.__rsub__ "object.__rsub__") method, `y.__rsub__(x)` is called if `x.__sub__(y)` returns *NotImplemented*. Note that ternary [`pow()`](../library/functions#pow "pow") will not try calling [`__rpow__()`](#object.__rpow__ "object.__rpow__") (the coercion rules would become too complicated). Note If the right operand’s type is a subclass of the left operand’s type and that subclass provides a different implementation of the reflected method for the operation, this method will be called before the left operand’s non-reflected method. This behavior allows subclasses to override their ancestors’ operations. `object.__iadd__(self, other)` `object.__isub__(self, other)` `object.__imul__(self, other)` `object.__imatmul__(self, other)` `object.__itruediv__(self, other)` `object.__ifloordiv__(self, other)` `object.__imod__(self, other)` `object.__ipow__(self, other[, modulo])` `object.__ilshift__(self, other)` `object.__irshift__(self, other)` `object.__iand__(self, other)` `object.__ixor__(self, other)` `object.__ior__(self, other)` These methods are called to implement the augmented arithmetic assignments (`+=`, `-=`, `*=`, `@=`, `/=`, `//=`, `%=`, `**=`, `<<=`, `>>=`, `&=`, `^=`, `|=`). These methods should attempt to do the operation in-place (modifying *self*) and return the result (which could be, but does not have to be, *self*). If a specific method is not defined, the augmented assignment falls back to the normal methods. For instance, if *x* is an instance of a class with an [`__iadd__()`](#object.__iadd__ "object.__iadd__") method, `x += y` is equivalent to `x = x.__iadd__(y)` . Otherwise, `x.__add__(y)` and `y.__radd__(x)` are considered, as with the evaluation of `x + y`. In certain situations, augmented assignment can result in unexpected errors (see [Why does a\_tuple[i] += [‘item’] raise an exception when the addition works?](../faq/programming#faq-augmented-assignment-tuple-error)), but this behavior is in fact part of the data model. Note Due to a bug in the dispatching mechanism for `**=`, a class that defines [`__ipow__()`](#object.__ipow__ "object.__ipow__") but returns `NotImplemented` would fail to fall back to `x.__pow__(y)` and `y.__rpow__(x)`. This bug is fixed in Python 3.10. `object.__neg__(self)` `object.__pos__(self)` `object.__abs__(self)` `object.__invert__(self)` Called to implement the unary arithmetic operations (`-`, `+`, [`abs()`](../library/functions#abs "abs") and `~`). `object.__complex__(self)` `object.__int__(self)` `object.__float__(self)` Called to implement the built-in functions [`complex()`](../library/functions#complex "complex"), [`int()`](../library/functions#int "int") and [`float()`](../library/functions#float "float"). Should return a value of the appropriate type. `object.__index__(self)` Called to implement [`operator.index()`](../library/operator#operator.index "operator.index"), and whenever Python needs to losslessly convert the numeric object to an integer object (such as in slicing, or in the built-in [`bin()`](../library/functions#bin "bin"), [`hex()`](../library/functions#hex "hex") and [`oct()`](../library/functions#oct "oct") functions). Presence of this method indicates that the numeric object is an integer type. Must return an integer. If [`__int__()`](#object.__int__ "object.__int__"), [`__float__()`](#object.__float__ "object.__float__") and [`__complex__()`](#object.__complex__ "object.__complex__") are not defined then corresponding built-in functions [`int()`](../library/functions#int "int"), [`float()`](../library/functions#float "float") and [`complex()`](../library/functions#complex "complex") fall back to [`__index__()`](#object.__index__ "object.__index__"). `object.__round__(self[, ndigits])` `object.__trunc__(self)` `object.__floor__(self)` `object.__ceil__(self)` Called to implement the built-in function [`round()`](../library/functions#round "round") and [`math`](../library/math#module-math "math: Mathematical functions (sin() etc.).") functions [`trunc()`](../library/math#math.trunc "math.trunc"), [`floor()`](../library/math#math.floor "math.floor") and [`ceil()`](../library/math#math.ceil "math.ceil"). Unless *ndigits* is passed to `__round__()` all these methods should return the value of the object truncated to an [`Integral`](../library/numbers#numbers.Integral "numbers.Integral") (typically an [`int`](../library/functions#int "int")). The built-in function [`int()`](../library/functions#int "int") falls back to [`__trunc__()`](#object.__trunc__ "object.__trunc__") if neither [`__int__()`](#object.__int__ "object.__int__") nor [`__index__()`](#object.__index__ "object.__index__") is defined. ### 3.3.9. With Statement Context Managers A *context manager* is an object that defines the runtime context to be established when executing a [`with`](compound_stmts#with) statement. The context manager handles the entry into, and the exit from, the desired runtime context for the execution of the block of code. Context managers are normally invoked using the `with` statement (described in section [The with statement](compound_stmts#with)), but can also be used by directly invoking their methods. Typical uses of context managers include saving and restoring various kinds of global state, locking and unlocking resources, closing opened files, etc. For more information on context managers, see [Context Manager Types](../library/stdtypes#typecontextmanager). `object.__enter__(self)` Enter the runtime context related to this object. The [`with`](compound_stmts#with) statement will bind this method’s return value to the target(s) specified in the `as` clause of the statement, if any. `object.__exit__(self, exc_type, exc_value, traceback)` Exit the runtime context related to this object. The parameters describe the exception that caused the context to be exited. If the context was exited without an exception, all three arguments will be [`None`](../library/constants#None "None"). If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a true value. Otherwise, the exception will be processed normally upon exit from this method. Note that [`__exit__()`](#object.__exit__ "object.__exit__") methods should not reraise the passed-in exception; this is the caller’s responsibility. See also [**PEP 343**](https://www.python.org/dev/peps/pep-0343) - The “with” statement The specification, background, and examples for the Python [`with`](compound_stmts#with) statement. ### 3.3.10. Special method lookup For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary. That behaviour is the reason why the following code raises an exception: ``` >>> class C: ... pass ... >>> c = C() >>> c.__len__ = lambda: 5 >>> len(c) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: object of type 'C' has no len() ``` The rationale behind this behaviour lies with a number of special methods such as [`__hash__()`](#object.__hash__ "object.__hash__") and [`__repr__()`](#object.__repr__ "object.__repr__") that are implemented by all objects, including type objects. If the implicit lookup of these methods used the conventional lookup process, they would fail when invoked on the type object itself: ``` >>> 1 .__hash__() == hash(1) True >>> int.__hash__() == hash(int) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: descriptor '__hash__' of 'int' object needs an argument ``` Incorrectly attempting to invoke an unbound method of a class in this way is sometimes referred to as ‘metaclass confusion’, and is avoided by bypassing the instance when looking up special methods: ``` >>> type(1).__hash__(1) == hash(1) True >>> type(int).__hash__(int) == hash(int) True ``` In addition to bypassing any instance attributes in the interest of correctness, implicit special method lookup generally also bypasses the [`__getattribute__()`](#object.__getattribute__ "object.__getattribute__") method even of the object’s metaclass: ``` >>> class Meta(type): ... def __getattribute__(*args): ... print("Metaclass getattribute invoked") ... return type.__getattribute__(*args) ... >>> class C(object, metaclass=Meta): ... def __len__(self): ... return 10 ... def __getattribute__(*args): ... print("Class getattribute invoked") ... return object.__getattribute__(*args) ... >>> c = C() >>> c.__len__() # Explicit lookup via instance Class getattribute invoked 10 >>> type(c).__len__(c) # Explicit lookup via type Metaclass getattribute invoked 10 >>> len(c) # Implicit lookup 10 ``` Bypassing the [`__getattribute__()`](#object.__getattribute__ "object.__getattribute__") machinery in this fashion provides significant scope for speed optimisations within the interpreter, at the cost of some flexibility in the handling of special methods (the special method *must* be set on the class object itself in order to be consistently invoked by the interpreter). 3.4. Coroutines ---------------- ### 3.4.1. Awaitable Objects An [awaitable](../glossary#term-awaitable) object generally implements an [`__await__()`](#object.__await__ "object.__await__") method. [Coroutine objects](../glossary#term-coroutine) returned from [`async def`](compound_stmts#async-def) functions are awaitable. Note The [generator iterator](../glossary#term-generator-iterator) objects returned from generators decorated with [`types.coroutine()`](../library/types#types.coroutine "types.coroutine") or [`asyncio.coroutine()`](../library/asyncio-task#asyncio.coroutine "asyncio.coroutine") are also awaitable, but they do not implement [`__await__()`](#object.__await__ "object.__await__"). `object.__await__(self)` Must return an [iterator](../glossary#term-iterator). Should be used to implement [awaitable](../glossary#term-awaitable) objects. For instance, [`asyncio.Future`](../library/asyncio-future#asyncio.Future "asyncio.Future") implements this method to be compatible with the [`await`](expressions#await) expression. New in version 3.5. See also [**PEP 492**](https://www.python.org/dev/peps/pep-0492) for additional information about awaitable objects. ### 3.4.2. Coroutine Objects [Coroutine objects](../glossary#term-coroutine) are [awaitable](../glossary#term-awaitable) objects. A coroutine’s execution can be controlled by calling [`__await__()`](#object.__await__ "object.__await__") and iterating over the result. When the coroutine has finished executing and returns, the iterator raises [`StopIteration`](../library/exceptions#StopIteration "StopIteration"), and the exception’s `value` attribute holds the return value. If the coroutine raises an exception, it is propagated by the iterator. Coroutines should not directly raise unhandled [`StopIteration`](../library/exceptions#StopIteration "StopIteration") exceptions. Coroutines also have the methods listed below, which are analogous to those of generators (see [Generator-iterator methods](expressions#generator-methods)). However, unlike generators, coroutines do not directly support iteration. Changed in version 3.5.2: It is a [`RuntimeError`](../library/exceptions#RuntimeError "RuntimeError") to await on a coroutine more than once. `coroutine.send(value)` Starts or resumes execution of the coroutine. If *value* is `None`, this is equivalent to advancing the iterator returned by [`__await__()`](#object.__await__ "object.__await__"). If *value* is not `None`, this method delegates to the [`send()`](expressions#generator.send "generator.send") method of the iterator that caused the coroutine to suspend. The result (return value, [`StopIteration`](../library/exceptions#StopIteration "StopIteration"), or other exception) is the same as when iterating over the [`__await__()`](#object.__await__ "object.__await__") return value, described above. `coroutine.throw(value)` `coroutine.throw(type[, value[, traceback]])` Raises the specified exception in the coroutine. This method delegates to the [`throw()`](expressions#generator.throw "generator.throw") method of the iterator that caused the coroutine to suspend, if it has such a method. Otherwise, the exception is raised at the suspension point. The result (return value, [`StopIteration`](../library/exceptions#StopIteration "StopIteration"), or other exception) is the same as when iterating over the [`__await__()`](#object.__await__ "object.__await__") return value, described above. If the exception is not caught in the coroutine, it propagates back to the caller. `coroutine.close()` Causes the coroutine to clean itself up and exit. If the coroutine is suspended, this method first delegates to the [`close()`](expressions#generator.close "generator.close") method of the iterator that caused the coroutine to suspend, if it has such a method. Then it raises [`GeneratorExit`](../library/exceptions#GeneratorExit "GeneratorExit") at the suspension point, causing the coroutine to immediately clean itself up. Finally, the coroutine is marked as having finished executing, even if it was never started. Coroutine objects are automatically closed using the above process when they are about to be destroyed. ### 3.4.3. Asynchronous Iterators An *asynchronous iterator* can call asynchronous code in its `__anext__` method. Asynchronous iterators can be used in an [`async for`](compound_stmts#async-for) statement. `object.__aiter__(self)` Must return an *asynchronous iterator* object. `object.__anext__(self)` Must return an *awaitable* resulting in a next value of the iterator. Should raise a [`StopAsyncIteration`](../library/exceptions#StopAsyncIteration "StopAsyncIteration") error when the iteration is over. An example of an asynchronous iterable object: ``` class Reader: async def readline(self): ... def __aiter__(self): return self async def __anext__(self): val = await self.readline() if val == b'': raise StopAsyncIteration return val ``` New in version 3.5. Changed in version 3.7: Prior to Python 3.7, [`__aiter__()`](#object.__aiter__ "object.__aiter__") could return an *awaitable* that would resolve to an [asynchronous iterator](../glossary#term-asynchronous-iterator). Starting with Python 3.7, [`__aiter__()`](#object.__aiter__ "object.__aiter__") must return an asynchronous iterator object. Returning anything else will result in a [`TypeError`](../library/exceptions#TypeError "TypeError") error. ### 3.4.4. Asynchronous Context Managers An *asynchronous context manager* is a *context manager* that is able to suspend execution in its `__aenter__` and `__aexit__` methods. Asynchronous context managers can be used in an [`async with`](compound_stmts#async-with) statement. `object.__aenter__(self)` Semantically similar to [`__enter__()`](#object.__enter__ "object.__enter__"), the only difference being that it must return an *awaitable*. `object.__aexit__(self, exc_type, exc_value, traceback)` Semantically similar to [`__exit__()`](#object.__exit__ "object.__exit__"), the only difference being that it must return an *awaitable*. An example of an asynchronous context manager class: ``` class AsyncContextManager: async def __aenter__(self): await log('entering context') async def __aexit__(self, exc_type, exc, tb): await log('exiting context') ``` New in version 3.5. #### Footnotes `1` It *is* possible in some cases to change an object’s type, under certain controlled conditions. It generally isn’t a good idea though, since it can lead to some very strange behaviour if it is handled incorrectly. `2` The [`__hash__()`](#object.__hash__ "object.__hash__"), [`__iter__()`](#object.__iter__ "object.__iter__"), [`__reversed__()`](#object.__reversed__ "object.__reversed__"), and [`__contains__()`](#object.__contains__ "object.__contains__") methods have special handling for this; others will still raise a [`TypeError`](../library/exceptions#TypeError "TypeError"), but may do so by relying on the behavior that `None` is not callable. `3` “Does not support” here means that the class has no such method, or the method returns `NotImplemented`. Do not set the method to `None` if you want to force fallback to the right operand’s reflected method—that will instead have the opposite effect of explicitly *blocking* such fallback. `4` For operands of the same type, it is assumed that if the non-reflected method – such as [`__add__()`](#object.__add__ "object.__add__") – fails then the overall operation is not supported, which is why the reflected method is not called.
programming_docs
phaser Class: Phaser.Rope Class: Phaser.Rope ================== Constructor ----------- ### new Rope(game, x, y, key, frame, points) A Rope is a Sprite that has a repeating texture. The texture will automatically wrap on the edges as it moves. Please note that Ropes cannot have an input handler. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | | `x` | number | The x coordinate (in world space) to position the Rope at. | | `y` | number | The y coordinate (in world space) to position the Rope at. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [PIXI.Texture](pixi.texture) | This is the image or texture used by the Rope during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. | | `frame` | string | number | If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | | `points` | Array | An array of {Phaser.Point}. | Source code: [gameobjects/Rope.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Rope.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Rope.js#L42)) Extends ------- * [PIXI.Rope](pixi.rope) * [Phaser.Component.Core](phaser.component.core) * [Phaser.Component.Angle](phaser.component.angle) * [Phaser.Component.Animation](phaser.component.animation) * [Phaser.Component.AutoCull](phaser.component.autocull) * [Phaser.Component.Bounds](phaser.component.bounds) * [Phaser.Component.BringToTop](phaser.component.bringtotop) * [Phaser.Component.Crop](phaser.component.crop) * [Phaser.Component.Delta](phaser.component.delta) * [Phaser.Component.Destroy](phaser.component.destroy) * [Phaser.Component.FixedToCamera](phaser.component.fixedtocamera) * [Phaser.Component.InWorld](phaser.component.inworld) * [Phaser.Component.LifeSpan](phaser.component.lifespan) * [Phaser.Component.LoadTexture](phaser.component.loadtexture) * [Phaser.Component.Overlap](phaser.component.overlap) * [Phaser.Component.PhysicsBody](phaser.component.physicsbody) * [Phaser.Component.Reset](phaser.component.reset) * [Phaser.Component.ScaleMinMax](phaser.component.scaleminmax) * [Phaser.Component.Smoothed](phaser.component.smoothed) Public Properties ----------------- ### alive : boolean A useful flag to control if the Game Object is alive or dead. This is set automatically by the Health components `damage` method should the object run out of health. Or you can toggle it via your game code. This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. Inherited From * [Phaser.Component.LifeSpan#alive](phaser.component.lifespan#alive) Default Value * true Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L50)) ### angle : number The angle property is the rotation of the Game Object in *degrees* from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90. If you wish to work in radians instead of degrees you can use the property `rotation` instead. Working in radians is slightly faster as it doesn't have to perform any calculations. Inherited From * [Phaser.Component.Angle#angle](phaser.component.angle#angle) Source code: [gameobjects/components/Angle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js#L29)) ### animations : [Phaser.AnimationManager](phaser.animationmanager) If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. Through it you can create, play, pause and stop animations. Inherited From * [Phaser.Component.Core#animations](phaser.component.core#animations) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 193](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L193)) See * [Phaser.AnimationManager](phaser.animationmanager) ### autoCull : boolean A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, or you have tested performance and find it acceptable. Inherited From * [Phaser.Component.AutoCull#autoCull](phaser.component.autocull#autoCull) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L28)) ### blendMode : number The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode. Inherited From * [PIXI.Strip#blendMode](pixi.strip#blendMode) Default Value * PIXI.blendModes.NORMAL; Source code: [pixi/extras/Strip.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js#L51)) ### body : [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | null `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated properties and methods via it. By default Game Objects won't add themselves to any physics system and their `body` property will be `null`. To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`. You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group. Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5, so the physics body is centered on the Game Object. If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics. ##### Type * [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | null Inherited From * [Phaser.Component.PhysicsBody#body](phaser.component.physicsbody#body) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 91](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L91)) ### bottom : number The sum of the y and height properties. This is the same as `y + height - offsetY`. Inherited From * [Phaser.Component.Bounds#bottom](phaser.component.bounds#bottom) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 168](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L168)) ### cameraOffset : [Phaser.Point](phaser.point) The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. Inherited From * [Phaser.Component.FixedToCamera#cameraOffset](phaser.component.fixedtocamera#cameraOffset) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L86)) ### canvasPadding : number Triangles in canvas mode are automatically antialiased, use this value to force triangles to overlap a bit with each other. Inherited From * [PIXI.Strip#canvasPadding](pixi.strip#canvasPadding) Source code: [pixi/extras/Strip.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js) ([Line 60](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js#L60)) ### centerX : number The center x coordinate of the Game Object. This is the same as `(x - offsetX) + (width / 2)`. Inherited From * [Phaser.Component.Bounds#centerX](phaser.component.bounds#centerX) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L58)) ### centerY : number The center y coordinate of the Game Object. This is the same as `(y - offsetY) + (height / 2)`. Inherited From * [Phaser.Component.Bounds#centerY](phaser.component.bounds#centerY) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 80](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L80)) ### checkWorldBounds : boolean If this is set to `true` the Game Object checks if it is within the World bounds each frame. When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event. If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event. It also optionally kills the Game Object if `outOfBoundsKill` is `true`. When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame. This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, or you have tested performance and find it acceptable. Inherited From * [Phaser.Component.InWorld#checkWorldBounds](phaser.component.inworld#checkWorldBounds) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L98)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### <internal> components : Object The components this Game Object has installed. Inherited From * [Phaser.Component.Core#components](phaser.component.core#components) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 167](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L167)) ### cropRect : [Phaser.Rectangle](phaser.rectangle) The Rectangle used to crop the texture this Game Object uses. Set this property via `crop`. If you modify this property directly you must call `updateCrop` in order to have the change take effect. Inherited From * [Phaser.Component.Crop#cropRect](phaser.component.crop#cropRect) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L24)) ### data : Object An empty Object that belongs to this Game Object. This value isn't ever used internally by Phaser, but may be used by your own code, or by Phaser Plugins, to store data that needs to be associated with the Game Object, without polluting the Game Object directly. Inherited From * [Phaser.Component.Core#data](phaser.component.core#data) Default Value * {} Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 160](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L160)) ### debug : boolean A debug flag designed for use with `Game.enableStep`. Inherited From * [Phaser.Component.Core#debug](phaser.component.core#debug) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 218](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L218)) ### [readonly] deltaX : number Returns the delta x value. The difference between world.x now and in the previous frame. The value will be positive if the Game Object has moved to the right or negative if to the left. Inherited From * [Phaser.Component.Delta#deltaX](phaser.component.delta#deltaX) Source code: [gameobjects/components/Delta.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js#L24)) ### [readonly] deltaY : number Returns the delta y value. The difference between world.y now and in the previous frame. The value will be positive if the Game Object has moved down or negative if up. Inherited From * [Phaser.Component.Delta#deltaY](phaser.component.delta#deltaY) Source code: [gameobjects/components/Delta.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js#L42)) ### [readonly] deltaZ : number Returns the delta z value. The difference between rotation now and in the previous frame. The delta value. Inherited From * [Phaser.Component.Delta#deltaZ](phaser.component.delta#deltaZ) Source code: [gameobjects/components/Delta.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js#L58)) ### [readonly] destroyPhase : boolean As a Game Object runs through its destroy method this flag is set to true, and can be checked in any sub-systems or plugins it is being destroyed from. Inherited From * [Phaser.Component.Destroy#destroyPhase](phaser.component.destroy#destroyPhase) Source code: [gameobjects/components/Destroy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js#L22)) ### dirty : boolean Whether the strip is dirty or not Inherited From * [PIXI.Strip#dirty](pixi.strip#dirty) Source code: [pixi/extras/Strip.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js) ([Line 43](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js#L43)) ### events : [Phaser.Events](phaser.events) All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this Game Object, or any of its components. Inherited From * [Phaser.Component.Core#events](phaser.component.core#events) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 185](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L185)) See * [Phaser.Events](phaser.events) ### exists : boolean Controls if this Game Object is processed by the core game loop. If this Game Object has a physics body it also controls if its physics body is updated or not. When `exists` is set to `false` it will remove its physics body from the physics world if it has one. It also toggles the `visible` property to false as well. Setting `exists` to true will add its physics body back in to the physics world, if it has one. It will also set the `visible` property to `true`. Inherited From * [Phaser.Component.Core#exists](phaser.component.core#exists) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 284](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L284)) ### fixedToCamera : boolean A Game Object that is "fixed" to the camera uses its x/y coordinates as offsets from the top left of the camera during rendering. The values are adjusted at the rendering stage, overriding the Game Objects actual world position. The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times regardless where in the world the camera is. The offsets are stored in the `cameraOffset` property. Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. Inherited From * [Phaser.Component.FixedToCamera#fixedToCamera](phaser.component.fixedtocamera#fixedToCamera) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 56](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L56)) ### frame : integer Gets or sets the current frame index of the texture being used to render this Game Object. To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use, for example: `player.frame = 4`. If the frame index given doesn't exist it will revert to the first frame found in the texture. If you are using a texture atlas then you should use the `frameName` property instead. If you wish to fully replace the texture being used see `loadTexture`. Inherited From * [Phaser.Component.LoadTexture#frame](phaser.component.loadtexture#frame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 254](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L254)) ### frameName : string Gets or sets the current frame name of the texture being used to render this Game Object. To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use, for example: `player.frameName = "idle"`. If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning. If you are using a sprite sheet then you should use the `frame` property instead. If you wish to fully replace the texture being used see `loadTexture`. Inherited From * [Phaser.Component.LoadTexture#frameName](phaser.component.loadtexture#frameName) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 279](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L279)) ### [readonly] fresh : boolean A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. This property is mostly used internally by the physics systems, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#fresh](phaser.component.core#fresh) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 248](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L248)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Inherited From * [Phaser.Component.Core#game](phaser.component.core#game) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 142](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L142)) ### height : number The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#height](pixi.displayobjectcontainer#height) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 600](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L600)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### [readonly] inCamera : boolean Checks if the Game Objects bounds intersect with the Game Camera bounds. Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. Inherited From * [Phaser.Component.AutoCull#inCamera](phaser.component.autocull#inCamera) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L37)) ### [readonly] inWorld : boolean Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds. Inherited From * [Phaser.Component.InWorld#inWorld](phaser.component.inworld#inWorld) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 129](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L129)) ### key : string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) The key of the image or texture used by this Game Object during rendering. If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. ##### Type * string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) Inherited From * [Phaser.Component.Core#key](phaser.component.core#key) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 203](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L203)) ### left : number The left coordinate of the Game Object. This is the same as `x - offsetX`. Inherited From * [Phaser.Component.Bounds#left](phaser.component.bounds#left) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 102](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L102)) ### lifespan : number The lifespan allows you to give a Game Object a lifespan in milliseconds. Once the Game Object is 'born' you can set this to a positive value. It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. When it reaches zero it will call the `kill` method. Very handy for particles, bullets, collectibles, or any other short-lived entity. Inherited From * [Phaser.Component.LifeSpan#lifespan](phaser.component.lifespan#lifespan) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 65](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L65)) ### name : string A user defined name given to this Game Object. This value isn't ever used internally by Phaser, it is meant as a game level property. Inherited From * [Phaser.Component.Core#name](phaser.component.core#name) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 150](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L150)) ### [readonly] offsetX : number The amount the Game Object is visually offset from its x coordinate. This is the same as `width * anchor.x`. It will only be > 0 if anchor.x is not equal to zero. Inherited From * [Phaser.Component.Bounds#offsetX](phaser.component.bounds#offsetX) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L24)) ### [readonly] offsetY : number The amount the Game Object is visually offset from its y coordinate. This is the same as `height * anchor.y`. It will only be > 0 if anchor.y is not equal to zero. Inherited From * [Phaser.Component.Bounds#offsetY](phaser.component.bounds#offsetY) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L42)) ### outOfBoundsKill : boolean If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false. Inherited From * [Phaser.Component.InWorld#outOfBoundsKill](phaser.component.inworld#outOfBoundsKill) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 106](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L106)) ### outOfCameraBoundsKill : boolean If this and the `autoCull` property are both set to `true`, then the `kill` method is called as soon as the Game Object leaves the camera bounds. Inherited From * [Phaser.Component.InWorld#outOfCameraBoundsKill](phaser.component.inworld#outOfCameraBoundsKill) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 115](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L115)) ### pendingDestroy : boolean A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. You can set it directly to allow you to flag an object to be destroyed on its next update. This is extremely useful if you wish to destroy an object from within one of its own callbacks such as with Buttons or other Input events. Inherited From * [Phaser.Component.Core#pendingDestroy](phaser.component.core#pendingDestroy) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 259](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L259)) ### [readonly] previousPosition : [Phaser.Point](phaser.point) The position the Game Object was located in the previous frame. Inherited From * [Phaser.Component.Core#previousPosition](phaser.component.core#previousPosition) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 225](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L225)) ### [readonly] previousRotation : number The rotation the Game Object was in set to in the previous frame. Value is in radians. Inherited From * [Phaser.Component.Core#previousRotation](phaser.component.core#previousRotation) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L232)) ### [readonly] renderOrderID : number The render order ID is used internally by the renderer and Input Manager and should not be modified. This property is mostly used internally by the renderers, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#renderOrderID](phaser.component.core#renderOrderID) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 240](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L240)) ### right : number The right coordinate of the Game Object. This is the same as `x + width - offsetX`. Inherited From * [Phaser.Component.Bounds#right](phaser.component.bounds#right) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L124)) ### scaleMax : [Phaser.Point](phaser.point) The maximum scale this Game Object will scale up to. It allows you to prevent a parent from scaling this Game Object higher than the given value. Set it to `null` to remove the limit. Inherited From * [Phaser.Component.ScaleMinMax#scaleMax](phaser.component.scaleminmax#scaleMax) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L46)) ### scaleMin : [Phaser.Point](phaser.point) The minimum scale this Game Object will scale down to. It allows you to prevent a parent from scaling this Game Object lower than the given value. Set it to `null` to remove the limit. Inherited From * [Phaser.Component.ScaleMinMax#scaleMin](phaser.component.scaleminmax#scaleMin) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 36](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L36)) ### segments The segments that make up the rope body as an array of Phaser.Rectangles ##### Properties: | Name | Type | Description | | --- | --- | --- | | `updateAnimation` | Array.<Phaser.Rectangles> | Returns an array of Phaser.Rectangles that represent the segments of the given rope | Source code: [gameobjects/Rope.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Rope.js) ([Line 175](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Rope.js#L175)) ### smoothed : boolean Enable or disable texture smoothing for this Game Object. It only takes effect if the Game Object is using an image based texture. Smoothing is enabled by default. Inherited From * [Phaser.Component.Smoothed#smoothed](phaser.component.smoothed#smoothed) Source code: [gameobjects/components/Smoothed.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Smoothed.js) ([Line 25](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Smoothed.js#L25)) ### texture : [PIXI.Texture](pixi.texture) The texture of the strip Inherited From * [PIXI.Strip#texture](pixi.strip#texture) Source code: [pixi/extras/Strip.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js#L20)) ### top : number The y coordinate of the Game Object. This is the same as `y - offsetY`. Inherited From * [Phaser.Component.Bounds#top](phaser.component.bounds#top) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 146](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L146)) ### transformCallback : Function The callback that will apply any scale limiting to the worldTransform. Inherited From * [Phaser.Component.ScaleMinMax#transformCallback](phaser.component.scaleminmax#transformCallback) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L20)) ### transformCallbackContext : Object The context under which `transformCallback` is called. Inherited From * [Phaser.Component.ScaleMinMax#transformCallbackContext](phaser.component.scaleminmax#transformCallbackContext) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L26)) ### [readonly] type : number The const type of this object. Source code: [gameobjects/Rope.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Rope.js) ([Line 57](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Rope.js#L57)) ### updateAnimation : Function A Rope will call its updateAnimation function on each update loop if it has one. Set to a function if you'd like the rope to animate during the update phase. Set to false or null to remove it. Source code: [gameobjects/Rope.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Rope.js) ([Line 144](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Rope.js#L144)) ### width : number The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#width](pixi.displayobjectcontainer#width) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 571](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L571)) ### world : [Phaser.Point](phaser.point) The world coordinates of this Game Object in pixels. Depending on where in the display list this Game Object is placed this value can differ from `position`, which contains the x/y coordinates relative to the Game Objects parent. Inherited From * [Phaser.Component.Core#world](phaser.component.core#world) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 211](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L211)) ### x : number The position of the Game Object on the x axis relative to the local coordinates of the parent. Inherited From * [Phaser.Component.PhysicsBody#x](phaser.component.physicsbody#x) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L98)) ### y : number The position of the Game Object on the y axis relative to the local coordinates of the parent. Inherited From * [Phaser.Component.PhysicsBody#y](phaser.component.physicsbody#y) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L124)) ### [readonly] z : number The z depth of this Game Object within its parent Group. No two objects in a Group can have the same z value. This value is adjusted automatically whenever the Group hierarchy changes. If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. Inherited From * [Phaser.Component.Core#z](phaser.component.core#z) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 177](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L177)) Public Methods -------------- ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### alignIn(container, position, offsetX, offsetY) → {Object} Aligns this Game Object within another Game Object, or Rectangle, known as the 'container', to one of 9 possible positions. The container must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the container. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the container, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `container` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Inherited From * [Phaser.Component.Bounds#alignIn](phaser.component.bounds#alignIn) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 223](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L223)) ### alignTo(parent, position, offsetX, offsetY) → {Object} Aligns this Game Object to the side of another Game Object, or Rectangle, known as the 'parent', in one of 11 possible positions. The parent must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the parent. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the parent, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Inherited From * [Phaser.Component.Bounds#alignTo](phaser.component.bounds#alignTo) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 321](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L321)) ### bringToTop() → {PIXI.DisplayObject} Brings this Game Object to the top of its parents display list. Visually this means it will render over the top of any old child in the same Group. If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#bringToTop](phaser.component.bringtotop#bringToTop) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L24)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### crop(rect, copy) Crop allows you to crop the texture being used to display this Game Object. Setting a crop rectangle modifies the core texture frame. The Game Object width and height properties will be adjusted accordingly. Cropping takes place from the top-left and can be modified in real-time either by providing an updated rectangle object to this method, or by modifying `cropRect` property directly and then calling `updateCrop`. The rectangle object given to this method can be either a `Phaser.Rectangle` or any other object so long as it has public `x`, `y`, `width`, `height`, `right` and `bottom` properties. A reference to the rectangle is stored in `cropRect` unless the `copy` parameter is `true`, in which case the values are duplicated to a local object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `rect` | [Phaser.Rectangle](phaser.rectangle) | | | The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle. | | `copy` | boolean | <optional> | false | If false `cropRect` will be stored as a reference to the given rect. If true it will copy the rect values into a local Phaser Rectangle object stored in cropRect. | Inherited From * [Phaser.Component.Crop#crop](phaser.component.crop#crop) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L49)) ### destroy(destroyChildren, destroyTexture) Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present and nulls its reference to `game`, freeing it up for garbage collection. If this Game Object has the Events component it will also dispatch the `onDestroy` event. You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've more than one Game Object sharing the same BaseTexture. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroyChildren` | boolean | <optional> | true | Should every child of this object have its destroy method called as well? | | `destroyTexture` | boolean | <optional> | false | Destroy the BaseTexture this Game Object is using? Note that if another Game Object is sharing the same BaseTexture it will invalidate it. | Inherited From * [Phaser.Component.Destroy#destroy](phaser.component.destroy#destroy) Source code: [gameobjects/components/Destroy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js#L37)) ### getBounds(matrix) → {Rectangle} Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `matrix` | Matrix | the transformation matrix of the sprite | ##### Returns Rectangle - the framing rectangle Inherited From * [PIXI.Strip#getBounds](pixi.strip#getBounds) Source code: [pixi/extras/Strip.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js) ([Line 405](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js#L405)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the displayObjectContainer as a rectangle without any transformations. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.DisplayObjectContainer#getLocalBounds](pixi.displayobjectcontainer#getLocalBounds) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 437](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L437)) ### kill() → {PIXI.DisplayObject} Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false. It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal. Note that killing a Game Object is a way for you to quickly recycle it in an object pool, it doesn't destroy the object or free it up from memory. If you don't need this Game Object any more you should call `destroy` instead. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.LifeSpan#kill](phaser.component.lifespan#kill) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 113](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L113)) ### loadTexture(key, frame, stopAnimation) Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache. If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead. You should only use `loadTexture` if you want to replace the base texture entirely. Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU. You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite. Doing this then sets the key to be the `frame` argument (the frame is set to zero). This allows you to create sprites using `load.image` during development, and then change them to use a Texture Atlas later in development by simply searching your code for 'PENDING\_ATLAS' and swapping it to be the key of the atlas data. Note: You cannot use a RenderTexture as a texture for a TileSprite. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | | `stopAnimation` | boolean | <optional> | true | If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing. | Inherited From * [Phaser.Component.LoadTexture#loadTexture](phaser.component.loadtexture#loadTexture) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L51)) ### moveDown() → {PIXI.DisplayObject} Moves this Game Object down one place in its parents display list. This call has no effect if the Game Object is already at the bottom of the display list. If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#moveDown](phaser.component.bringtotop#moveDown) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L87)) ### moveUp() → {PIXI.DisplayObject} Moves this Game Object up one place in its parents display list. This call has no effect if the Game Object is already at the top of the display list. If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#moveUp](phaser.component.bringtotop#moveUp) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 66](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L66)) ### overlap(displayObject) → {boolean} Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object, which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result. This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result. Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency. It should be fine for low-volume testing where physics isn't required. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `displayObject` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.TileSprite](phaser.tilesprite) | [Phaser.Button](phaser.button) | PIXI.DisplayObject | The display object to check against. | ##### Returns boolean - True if the bounds of this Game Object intersects at any point with the bounds of the given display object. Inherited From * [Phaser.Component.Overlap#overlap](phaser.component.overlap#overlap) Source code: [gameobjects/components/Overlap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Overlap.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Overlap.js#L29)) ### play(name, frameRate, loop, killOnComplete) → {[Phaser.Animation](phaser.animation)} Plays an Animation. The animation should have previously been created via `animations.add`. If the animation is already playing calling this again won't do anything. If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `name` | string | | | The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'. | | `frameRate` | number | <optional> | null | The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. | | `loop` | boolean | <optional> | false | Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. | | `killOnComplete` | boolean | <optional> | false | If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. | ##### Returns [Phaser.Animation](phaser.animation) - A reference to playing Animation. Inherited From * [Phaser.Component.Animation#play](phaser.component.animation#play) Source code: [gameobjects/components/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Animation.js) ([Line 31](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Animation.js#L31)) ### <internal> postUpdate() Internal method called by the World postUpdate cycle. Inherited From * [Phaser.Component.Core#postUpdate](phaser.component.core#postUpdate) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 338](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L338)) ### preUpdate() Automatically called by World.preUpdate. Source code: [gameobjects/Rope.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Rope.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Rope.js#L93)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### reset(x, y) → {[Phaser.Rope](phaser.rope)} Resets the Rope. This places the Rope at the given x/y world coordinates and then sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state. If the Rope has a physics body that too is reset. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The x coordinate (in world space) to position the Sprite at. | | `y` | number | The y coordinate (in world space) to position the Sprite at. | ##### Returns [Phaser.Rope](phaser.rope) - This instance. Source code: [gameobjects/Rope.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Rope.js) ([Line 125](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Rope.js#L125)) ### resetFrame() Resets the texture frame dimensions that the Game Object uses for rendering. Inherited From * [Phaser.Component.LoadTexture#resetFrame](phaser.component.loadtexture#resetFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L232)) ### resizeFrame(parent, width, height) Resizes the Frame dimensions that the Game Object uses for rendering. You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData it can be useful to adjust the dimensions directly in this way. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `parent` | object | The parent texture object that caused the resize, i.e. a Phaser.Video object. | | `width` | integer | The new width of the texture. | | `height` | integer | The new height of the texture. | Inherited From * [Phaser.Component.LoadTexture#resizeFrame](phaser.component.loadtexture#resizeFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 220](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L220)) ### revive(health) → {PIXI.DisplayObject} Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `health` | number | <optional> | 100 | The health to give the Game Object. Only set if the GameObject has the Health component. | ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.LifeSpan#revive](phaser.component.lifespan#revive) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L78)) ### sendToBack() → {PIXI.DisplayObject} Sends this Game Object to the bottom of its parents display list. Visually this means it will render below all other children in the same Group. If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#sendToBack](phaser.component.bringtotop#sendToBack) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L45)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### setFrame(frame) Sets the texture frame the Game Object uses for rendering. This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `frame` | [Phaser.Frame](phaser.frame) | The Frame to be used by the texture. | Inherited From * [Phaser.Component.LoadTexture#setFrame](phaser.component.loadtexture#setFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 155](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L155)) ### setScaleMinMax(minX, minY, maxX, maxY) Sets the scaleMin and scaleMax values. These values are used to limit how far this Game Object will scale based on its parent. For example if this Game Object has a `minScale` value of 1 and its parent has a `scale` value of 0.5, the 0.5 will be ignored and the scale value of 1 will be used, as the parents scale is lower than the minimum scale this Game Object should adhere to. By setting these values you can carefully control how Game Objects deal with responsive scaling. If only one parameter is given then that value will be used for both scaleMin and scaleMax: `setScaleMinMax(1)` = scaleMin.x, scaleMin.y, scaleMax.x and scaleMax.y all = 1 If only two parameters are given the first is set as scaleMin.x and y and the second as scaleMax.x and y: `setScaleMinMax(0.5, 2)` = scaleMin.x and y = 0.5 and scaleMax.x and y = 2 If you wish to set `scaleMin` with different values for x and y then either modify Game Object.scaleMin directly, or pass `null` for the `maxX` and `maxY` parameters. Call `setScaleMinMax(null)` to clear all previously set values. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `minX` | number | null | The minimum horizontal scale value this Game Object can scale down to. | | `minY` | number | null | The minimum vertical scale value this Game Object can scale down to. | | `maxX` | number | null | The maximum horizontal scale value this Game Object can scale up to. | | `maxY` | number | null | The maximum vertical scale value this Game Object can scale up to. | Inherited From * [Phaser.Component.ScaleMinMax#setScaleMinMax](phaser.component.scaleminmax#setScaleMinMax) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 110](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L110)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) ### update() Override and use this function in your own custom objects to handle any update requirements you may have. Source code: [gameobjects/Rope.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Rope.js) ([Line 110](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Rope.js#L110)) ### updateCrop() If you have set a crop rectangle on this Game Object via `crop` and since modified the `cropRect` property, or the rectangle it references, then you need to update the crop frame by calling this method. Inherited From * [Phaser.Component.Crop#updateCrop](phaser.component.crop#updateCrop) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L86))
programming_docs
phaser Class: Phaser.FrameData Class: Phaser.FrameData ======================= Constructor ----------- ### new FrameData() FrameData is a container for Frame objects, which are the internal representation of animation data in Phaser. Source code: [animation/FrameData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/FrameData.js) ([Line 13](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/FrameData.js#L13)) Public Properties ----------------- ### [readonly] total : number The total number of frames in this FrameData set. Source code: [animation/FrameData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/FrameData.js) ([Line 267](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/FrameData.js#L267)) Public Methods -------------- ### addFrame(frame) → {[Phaser.Frame](phaser.frame)} Adds a new Frame to this FrameData collection. Typically called by the Animation.Parser and not directly. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `frame` | [Phaser.Frame](phaser.frame) | The frame to add to this FrameData set. | ##### Returns [Phaser.Frame](phaser.frame) - The frame that was just added. Source code: [animation/FrameData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/FrameData.js) ([Line 31](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/FrameData.js#L31)) ### checkFrameName(name) → {boolean} Check if there is a Frame with the given name. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `name` | string | The name of the frame you want to check. | ##### Returns boolean - True if the frame is found, otherwise false. Source code: [animation/FrameData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/FrameData.js) ([Line 89](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/FrameData.js#L89)) ### clone() → {[Phaser.FrameData](phaser.framedata)} Makes a copy of this FrameData including copies (not references) to all of the Frames it contains. ##### Returns [Phaser.FrameData](phaser.framedata) - A clone of this object, including clones of the Frame objects it contains. Source code: [animation/FrameData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/FrameData.js) ([Line 107](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/FrameData.js#L107)) ### destroy() Destroys this FrameData collection by nulling the \_frames and \_frameNames arrays. Source code: [animation/FrameData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/FrameData.js) ([Line 251](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/FrameData.js#L251)) ### getFrame(index) → {[Phaser.Frame](phaser.frame)} Get a Frame by its numerical index. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | number | The index of the frame you want to get. | ##### Returns [Phaser.Frame](phaser.frame) - The frame, if found. Source code: [animation/FrameData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/FrameData.js) ([Line 53](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/FrameData.js#L53)) ### getFrameByName(name) → {[Phaser.Frame](phaser.frame)} Get a Frame by its frame name. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `name` | string | The name of the frame you want to get. | ##### Returns [Phaser.Frame](phaser.frame) - The frame, if found. Source code: [animation/FrameData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/FrameData.js) ([Line 71](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/FrameData.js#L71)) ### getFrameIndexes(frames, useNumericIndex, output) → {Array} Returns all of the Frame indexes in this FrameData set. The frames indexes are returned in the output array, or if none is provided in a new Array object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `frames` | Array | <optional> | | An Array containing the indexes of the frames to retrieve. If undefined or the array is empty then all frames in the FrameData are returned. | | `useNumericIndex` | boolean | <optional> | true | Are the given frames using numeric indexes (default) or strings? (false) | | `output` | Array | <optional> | | If given the results will be appended to the end of this array otherwise a new array will be created. | ##### Returns Array - An array of all Frame indexes matching the given names or IDs. Source code: [animation/FrameData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/FrameData.js) ([Line 204](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/FrameData.js#L204)) ### getFrameRange(start, end, output) → {Array} Returns a range of frames based on the given start and end frame indexes and returns them in an Array. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `start` | number | | The starting frame index. | | `end` | number | | The ending frame index. | | `output` | Array | <optional> | If given the results will be appended to the end of this array otherwise a new array will be created. | ##### Returns Array - An array of Frames between the start and end index values, or an empty array if none were found. Source code: [animation/FrameData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/FrameData.js) ([Line 135](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/FrameData.js#L135)) ### getFrames(frames, useNumericIndex, output) → {Array} Returns all of the Frames in this FrameData set where the frame index is found in the input array. The frames are returned in the output array, or if none is provided in a new Array object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `frames` | Array | <optional> | | An Array containing the indexes of the frames to retrieve. If the array is empty or undefined then all frames in the FrameData are returned. | | `useNumericIndex` | boolean | <optional> | true | Are the given frames using numeric indexes (default) or strings? (false) | | `output` | Array | <optional> | | If given the results will be appended to the end of this array otherwise a new array will be created. | ##### Returns Array - An array of all Frames in this FrameData set matching the given names or IDs. Source code: [animation/FrameData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/FrameData.js) ([Line 157](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/FrameData.js#L157)) phaser Class: Phaser.Physics.Ninja.Circle Class: Phaser.Physics.Ninja.Circle ================================== Constructor ----------- ### new Circle(body, x, y, radius) Ninja Physics Circle constructor. Note: This class could be massively optimised and reduced in size. I leave that challenge up to you. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `body` | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | The body that owns this shape. | | `x` | number | The x coordinate to create this shape at. | | `y` | number | The y coordinate to create this shape at. | | `radius` | number | The radius of this Circle. | Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 19](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L19)) Public Properties ----------------- ### body ##### Properties: | Name | Type | Description | | --- | --- | --- | | `system` | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | A reference to the body that owns this shape. | Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L24)) ### circleTileProjections : Object All of the collision response handlers. Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 90](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L90)) ### [readonly] height : number The height. Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 68](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L68)) ### oldpos : [Phaser.Point](phaser.point) The position of this object in the previous update. Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 39](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L39)) ### pos : [Phaser.Point](phaser.point) The position of this object. Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 34](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L34)) ### radius : number The radius of this circle shape. Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 44](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L44)) ### system : [Phaser.Physics.Ninja](phaser.physics.ninja) A reference to the physics system. Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L29)) ### velocity : [Phaser.Point](phaser.point) The velocity of this object. Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L85)) ### [readonly] width : number The width. Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 62](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L62)) ### [readonly] xw : number Half the width. Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L50)) ### [readonly] yw ##### Properties: | Name | Type | Description | | --- | --- | --- | | `xw` | number | Half the height. | Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 56](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L56)) Public Methods -------------- ### collideCircleVsTile(t) → {boolean} Collides this Circle with a Tile. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `t` | [Phaser.Physics.Ninja.Tile](phaser.physics.ninja.tile) | The Tile involved in the collision. | ##### Returns boolean - True if they collide, otherwise false. Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 248](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L248)) ### collideWorldBounds() Collides this Circle against the world bounds. Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 207](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L207)) ### destroy() Destroys this Circle's reference to Body and System Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 2612](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L2612)) ### integrate() Updates this Circles position. Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L112)) ### projCircle\_22DegB(x, y, oH, oV, obj, t) → {number} Resolves 22 Degree tile collision. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Penetration depth on the x axis. | | `y` | number | Penetration depth on the y axis. | | `oH` | number | Grid / voronoi region. | | `oV` | number | Grid / voronoi region. | | `obj` | [Phaser.Physics.Ninja.Circle](phaser.physics.ninja.circle) | The Circle involved in the collision. | | `t` | [Phaser.Physics.Ninja.Tile](phaser.physics.ninja.tile) | The Tile involved in the collision. | ##### Returns number - The result of the collision. Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 1719](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L1719)) ### projCircle\_22DegS(x, y, oH, oV, obj, t) → {number} Resolves 22 Degree tile collision. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Penetration depth on the x axis. | | `y` | number | Penetration depth on the y axis. | | `oH` | number | Grid / voronoi region. | | `oV` | number | Grid / voronoi region. | | `obj` | [Phaser.Physics.Ninja.Circle](phaser.physics.ninja.circle) | The Circle involved in the collision. | | `t` | [Phaser.Physics.Ninja.Tile](phaser.physics.ninja.tile) | The Tile involved in the collision. | ##### Returns number - The result of the collision. Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 1427](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L1427)) ### projCircle\_45Deg(x, y, oH, oV, obj, t) → {number} Resolves 45 Degree tile collision. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Penetration depth on the x axis. | | `y` | number | Penetration depth on the y axis. | | `oH` | number | Grid / voronoi region. | | `oV` | number | Grid / voronoi region. | | `obj` | [Phaser.Physics.Ninja.Circle](phaser.physics.ninja.circle) | The Circle involved in the collision. | | `t` | [Phaser.Physics.Ninja.Tile](phaser.physics.ninja.tile) | The Tile involved in the collision. | ##### Returns number - The result of the collision. Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 447](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L447)) ### projCircle\_67DegB(x, y, oH, oV, obj, t) → {number} Resolves 67 Degree tile collision. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Penetration depth on the x axis. | | `y` | number | Penetration depth on the y axis. | | `oH` | number | Grid / voronoi region. | | `oV` | number | Grid / voronoi region. | | `obj` | [Phaser.Physics.Ninja.Circle](phaser.physics.ninja.circle) | The Circle involved in the collision. | | `t` | [Phaser.Physics.Ninja.Tile](phaser.physics.ninja.tile) | The Tile involved in the collision. | ##### Returns number - The result of the collision. Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 2307](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L2307)) ### projCircle\_67DegS(x, y, oH, oV, obj, t) → {number} Resolves 67 Degree tile collision. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Penetration depth on the x axis. | | `y` | number | Penetration depth on the y axis. | | `oH` | number | Grid / voronoi region. | | `oV` | number | Grid / voronoi region. | | `obj` | [Phaser.Physics.Ninja.Circle](phaser.physics.ninja.circle) | The Circle involved in the collision. | | `t` | [Phaser.Physics.Ninja.Tile](phaser.physics.ninja.tile) | The Tile involved in the collision. | ##### Returns number - The result of the collision. Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 2022](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L2022)) ### projCircle\_Concave(x, y, oH, oV, obj, t) → {number} Resolves Concave tile collision. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Penetration depth on the x axis. | | `y` | number | Penetration depth on the y axis. | | `oH` | number | Grid / voronoi region. | | `oV` | number | Grid / voronoi region. | | `obj` | [Phaser.Physics.Ninja.Circle](phaser.physics.ninja.circle) | The Circle involved in the collision. | | `t` | [Phaser.Physics.Ninja.Tile](phaser.physics.ninja.tile) | The Tile involved in the collision. | ##### Returns number - The result of the collision. Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 717](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L717)) ### projCircle\_Convex(x, y, oH, oV, obj, t) → {number} Resolves Convex tile collision. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Penetration depth on the x axis. | | `y` | number | Penetration depth on the y axis. | | `oH` | number | Grid / voronoi region. | | `oV` | number | Grid / voronoi region. | | `obj` | [Phaser.Physics.Ninja.Circle](phaser.physics.ninja.circle) | The Circle involved in the collision. | | `t` | [Phaser.Physics.Ninja.Tile](phaser.physics.ninja.tile) | The Tile involved in the collision. | ##### Returns number - The result of the collision. Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 951](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L951)) ### projCircle\_Full(x, y, oH, oV, obj, t) → {number} Resolves Full tile collision. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Penetration depth on the x axis. | | `y` | number | Penetration depth on the y axis. | | `oH` | number | Grid / voronoi region. | | `oV` | number | Grid / voronoi region. | | `obj` | [Phaser.Physics.Ninja.Circle](phaser.physics.ninja.circle) | The Circle involved in the collision. | | `t` | [Phaser.Physics.Ninja.Tile](phaser.physics.ninja.tile) | The Tile involved in the collision. | ##### Returns number - The result of the collision. Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 335](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L335)) ### projCircle\_Half(x, y, oH, oV, obj, t) → {number} Resolves Half tile collision. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Penetration depth on the x axis. | | `y` | number | Penetration depth on the y axis. | | `oH` | number | Grid / voronoi region. | | `oV` | number | Grid / voronoi region. | | `obj` | [Phaser.Physics.Ninja.Circle](phaser.physics.ninja.circle) | The Circle involved in the collision. | | `t` | [Phaser.Physics.Ninja.Tile](phaser.physics.ninja.tile) | The Tile involved in the collision. | ##### Returns number - The result of the collision. Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 1193](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L1193)) ### render(context, xOffset, yOffset, color, filled) Render this circle for debugging purposes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `context` | object | The context to render to. | | `xOffset` | number | X offset from circle's position to render at. | | `yOffset` | number | Y offset from circle's position to render at. | | `color` | string | color of the debug shape to be rendered. (format is css color string). | | `filled` | boolean | Render the shape as solid (true) or hollow (false). | Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 2622](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L2622)) ### reportCollisionVsWorld(px, py, dx, dy, obj) Process a world collision and apply the resulting forces. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `px` | number | The tangent velocity | | `py` | number | The tangent velocity | | `dx` | number | Collision normal | | `dy` | number | Collision normal | | `obj` | number | Object this Circle collided with | Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L132)) ### resolveCircleTile(x, y, oH, oV, obj, t) → {number} Resolves tile collision. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Penetration depth on the x axis. | | `y` | number | Penetration depth on the y axis. | | `oH` | number | Grid / voronoi region. | | `oV` | number | Grid / voronoi region. | | `obj` | [Phaser.Physics.Ninja.Circle](phaser.physics.ninja.circle) | The Circle involved in the collision. | | `t` | [Phaser.Physics.Ninja.Tile](phaser.physics.ninja.tile) | The Tile involved in the collision. | ##### Returns number - The result of the collision. Source code: [physics/ninja/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js) ([Line 310](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Circle.js#L310))
programming_docs
phaser Class: Phaser.Component.Bounds Class: Phaser.Component.Bounds ============================== Constructor ----------- ### new Bounds() The Bounds component contains properties related to the bounds of the Game Object. Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 12](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L12)) Public Properties ----------------- ### bottom : number The sum of the y and height properties. This is the same as `y + height - offsetY`. Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 168](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L168)) ### centerX : number The center x coordinate of the Game Object. This is the same as `(x - offsetX) + (width / 2)`. Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L58)) ### centerY : number The center y coordinate of the Game Object. This is the same as `(y - offsetY) + (height / 2)`. Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 80](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L80)) ### left : number The left coordinate of the Game Object. This is the same as `x - offsetX`. Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 102](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L102)) ### [readonly] offsetX : number The amount the Game Object is visually offset from its x coordinate. This is the same as `width * anchor.x`. It will only be > 0 if anchor.x is not equal to zero. Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L24)) ### [readonly] offsetY : number The amount the Game Object is visually offset from its y coordinate. This is the same as `height * anchor.y`. It will only be > 0 if anchor.y is not equal to zero. Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L42)) ### right : number The right coordinate of the Game Object. This is the same as `x + width - offsetX`. Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L124)) ### top : number The y coordinate of the Game Object. This is the same as `y - offsetY`. Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 146](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L146)) Public Methods -------------- ### alignIn(container, position, offsetX, offsetY) → {Object} Aligns this Game Object within another Game Object, or Rectangle, known as the 'container', to one of 9 possible positions. The container must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the container. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the container, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `container` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 223](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L223)) ### alignTo(parent, position, offsetX, offsetY) → {Object} Aligns this Game Object to the side of another Game Object, or Rectangle, known as the 'parent', in one of 11 possible positions. The parent must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the parent. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the parent, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 321](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L321)) phaser Class: Phaser.Graphics Class: Phaser.Graphics ====================== Constructor ----------- ### new Graphics(game, x, y) A Graphics object is a way to draw primitives to your game. Primitives include forms of geometry, such as Rectangles, Circles and Polygons. They also include lines, arcs and curves. When you initially create a Graphics object it will be empty. To 'draw' to it you first specify a lineStyle or fillStyle (or both), and then draw a shape. For example: ``` graphics.beginFill(0xff0000); graphics.drawCircle(50, 50, 100); graphics.endFill(); ``` This will draw a circle shape to the Graphics object, with a diameter of 100, located at x: 50, y: 50. When a Graphics object is rendered it will render differently based on if the game is running under Canvas or WebGL. Under Canvas it will use the HTML Canvas context drawing operations to draw the path. Under WebGL the graphics data is decomposed into polygons. Both of these are expensive processes, especially with complex shapes. If your Graphics object doesn't change much (or at all) once you've drawn your shape to it, then you will help performance by calling `Graphics.generateTexture`. This will 'bake' the Graphics object into a Texture, and return it. You can then use this Texture for Sprites or other display objects. If your Graphics object updates frequently then you should avoid doing this, as it will constantly generate new textures, which will consume memory. As you can tell, Graphics objects are a bit of a trade-off. While they are extremely useful, you need to be careful in their complexity and quantity of them in your game. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | | Current game instance. | | `x` | number | <optional> | 0 | X position of the new graphics object. | | `y` | number | <optional> | 0 | Y position of the new graphics object. | Source code: [gameobjects/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Graphics.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Graphics.js#L50)) Extends ------- * [PIXI.Graphics](pixi.graphics) * [Phaser.Component.Core](phaser.component.core) * [Phaser.Component.Angle](phaser.component.angle) * [Phaser.Component.AutoCull](phaser.component.autocull) * [Phaser.Component.Bounds](phaser.component.bounds) * [Phaser.Component.Destroy](phaser.component.destroy) * [Phaser.Component.FixedToCamera](phaser.component.fixedtocamera) * [Phaser.Component.InputEnabled](phaser.component.inputenabled) * [Phaser.Component.InWorld](phaser.component.inworld) * [Phaser.Component.LifeSpan](phaser.component.lifespan) * [Phaser.Component.PhysicsBody](phaser.component.physicsbody) * [Phaser.Component.Reset](phaser.component.reset) Public Properties ----------------- ### alive : boolean A useful flag to control if the Game Object is alive or dead. This is set automatically by the Health components `damage` method should the object run out of health. Or you can toggle it via your game code. This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. Inherited From * [Phaser.Component.LifeSpan#alive](phaser.component.lifespan#alive) Default Value * true Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L50)) ### angle : number The angle property is the rotation of the Game Object in *degrees* from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90. If you wish to work in radians instead of degrees you can use the property `rotation` instead. Working in radians is slightly faster as it doesn't have to perform any calculations. Inherited From * [Phaser.Component.Angle#angle](phaser.component.angle#angle) Source code: [gameobjects/components/Angle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js#L29)) ### animations : [Phaser.AnimationManager](phaser.animationmanager) If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. Through it you can create, play, pause and stop animations. Inherited From * [Phaser.Component.Core#animations](phaser.component.core#animations) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 193](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L193)) See * [Phaser.AnimationManager](phaser.animationmanager) ### autoCull : boolean A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, or you have tested performance and find it acceptable. Inherited From * [Phaser.Component.AutoCull#autoCull](phaser.component.autocull#autoCull) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L28)) ### blendMode : number The blend mode to be applied to the graphic shape. Apply a value of PIXI.blendModes.NORMAL to reset the blend mode. Inherited From * [PIXI.Graphics#blendMode](pixi.graphics#blendMode) Default Value * PIXI.blendModes.NORMAL; Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 61](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L61)) ### body : [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | null `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated properties and methods via it. By default Game Objects won't add themselves to any physics system and their `body` property will be `null`. To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`. You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group. Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5, so the physics body is centered on the Game Object. If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics. ##### Type * [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | null Inherited From * [Phaser.Component.PhysicsBody#body](phaser.component.physicsbody#body) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 91](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L91)) ### bottom : number The sum of the y and height properties. This is the same as `y + height - offsetY`. Inherited From * [Phaser.Component.Bounds#bottom](phaser.component.bounds#bottom) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 168](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L168)) ### boundsPadding : number The bounds' padding used for bounds calculation. Inherited From * [PIXI.Graphics#boundsPadding](pixi.graphics#boundsPadding) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 96](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L96)) ### cameraOffset : [Phaser.Point](phaser.point) The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. Inherited From * [Phaser.Component.FixedToCamera#cameraOffset](phaser.component.fixedtocamera#cameraOffset) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L86)) ### centerX : number The center x coordinate of the Game Object. This is the same as `(x - offsetX) + (width / 2)`. Inherited From * [Phaser.Component.Bounds#centerX](phaser.component.bounds#centerX) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L58)) ### centerY : number The center y coordinate of the Game Object. This is the same as `(y - offsetY) + (height / 2)`. Inherited From * [Phaser.Component.Bounds#centerY](phaser.component.bounds#centerY) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 80](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L80)) ### checkWorldBounds : boolean If this is set to `true` the Game Object checks if it is within the World bounds each frame. When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event. If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event. It also optionally kills the Game Object if `outOfBoundsKill` is `true`. When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame. This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, or you have tested performance and find it acceptable. Inherited From * [Phaser.Component.InWorld#checkWorldBounds](phaser.component.inworld#checkWorldBounds) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L98)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### <internal> components : Object The components this Game Object has installed. Inherited From * [Phaser.Component.Core#components](phaser.component.core#components) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 167](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L167)) ### data : Object An empty Object that belongs to this Game Object. This value isn't ever used internally by Phaser, but may be used by your own code, or by Phaser Plugins, to store data that needs to be associated with the Game Object, without polluting the Game Object directly. Inherited From * [Phaser.Component.Core#data](phaser.component.core#data) Default Value * {} Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 160](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L160)) ### debug : boolean A debug flag designed for use with `Game.enableStep`. Inherited From * [Phaser.Component.Core#debug](phaser.component.core#debug) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 218](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L218)) ### [readonly] destroyPhase : boolean As a Game Object runs through its destroy method this flag is set to true, and can be checked in any sub-systems or plugins it is being destroyed from. Inherited From * [Phaser.Component.Destroy#destroyPhase](phaser.component.destroy#destroyPhase) Source code: [gameobjects/components/Destroy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js#L22)) ### events : [Phaser.Events](phaser.events) All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this Game Object, or any of its components. Inherited From * [Phaser.Component.Core#events](phaser.component.core#events) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 185](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L185)) See * [Phaser.Events](phaser.events) ### exists : boolean Controls if this Game Object is processed by the core game loop. If this Game Object has a physics body it also controls if its physics body is updated or not. When `exists` is set to `false` it will remove its physics body from the physics world if it has one. It also toggles the `visible` property to false as well. Setting `exists` to true will add its physics body back in to the physics world, if it has one. It will also set the `visible` property to `true`. Inherited From * [Phaser.Component.Core#exists](phaser.component.core#exists) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 284](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L284)) ### fillAlpha : number The alpha value used when filling the Graphics object. Inherited From * [PIXI.Graphics#fillAlpha](pixi.graphics#fillAlpha) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 18](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L18)) ### fixedToCamera : boolean A Game Object that is "fixed" to the camera uses its x/y coordinates as offsets from the top left of the camera during rendering. The values are adjusted at the rendering stage, overriding the Game Objects actual world position. The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times regardless where in the world the camera is. The offsets are stored in the `cameraOffset` property. Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. Inherited From * [Phaser.Component.FixedToCamera#fixedToCamera](phaser.component.fixedtocamera#fixedToCamera) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 56](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L56)) ### [readonly] fresh : boolean A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. This property is mostly used internally by the physics systems, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#fresh](phaser.component.core#fresh) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 248](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L248)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Inherited From * [Phaser.Component.Core#game](phaser.component.core#game) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 142](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L142)) ### height : number The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#height](pixi.displayobjectcontainer#height) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 600](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L600)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### [readonly] inCamera : boolean Checks if the Game Objects bounds intersect with the Game Camera bounds. Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. Inherited From * [Phaser.Component.AutoCull#inCamera](phaser.component.autocull#inCamera) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L37)) ### input : [Phaser.InputHandler](phaser.inputhandler) | null The Input Handler for this Game Object. By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`. After you have done this, this property will be a reference to the Phaser InputHandler. ##### Type * [Phaser.InputHandler](phaser.inputhandler) | null Inherited From * [Phaser.Component.InputEnabled#input](phaser.component.inputenabled#input) Source code: [gameobjects/components/InputEnabled.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js#L24)) ### inputEnabled : boolean By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created for this Game Object and it will then start to process click / touch events and more. You can then access the Input Handler via `this.input`. Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`. If you set this property to false it will stop the Input Handler from processing any more input events. If you want to *temporarily* disable input for a Game Object, then it's better to set `input.enabled = false`, as it won't reset any of the Input Handlers internal properties. You can then toggle this back on as needed. Inherited From * [Phaser.Component.InputEnabled#inputEnabled](phaser.component.inputenabled#inputEnabled) Source code: [gameobjects/components/InputEnabled.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js#L42)) ### [readonly] inWorld : boolean Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds. Inherited From * [Phaser.Component.InWorld#inWorld](phaser.component.inworld#inWorld) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 129](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L129)) ### isMask : boolean Whether this shape is being used as a mask. Inherited From * [PIXI.Graphics#isMask](pixi.graphics#isMask) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 88](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L88)) ### key : string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) The key of the image or texture used by this Game Object during rendering. If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. ##### Type * string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) Inherited From * [Phaser.Component.Core#key](phaser.component.core#key) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 203](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L203)) ### left : number The left coordinate of the Game Object. This is the same as `x - offsetX`. Inherited From * [Phaser.Component.Bounds#left](phaser.component.bounds#left) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 102](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L102)) ### lifespan : number The lifespan allows you to give a Game Object a lifespan in milliseconds. Once the Game Object is 'born' you can set this to a positive value. It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. When it reaches zero it will call the `kill` method. Very handy for particles, bullets, collectibles, or any other short-lived entity. Inherited From * [Phaser.Component.LifeSpan#lifespan](phaser.component.lifespan#lifespan) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 65](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L65)) ### lineColor : string The color of any lines drawn. Inherited From * [PIXI.Graphics#lineColor](pixi.graphics#lineColor) Default Value * 0 Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 34](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L34)) ### lineWidth : number The width (thickness) of any lines drawn. Inherited From * [PIXI.Graphics#lineWidth](pixi.graphics#lineWidth) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L26)) ### name : string A user defined name given to this Game Object. This value isn't ever used internally by Phaser, it is meant as a game level property. Inherited From * [Phaser.Component.Core#name](phaser.component.core#name) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 150](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L150)) ### [readonly] offsetX : number The amount the Game Object is visually offset from its x coordinate. This is the same as `width * anchor.x`. It will only be > 0 if anchor.x is not equal to zero. Inherited From * [Phaser.Component.Bounds#offsetX](phaser.component.bounds#offsetX) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L24)) ### [readonly] offsetY : number The amount the Game Object is visually offset from its y coordinate. This is the same as `height * anchor.y`. It will only be > 0 if anchor.y is not equal to zero. Inherited From * [Phaser.Component.Bounds#offsetY](phaser.component.bounds#offsetY) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L42)) ### outOfBoundsKill : boolean If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false. Inherited From * [Phaser.Component.InWorld#outOfBoundsKill](phaser.component.inworld#outOfBoundsKill) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 106](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L106)) ### outOfCameraBoundsKill : boolean If this and the `autoCull` property are both set to `true`, then the `kill` method is called as soon as the Game Object leaves the camera bounds. Inherited From * [Phaser.Component.InWorld#outOfCameraBoundsKill](phaser.component.inworld#outOfCameraBoundsKill) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 115](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L115)) ### pendingDestroy : boolean A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. You can set it directly to allow you to flag an object to be destroyed on its next update. This is extremely useful if you wish to destroy an object from within one of its own callbacks such as with Buttons or other Input events. Inherited From * [Phaser.Component.Core#pendingDestroy](phaser.component.core#pendingDestroy) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 259](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L259)) ### [readonly] physicsType : number The const physics body type of this object. Source code: [gameobjects/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Graphics.js) ([Line 65](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Graphics.js#L65)) ### [readonly] previousPosition : [Phaser.Point](phaser.point) The position the Game Object was located in the previous frame. Inherited From * [Phaser.Component.Core#previousPosition](phaser.component.core#previousPosition) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 225](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L225)) ### [readonly] previousRotation : number The rotation the Game Object was in set to in the previous frame. Value is in radians. Inherited From * [Phaser.Component.Core#previousRotation](phaser.component.core#previousRotation) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L232)) ### [readonly] renderOrderID : number The render order ID is used internally by the renderer and Input Manager and should not be modified. This property is mostly used internally by the renderers, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#renderOrderID](phaser.component.core#renderOrderID) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 240](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L240)) ### right : number The right coordinate of the Game Object. This is the same as `x + width - offsetX`. Inherited From * [Phaser.Component.Bounds#right](phaser.component.bounds#right) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L124)) ### tint : number The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to reset the tint. Inherited From * [PIXI.Graphics#tint](pixi.graphics#tint) Default Value * 0xFFFFFF Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 52](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L52)) ### top : number The y coordinate of the Game Object. This is the same as `y - offsetY`. Inherited From * [Phaser.Component.Bounds#top](phaser.component.bounds#top) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 146](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L146)) ### type : number The const type of this object. Source code: [gameobjects/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Graphics.js) ([Line 59](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Graphics.js#L59)) ### width : number The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#width](pixi.displayobjectcontainer#width) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 571](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L571)) ### world : [Phaser.Point](phaser.point) The world coordinates of this Game Object in pixels. Depending on where in the display list this Game Object is placed this value can differ from `position`, which contains the x/y coordinates relative to the Game Objects parent. Inherited From * [Phaser.Component.Core#world](phaser.component.core#world) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 211](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L211)) ### x : number The position of the Game Object on the x axis relative to the local coordinates of the parent. Inherited From * [Phaser.Component.PhysicsBody#x](phaser.component.physicsbody#x) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L98)) ### y : number The position of the Game Object on the y axis relative to the local coordinates of the parent. Inherited From * [Phaser.Component.PhysicsBody#y](phaser.component.physicsbody#y) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L124)) ### [readonly] z : number The z depth of this Game Object within its parent Group. No two objects in a Group can have the same z value. This value is adjusted automatically whenever the Group hierarchy changes. If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. Inherited From * [Phaser.Component.Core#z](phaser.component.core#z) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 177](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L177)) Public Methods -------------- ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### alignIn(container, position, offsetX, offsetY) → {Object} Aligns this Game Object within another Game Object, or Rectangle, known as the 'container', to one of 9 possible positions. The container must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the container. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the container, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `container` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Inherited From * [Phaser.Component.Bounds#alignIn](phaser.component.bounds#alignIn) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 223](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L223)) ### alignTo(parent, position, offsetX, offsetY) → {Object} Aligns this Game Object to the side of another Game Object, or Rectangle, known as the 'parent', in one of 11 possible positions. The parent must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the parent. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the parent, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Inherited From * [Phaser.Component.Bounds#alignTo](phaser.component.bounds#alignTo) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 321](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L321)) ### arc(cx, cy, radius, startAngle, endAngle, anticlockwise, segments) → {[PIXI.Graphics](pixi.graphics)} The arc method creates an arc/curve (used to create circles, or parts of circles). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `cx` | Number | The x-coordinate of the center of the circle | | `cy` | Number | The y-coordinate of the center of the circle | | `radius` | Number | The radius of the circle | | `startAngle` | Number | The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle) | | `endAngle` | Number | The ending angle, in radians | | `anticlockwise` | Boolean | Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. | | `segments` | Number | Optional. The number of segments to use when calculating the arc. The default is 40. If you need more fidelity use a higher number. | ##### Returns [PIXI.Graphics](pixi.graphics) - Inherited From * [PIXI.Graphics#arc](pixi.graphics#arc) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 405](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L405)) ### beginFill(color, alpha) → {[PIXI.Graphics](pixi.graphics)} Specifies a simple one-color fill that subsequent calls to other Graphics methods (such as lineTo() or drawCircle()) use when drawing. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `color` | Number | the color of the fill | | `alpha` | Number | the alpha of the fill | ##### Returns [PIXI.Graphics](pixi.graphics) - Inherited From * [PIXI.Graphics#beginFill](pixi.graphics#beginFill) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 491](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L491)) ### bezierCurveTo(cpX, cpY, cpX2, cpY2, toX, toY) → {[PIXI.Graphics](pixi.graphics)} Calculate the points for a bezier curve and then draws it. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `cpX` | Number | Control point x | | `cpY` | Number | Control point y | | `cpX2` | Number | Second Control point x | | `cpY2` | Number | Second Control point y | | `toX` | Number | Destination point x | | `toY` | Number | Destination point y | ##### Returns [PIXI.Graphics](pixi.graphics) - Inherited From * [PIXI.Graphics#bezierCurveTo](pixi.graphics#bezierCurveTo) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 276](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L276)) ### clear() → {[PIXI.Graphics](pixi.graphics)} Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. ##### Returns [PIXI.Graphics](pixi.graphics) - Inherited From * [PIXI.Graphics#clear](pixi.graphics#clear) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 633](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L633)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### destroy(destroyChildren) Destroy this Graphics instance. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroyChildren` | boolean | <optional> | true | Should every child of this object have its destroy method called? | Source code: [gameobjects/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Graphics.js) ([Line 139](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Graphics.js#L139)) ### destroyCachedSprite() Destroys a previous cached sprite. Inherited From * [PIXI.Graphics#destroyCachedSprite](pixi.graphics#destroyCachedSprite) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 1173](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L1173)) ### drawCircle(x, y, diameter) → {[PIXI.Graphics](pixi.graphics)} Draws a circle. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | Number | The X coordinate of the center of the circle | | `y` | Number | The Y coordinate of the center of the circle | | `diameter` | Number | The diameter of the circle | ##### Returns [PIXI.Graphics](pixi.graphics) - Inherited From * [PIXI.Graphics#drawCircle](pixi.graphics#drawCircle) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 565](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L565)) ### drawEllipse(x, y, width, height) → {[PIXI.Graphics](pixi.graphics)} Draws an ellipse. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | Number | The X coordinate of the center of the ellipse | | `y` | Number | The Y coordinate of the center of the ellipse | | `width` | Number | The half width of the ellipse | | `height` | Number | The half height of the ellipse | ##### Returns [PIXI.Graphics](pixi.graphics) - Inherited From * [PIXI.Graphics#drawEllipse](pixi.graphics#drawEllipse) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 581](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L581)) ### drawPolygon(path) → {[PIXI.Graphics](pixi.graphics)} Draws a polygon using the given path. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `path` | Array | PhaserPolygon | The path data used to construct the polygon. Can either be an array of points or a Phaser.Polygon object. | ##### Returns [PIXI.Graphics](pixi.graphics) - Inherited From * [PIXI.Graphics#drawPolygon](pixi.graphics#drawPolygon) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 598](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L598)) ### drawRect(x, y, width, height) → {[PIXI.Graphics](pixi.graphics)} ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | Number | The X coord of the top-left of the rectangle | | `y` | Number | The Y coord of the top-left of the rectangle | | `width` | Number | The width of the rectangle | | `height` | Number | The height of the rectangle | ##### Returns [PIXI.Graphics](pixi.graphics) - Inherited From * [PIXI.Graphics#drawRect](pixi.graphics#drawRect) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 534](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L534)) ### drawRoundedRect(x, y, width, height, radius) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | Number | The X coord of the top-left of the rectangle | | `y` | Number | The Y coord of the top-left of the rectangle | | `width` | Number | The width of the rectangle | | `height` | Number | The height of the rectangle | | `radius` | Number | Radius of the rectangle corners. In WebGL this must be a value between 0 and 9. | Inherited From * [PIXI.Graphics#drawRoundedRect](pixi.graphics#drawRoundedRect) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 550](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L550)) ### drawShape(shape) → {[PIXI.GraphicsData](pixi.graphicsdata)} Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `shape` | Circle | Rectangle | Ellipse | Line | Polygon | The Shape object to draw. | ##### Returns [PIXI.GraphicsData](pixi.graphicsdata) - The generated GraphicsData object. Inherited From * [PIXI.Graphics#drawShape](pixi.graphics#drawShape) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 1184](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L1184)) ### endFill() → {[PIXI.Graphics](pixi.graphics)} Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. ##### Returns [PIXI.Graphics](pixi.graphics) - Inherited From * [PIXI.Graphics#endFill](pixi.graphics#endFill) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 519](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L519)) ### generateTexture(resolution, scaleMode, padding) → {[PIXI.Texture](pixi.texture)} Useful function that returns a texture of the graphics object that can then be used to create sprites This can be quite useful if your geometry is complicated and needs to be reused multiple times. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `resolution` | Number | <optional> | 1 | The resolution of the texture being generated | | `scaleMode` | Number | <optional> | 0 | Should be one of the PIXI.scaleMode consts | | `padding` | Number | <optional> | 0 | Add optional extra padding to the generated texture (default 0) | ##### Returns [PIXI.Texture](pixi.texture) - a texture of the graphics object Inherited From * [PIXI.Graphics#generateTexture](pixi.graphics#generateTexture) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 654](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L654)) ### getBounds() → {Rectangle} Retrieves the bounds of the graphic shape as a rectangle object ##### Returns Rectangle - the rectangular bounding area Inherited From * [PIXI.Graphics#getBounds](pixi.graphics#getBounds) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 848](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L848)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the graphic shape as a rectangle. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.Graphics#getLocalBounds](pixi.graphics#getLocalBounds) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 936](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L936)) ### kill() → {PIXI.DisplayObject} Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false. It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal. Note that killing a Game Object is a way for you to quickly recycle it in an object pool, it doesn't destroy the object or free it up from memory. If you don't need this Game Object any more you should call `destroy` instead. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.LifeSpan#kill](phaser.component.lifespan#kill) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 113](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L113)) ### lineStyle(lineWidth, color, alpha) → {[PIXI.Graphics](pixi.graphics)} Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `lineWidth` | Number | width of the line to draw, will update the objects stored style | | `color` | Number | color of the line to draw, will update the objects stored style | | `alpha` | Number | alpha of the line to draw, will update the objects stored style | ##### Returns [PIXI.Graphics](pixi.graphics) - Inherited From * [PIXI.Graphics#lineStyle](pixi.graphics#lineStyle) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 149](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L149)) ### lineTo(x, y) → {[PIXI.Graphics](pixi.graphics)} Draws a line using the current line style from the current drawing position to (x, y); The current drawing position is then set to (x, y). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | Number | the X coordinate to draw to | | `y` | Number | the Y coordinate to draw to | ##### Returns [PIXI.Graphics](pixi.graphics) - Inherited From * [PIXI.Graphics#lineTo](pixi.graphics#lineTo) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 198](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L198)) ### moveTo(x, y) → {[PIXI.Graphics](pixi.graphics)} Moves the current drawing position to x, y. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | Number | the X coordinate to move to | | `y` | Number | the Y coordinate to move to | ##### Returns [PIXI.Graphics](pixi.graphics) - Inherited From * [PIXI.Graphics#moveTo](pixi.graphics#moveTo) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 183](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L183)) ### postUpdate() Automatically called by World Source code: [gameobjects/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Graphics.js) ([Line 117](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Graphics.js#L117)) ### preUpdate() Automatically called by World.preUpdate. Source code: [gameobjects/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Graphics.js) ([Line 106](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Graphics.js#L106)) ### quadraticCurveTo(cpX, cpY, toX, toY) → {[PIXI.Graphics](pixi.graphics)} Calculate the points for a quadratic bezier curve and then draws it. Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c ##### Parameters | Name | Type | Description | | --- | --- | --- | | `cpX` | Number | Control point x | | `cpY` | Number | Control point y | | `toX` | Number | Destination point x | | `toY` | Number | Destination point y | ##### Returns [PIXI.Graphics](pixi.graphics) - Inherited From * [PIXI.Graphics#quadraticCurveTo](pixi.graphics#quadraticCurveTo) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 221](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L221)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### reset(x, y, health) → {PIXI.DisplayObject} Resets the Game Object. This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`, `visible` and `renderable` to true. If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value. If this Game Object has a Physics Body it will reset the Body. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate (in world space) to position the Game Object at. | | `y` | number | | | The y coordinate (in world space) to position the Game Object at. | | `health` | number | <optional> | 1 | The health to give the Game Object if it has the Health component. | ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.Reset#reset](phaser.component.reset#reset) Source code: [gameobjects/components/Reset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Reset.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Reset.js#L30)) ### revive(health) → {PIXI.DisplayObject} Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `health` | number | <optional> | 100 | The health to give the Game Object. Only set if the GameObject has the Health component. | ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.LifeSpan#revive](phaser.component.lifespan#revive) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L78)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) ### update() Override this method in your own custom objects to handle any update requirements. It is called immediately after `preUpdate` and before `postUpdate`. Remember if this Game Object has any children you should call update on those too. Inherited From * [Phaser.Component.Core#update](phaser.component.core#update) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 328](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L328)) ### updateLocalBounds() Update the bounds of the object Inherited From * [PIXI.Graphics#updateLocalBounds](pixi.graphics#updateLocalBounds) Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 997](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L997))
programming_docs
phaser Class: Phaser.Easing.Cubic Class: Phaser.Easing.Cubic ========================== Constructor ----------- ### new Cubic() Cubic easing. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 92](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L92)) Public Methods -------------- ### In(k) → {number} Cubic ease-in. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 94](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L94)) ### InOut(k) → {number} Cubic ease-in/out. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 120](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L120)) ### Out(k) → {number} Cubic ease-out. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 107](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L107)) phaser Class: Phaser.Easing.Exponential Class: Phaser.Easing.Exponential ================================ Constructor ----------- ### new Exponential() Exponential easing. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 293](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L293)) Public Methods -------------- ### In(k) → {number} Exponential ease-in. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 295](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L295)) ### InOut(k) → {number} Exponential ease-in/out. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 321](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L321)) ### Out(k) → {number} Exponential ease-out. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 308](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L308)) phaser Class: Phaser.Particles Class: Phaser.Particles ======================= Constructor ----------- ### new Particles(game) Phaser.Particles is the Particle Manager for the game. It is called during the game update loop and in turn updates any Emitters attached to it. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | Source code: [particles/Particles.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/Particles.js) ([Line 14](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/Particles.js#L14)) Classes ------- [Arcade](phaser.particles.arcade) Public Properties ----------------- ### emitters : Object Internal emitters store. Source code: [particles/Particles.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/Particles.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/Particles.js#L24)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Source code: [particles/Particles.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/Particles.js) ([Line 19](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/Particles.js#L19)) ### ID : number - Source code: [particles/Particles.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/Particles.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/Particles.js#L30)) Public Methods -------------- ### add(emitter) → {Phaser.Emitter} Adds a new Particle Emitter to the Particle Manager. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `emitter` | Phaser.Emitter | The emitter to be added to the particle manager. | ##### Returns Phaser.Emitter - The emitter that was added. Source code: [particles/Particles.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/Particles.js) ([Line 36](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/Particles.js#L36)) ### remove(emitter) Removes an existing Particle Emitter from the Particle Manager. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `emitter` | Phaser.Emitter | The emitter to remove. | Source code: [particles/Particles.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/Particles.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/Particles.js#L50)) ### <internal> update() Called by the core game loop. Updates all Emitters who have their exists value set to true. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [particles/Particles.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/Particles.js) ([Line 61](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/Particles.js#L61)) phaser Class: Phaser.Camera Class: Phaser.Camera ==================== Constructor ----------- ### new Camera(game, id, x, y, width, height) A Camera is your view into the game world. It has a position and size and renders only those objects within its field of view. The game automatically creates a single Stage sized camera on boot. Move the camera around the world with Phaser.Camera.x/y ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | Game reference to the currently running game. | | `id` | number | Not being used at the moment, will be when Phaser supports multiple camera | | `x` | number | Position of the camera on the X axis | | `y` | number | Position of the camera on the Y axis | | `width` | number | The width of the view rectangle | | `height` | number | The height of the view rectangle | Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L20)) Public Properties ----------------- ### [static] ENABLE\_FX : boolean Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 231](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L231)) ### [static] FOLLOW\_LOCKON : number Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 189](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L189)) ### [static] FOLLOW\_PLATFORMER : number Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 195](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L195)) ### [static] FOLLOW\_TOPDOWN : number Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 201](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L201)) ### [static] FOLLOW\_TOPDOWN\_TIGHT : number Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 207](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L207)) ### [static] SHAKE\_BOTH : number Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L213)) ### [static] SHAKE\_HORIZONTAL : number Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 219](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L219)) ### [static] SHAKE\_VERTICAL : number Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 225](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L225)) ### atLimit : boolean Whether this camera is flush with the World Bounds or not. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 76](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L76)) ### bounds : [Phaser.Rectangle](phaser.rectangle) The Camera is bound to this Rectangle and cannot move outside of it. By default it is enabled and set to the size of the World. The Rectangle can be located anywhere in the world and updated as often as you like. If you don't wish the Camera to be bound at all then set this to null. The values can be anything and are in World coordinates, with 0,0 being the top-left of the world. The Rectangle in which the Camera is bounded. Set to null to allow for movement anywhere. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L54)) ### deadzone : [Phaser.Rectangle](phaser.rectangle) Moving inside this Rectangle will not cause the camera to move. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 59](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L59)) ### displayObject :PIXI.DisplayObject The display object to which all game objects are added. Set by World.boot. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L87)) ### <internal> fx : [Phaser.Graphics](phaser.graphics) The Graphics object used to handle camera fx such as fade and flash. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 135](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L135)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 25](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L25)) ### height : number The Cameras height. By default this is the same as the Game size and should not be adjusted for now. Gets or sets the cameras height. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 898](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L898)) ### id : number Reserved for future multiple camera set-ups. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 36](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L36)) ### lerp : [Phaser.Point](phaser.point) The linear interpolation value to use when following a target. The default values of 1 means the camera will instantly snap to the target coordinates. A lower value, such as 0.1 means the camera will more slowly track the target, giving a smooth transition. You can set the horizontal and vertical values independently, and also adjust this value in real-time during your game. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 109](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L109)) ### onFadeComplete : [Phaser.Signal](phaser.signal) This signal is dispatched when the camera fade effect completes. When the fade effect completes you will be left with the screen black (or whatever color you faded to). In order to reset this call `Camera.resetFX`. This is called automatically when you change State. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 128](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L128)) ### onFlashComplete : [Phaser.Signal](phaser.signal) This signal is dispatched when the camera flash effect completes. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 119](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L119)) ### onShakeComplete : [Phaser.Signal](phaser.signal) This signal is dispatched when the camera shake effect completes. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 114](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L114)) ### position : [Phaser.Point](phaser.point) The Cameras position. This value is automatically clamped if it falls outside of the World bounds. Gets or sets the cameras xy position using Phaser.Point object. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 849](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L849)) ### roundPx : boolean If a Camera has roundPx set to `true` it will call `view.floor` as part of its update loop, keeping its boundary to integer values. Set this to `false` to disable this from happening. Default Value * true Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 71](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L71)) ### scale : [Phaser.Point](phaser.point) The scale of the display object to which all game objects are added. Set by World.boot. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 92](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L92)) ### shakeIntensity : number The Cameras shake intensity. Gets or sets the cameras shake intensity. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 920](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L920)) ### target : [Phaser.Sprite](phaser.sprite) If the camera is tracking a Sprite, this is a reference to it, otherwise null. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 82](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L82)) ### [readonly] totalInView : number The total number of Sprites with `autoCull` set to `true` that are visible by this Camera. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L98)) ### view : [Phaser.Rectangle](phaser.rectangle) Camera view. The view into the world we wish to render (by default the game dimensions). The x/y values are in world coordinates, not screen coordinates, the width/height is how many pixels to render. Sprites outside of this view are not rendered if Sprite.autoCull is set to `true`. Otherwise they are always rendered. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L45)) ### visible : boolean Whether this camera is visible or not. Default Value * true Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 65](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L65)) ### width : number The Cameras width. By default this is the same as the Game size and should not be adjusted for now. Gets or sets the cameras width. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 877](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L877)) ### world : [Phaser.World](phaser.world) A reference to the game world. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L30)) ### x : number The Cameras x coordinate. This value is automatically clamped if it falls outside of the World bounds. Gets or sets the cameras x position. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 799](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L799)) ### y : number The Cameras y coordinate. This value is automatically clamped if it falls outside of the World bounds. Gets or sets the cameras y position. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 824](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L824)) Public Methods -------------- ### <internal> checkBounds() Method called to ensure the camera doesn't venture outside of the game world. Called automatically by Camera.update. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 657](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L657)) ### fade(color, duration, force) → {boolean} This creates a camera fade effect. It works by filling the game with the color specified, over the duration given, ending with a solid fill. You can use this for things such as transitioning to a new scene. The game will be left 'filled' at the end of this effect, likely obscuring everything. In order to reset it you can call `Camera.resetFX` and it will clear the fade. Or you can call `Camera.flash` with the same color as the fade, and it will reverse the process, bringing the game back into view again. When the effect ends the signal Camera.onFadeComplete is dispatched. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `color` | numer | <optional> | 0x000000 | The color the game will fade to. I.e. 0x000000 for black, 0xff0000 for red, etc. | | `duration` | number | <optional> | 500 | The duration of the fade in milliseconds. | | `force` | boolean | <optional> | false | If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration. | ##### Returns boolean - True if the effect was started, otherwise false. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 441](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L441)) ### flash(color, duration, force) → {boolean} This creates a camera flash effect. It works by filling the game with the solid fill color specified, and then fading it away to alpha 0 over the duration given. You can use this for things such as hit feedback effects. When the effect ends the signal Camera.onFlashComplete is dispatched. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `color` | numer | <optional> | 0xffffff | The color of the flash effect. I.e. 0xffffff for white, 0xff0000 for red, etc. | | `duration` | number | <optional> | 500 | The duration of the flash effect in milliseconds. | | `force` | boolean | <optional> | false | If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration. | ##### Returns boolean - True if the effect was started, otherwise false. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 401](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L401)) ### focusOn(displayObject) Move the camera focus on a display object instantly. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `displayObject` | any | The display object to focus the camera on. Must have visible x/y properties. | Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 335](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L335)) ### focusOnXY(x, y) Move the camera focus on a location instantly. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | X position. | | `y` | number | Y position. | Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 346](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L346)) ### follow(target, style, lerpX, lerpY) Tell the camera which sprite to follow. You can set the follow type and a linear interpolation value. Use low lerp values (such as 0.1) to automatically smooth the camera motion. If you find you're getting a slight "jitter" effect when following a Sprite it's probably to do with sub-pixel rendering of the Sprite position. This can be disabled by setting `game.renderer.renderSession.roundPixels = true` to force full pixel rendering. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `target` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | | | The object you want the camera to track. Set to null to not follow anything. | | `style` | number | <optional> | | Leverage one of the existing "deadzone" presets. If you use a custom deadzone, ignore this parameter and manually specify the deadzone after calling follow(). | | `lerpX` | float | <optional> | 1 | A value between 0 and 1. This value specifies the amount of linear interpolation to use when horizontally tracking the target. The closer the value to 1, the faster the camera will track. | | `lerpY` | float | <optional> | 1 | A value between 0 and 1. This value specifies the amount of linear interpolation to use when vertically tracking the target. The closer the value to 1, the faster the camera will track. | Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 269](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L269)) ### preUpdate() Camera preUpdate. Sets the total view counter to zero. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 258](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L258)) ### reset() Resets the camera back to 0,0 and un-follows any object it may have been tracking. Also immediately resets any camera effects that may have been running such as shake, flash or fade. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 759](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L759)) ### resetFX() Resets any active FX, such as a fade or flash and immediately clears it. Useful to calling after a fade in order to remove the fade from the Stage. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 779](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L779)) ### setBoundsToWorld() Update the Camera bounds to match the game world. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 643](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L643)) ### setPosition(x, y) A helper function to set both the X and Y properties of the camera at once without having to use game.camera.x and game.camera.y. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | X position. | | `y` | number | Y position. | Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 725](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L725)) ### setSize(width, height) Sets the size of the view rectangle given the width and height in parameters. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `width` | number | The desired width. | | `height` | number | The desired height. | Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 745](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L745)) ### shake(intensity, duration, force, direction, shakeBounds) → {boolean} This creates a camera shake effect. It works by applying a random amount of additional spacing on the x and y axis each frame. You can control the intensity and duration of the effect, and if it should effect both axis or just one. When the shake effect ends the signal Camera.onShakeComplete is dispatched. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `intensity` | float | <optional> | 0.05 | The intensity of the camera shake. Given as a percentage of the camera size representing the maximum distance that the camera can move while shaking. | | `duration` | number | <optional> | 500 | The duration of the shake effect in milliseconds. | | `force` | boolean | <optional> | true | If a camera shake effect is already running and force is true it will replace the previous effect, resetting the duration. | | `direction` | number | <optional> | Phaser.Camera.SHAKE\_BOTH | The directions in which the camera can shake. Either Phaser.Camera.SHAKE\_BOTH, Phaser.Camera.SHAKE\_HORIZONTAL or Phaser.Camera.SHAKE\_VERTICAL. | | `shakeBounds` | boolean | <optional> | true | Is the effect allowed to shake the camera beyond its bounds (if set?). | ##### Returns boolean - True if the shake effect was started, otherwise false. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 358](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L358)) ### unfollow() Sets the Camera follow target to null, stopping it from following an object if it's doing so. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 324](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L324)) ### <internal> update() The camera update loop. This is called automatically by the core game loop. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Camera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js) ([Line 486](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Camera.js#L486))
programming_docs
phaser Class: Phaser.Physics.P2.PointProxy Class: Phaser.Physics.P2.PointProxy =================================== Constructor ----------- ### new PointProxy(world, destination) A PointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `world` | [Phaser.Physics.P2](phaser.physics.p2) | A reference to the P2 World. | | `destination` | any | The object to bind to. | Source code: [physics/p2/PointProxy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/PointProxy.js) ([Line 15](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/PointProxy.js#L15)) Public Properties ----------------- ### mx : number The x property of this PointProxy get and set in meters. Source code: [physics/p2/PointProxy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/PointProxy.js) ([Line 64](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/PointProxy.js#L64)) ### my : number The x property of this PointProxy get and set in meters. Source code: [physics/p2/PointProxy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/PointProxy.js) ([Line 84](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/PointProxy.js#L84)) ### x : number The x property of this PointProxy get and set in pixels. Source code: [physics/p2/PointProxy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/PointProxy.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/PointProxy.js#L24)) ### y : number The y property of this PointProxy get and set in pixels. Source code: [physics/p2/PointProxy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/PointProxy.js) ([Line 44](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/PointProxy.js#L44)) phaser Class: Phaser.Physics.P2.DistanceConstraint Class: Phaser.Physics.P2.DistanceConstraint =========================================== Constructor ----------- ### new DistanceConstraint(world, bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce) A constraint that tries to keep the distance between two bodies constant. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `world` | [Phaser.Physics.P2](phaser.physics.p2) | | | A reference to the P2 World. | | `bodyA` | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | First connected body. | | `bodyB` | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | Second connected body. | | `distance` | number | | | The distance to keep between the bodies. | | `localAnchorA` | Array | <optional> | | The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0]. | | `localAnchorB` | Array | <optional> | | The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0]. | | `maxForce` | object | <optional> | Number.MAX\_VALUE | Maximum force to apply. | Source code: [physics/p2/DistanceConstraint.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/DistanceConstraint.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/DistanceConstraint.js#L20)) Public Properties ----------------- ### game : [Phaser.Game](phaser.game) Local reference to game. Source code: [physics/p2/DistanceConstraint.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/DistanceConstraint.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/DistanceConstraint.js#L30)) ### world : [Phaser.Physics.P2](phaser.physics.p2) Local reference to P2 World. Source code: [physics/p2/DistanceConstraint.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/DistanceConstraint.js) ([Line 35](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/DistanceConstraint.js#L35)) phaser Class: Phaser.Game Class: Phaser.Game ================== Constructor ----------- ### new Game(width, height, renderer, parent, state, transparent, antialias, physicsConfig) This is where the magic happens. The Game object is the heart of your game, providing quick access to common functions and handling the boot process. "Hell, there are no rules here - we're trying to accomplish something." Thomas A. Edison ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `width` | number | string | <optional> | 800 | The width of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage width of the parent container, or the browser window if no parent is given. | | `height` | number | string | <optional> | 600 | The height of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage height of the parent container, or the browser window if no parent is given. | | `renderer` | number | <optional> | Phaser.AUTO | Which renderer to use: Phaser.AUTO will auto-detect, Phaser.WEBGL, Phaser.CANVAS or Phaser.HEADLESS (no rendering at all). | | `parent` | string | HTMLElement | <optional> | '' | The DOM element into which this games canvas will be injected. Either a DOM ID (string) or the element itself. | | `state` | object | <optional> | null | The default state object. A object consisting of Phaser.State functions (preload, create, update, render) or null. | | `transparent` | boolean | <optional> | false | Use a transparent canvas background or not. | | `antialias` | boolean | <optional> | true | Draw all image textures anti-aliased or not. The default is for smooth textures, but disable if your game features pixel art. | | `physicsConfig` | object | <optional> | null | A physics configuration object to pass to the Physics world on creation. | Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 25](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L25)) Public Properties ----------------- ### add : [Phaser.GameObjectFactory](phaser.gameobjectfactory) Reference to the Phaser.GameObjectFactory. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 156](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L156)) ### antialias : boolean Anti-alias graphics. By default scaled images are smoothed in Canvas and WebGL, set anti-alias to false to disable this globally. Default Value * true Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 102](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L102)) ### cache : [Phaser.Cache](phaser.cache) Reference to the assets cache. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 166](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L166)) ### camera : [Phaser.Camera](phaser.camera) A handy reference to world.camera. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 241](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L241)) ### canvas :HTMLCanvasElement A handy reference to renderer.view, the canvas that the game is being rendered in to. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 246](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L246)) ### clearBeforeRender : boolean Clear the Canvas each frame before rendering the display list. You can set this to `false` to gain some performance if your game always contains a background that completely fills the display. Default Value * true Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 116](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L116)) ### config : Object The Phaser.Game configuration object. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 36](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L36)) ### context :CanvasRenderingContext2D A handy reference to renderer.context (only set for CANVAS games, not WebGL) Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 251](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L251)) ### create : [Phaser.Create](phaser.create) The Asset Generator. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 266](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L266)) ### <internal> currentUpdateID : integer The ID of the current/last logic update applied this render frame, starting from 0. The first update is `currentUpdateID === 0` and the last update is `currentUpdateID === updatesThisFrame.` Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 336](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L336)) ### debug : [Phaser.Utils.Debug](phaser.utils.debug) A set of useful debug utilities. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 256](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L256)) ### device : [Phaser.Device](phaser.device) Contains device information and capabilities. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 236](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L236)) ### forceSingleUpdate : boolean Should the game loop force a logic update, regardless of the delta timer? Set to true if you know you need this. You can toggle it on the fly. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 380](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L380)) ### fpsProblemNotifier : [Phaser.Signal](phaser.signal) If the game is struggling to maintain the desired FPS, this signal will be dispatched. The desired/chosen FPS should probably be closer to the [Phaser.Time#suggestedFps](phaser.time#suggestedFps) value. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 375](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L375)) ### [readonly] height : integer The current Game Height in pixels. *Do not modify this property directly:* use [Phaser.ScaleManager#setGameSize](phaser.scalemanager#setGameSize) - eg. `game.scale.setGameSize(width, height)` - instead. Default Value * 600 Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 69](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L69)) ### [readonly] id : number Phaser Game ID (for when Pixi supports multiple instances). Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 31](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L31)) ### input : [Phaser.Input](phaser.input) Reference to the input manager Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L171)) ### [readonly] isBooted : boolean Whether the game engine is booted, aka available. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 139](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L139)) ### [readonly] isRunning : boolean Is game running or paused? Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 145](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L145)) ### load : [Phaser.Loader](phaser.loader) Reference to the assets loader. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 176](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L176)) ### lockRender : boolean If `false` Phaser will automatically render the display list every update. If `true` the render loop will be skipped. You can toggle this value at run-time to gain exact control over when Phaser renders. This can be useful in certain types of game or application. Please note that if you don't render the display list then none of the game object transforms will be updated, so use this value carefully. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 275](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L275)) ### make : [Phaser.GameObjectCreator](phaser.gameobjectcreator) Reference to the GameObject Creator. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 161](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L161)) ### math : [Phaser.Math](phaser.math) Reference to the math helper. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 181](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L181)) ### net : [Phaser.Net](phaser.net) Reference to the network class. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 186](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L186)) ### onBlur : [Phaser.Signal](phaser.signal) This event is fired when the game no longer has focus (typically on page hide). Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 311](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L311)) ### onFocus : [Phaser.Signal](phaser.signal) This event is fired when the game has focus (typically on page show). Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 316](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L316)) ### onPause : [Phaser.Signal](phaser.signal) This event is fired when the game pauses. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 301](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L301)) ### onResume : [Phaser.Signal](phaser.signal) This event is fired when the game resumes from a paused state. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 306](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L306)) ### parent : string | HTMLElement The Games DOM parent. ##### Type * string | HTMLElement Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 47](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L47)) ### particles : [Phaser.Particles](phaser.particles) The Particle Manager. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 261](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L261)) ### paused : boolean The paused state of the Game. A paused game doesn't update any of its subsystems. When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched. Gets and sets the paused state of the Game. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 1154](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L1154)) ### [readonly] pendingStep : boolean An internal property used by enableStep, but also useful to query from your own game objects. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 289](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L289)) ### physics : [Phaser.Physics](phaser.physics) Reference to the physics manager. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 221](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L221)) ### physicsConfig : Object The Phaser.Physics.World configuration object. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 41](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L41)) ### plugins : [Phaser.PluginManager](phaser.pluginmanager) Reference to the plugin manager. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 226](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L226)) ### preserveDrawingBuffer : boolean The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 108](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L108)) ### <internal> raf : [Phaser.RequestAnimationFrame](phaser.requestanimationframe) Automatically handles the core game loop via requestAnimationFrame or setTimeout Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 151](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L151)) ### <internal> renderer : [PIXI.CanvasRenderer](pixi.canvasrenderer) | [PIXI.WebGLRenderer](pixi.webglrenderer) The Pixi Renderer. ##### Type * [PIXI.CanvasRenderer](pixi.canvasrenderer) | [PIXI.WebGLRenderer](pixi.webglrenderer) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 122](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L122)) ### [readonly] renderType : number The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS, Phaser.WEBGL, or Phaser.HEADLESS. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 128](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L128)) ### [readonly] resolution : integer The resolution of your game. This value is read only, but can be changed at start time it via a game configuration object. Default Value * 1 Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L78)) ### rnd : [Phaser.RandomDataGenerator](phaser.randomdatagenerator) Instance of repeatable random data generator helper. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 231](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L231)) ### scale : [Phaser.ScaleManager](phaser.scalemanager) The game scale manager. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L191)) ### sound : [Phaser.SoundManager](phaser.soundmanager) Reference to the sound manager. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 196](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L196)) ### stage : [Phaser.Stage](phaser.stage) Reference to the stage. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 201](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L201)) ### state : [Phaser.StateManager](phaser.statemanager) The StateManager. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 133](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L133)) ### [readonly] stepCount : number When stepping is enabled this contains the current step cycle. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 296](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L296)) ### [readonly] stepping : boolean Enable core loop stepping with Game.enableStep(). Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 282](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L282)) ### time : [Phaser.Time](phaser.time) Reference to the core game clock. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 206](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L206)) ### transparent : boolean Use a transparent canvas background or not. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 96](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L96)) ### tweens : [Phaser.TweenManager](phaser.tweenmanager) Reference to the tween manager. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 211](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L211)) ### <internal> updatesThisFrame : integer Number of logic updates expected to occur this render frame; will be 1 unless there are catch-ups required (and allowed). Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 343](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L343)) ### [readonly] width : integer The current Game Width in pixels. *Do not modify this property directly:* use [Phaser.ScaleManager#setGameSize](phaser.scalemanager#setGameSize) - eg. `game.scale.setGameSize(width, height)` - instead. Default Value * 800 Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L58)) ### world : [Phaser.World](phaser.world) Reference to the world. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 216](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L216)) Public Methods -------------- ### <internal> boot() Initialize engine sub modules and start the game. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 520](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L520)) ### destroy() Nukes the entire game from orbit. Calls destroy on Game.state, Game.sound, Game.scale, Game.stage, Game.input, Game.physics and Game.plugins. Then sets all of those local handlers to null, destroys the renderer, removes the canvas from the DOM and resets the PIXI default renderer. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 1001](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L1001)) ### disableStep() Disables core game loop stepping. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 976](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L976)) ### enableStep() Enable core game loop stepping. When enabled you must call game.step() directly (perhaps via a DOM button?) Calling step will advance the game loop by one frame. This is extremely useful for hard to track down errors! Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 962](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L962)) ### <internal> focusGain(event) Called by the Stage visibility handler. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | object | The DOM event that caused the game to pause, if any. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 1132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L1132)) ### <internal> focusLoss(event) Called by the Stage visibility handler. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | object | The DOM event that caused the game to pause, if any. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 1114](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L1114)) ### <internal> gamePaused(event) Called by the Stage visibility handler. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | object | The DOM event that caused the game to pause, if any. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 1048](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L1048)) ### <internal> gameResumed(event) Called by the Stage visibility handler. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | object | The DOM event that caused the game to pause, if any. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 1080](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L1080)) ### <internal> parseConfig() Parses a Game configuration object. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 440](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L440)) ### <internal> setUpRenderer() Checks if the device is capable of using the requested renderer and sets it up or an alternative if not. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 676](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L676)) ### <internal> showDebugHeader() Displays a Phaser version debug header in the console. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 609](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L609)) ### step() When stepping is enabled you must call this function directly (perhaps via a DOM button?) to advance the game loop by one frame. This is extremely useful to hard to track down errors! Use the internal stepCount property to monitor progress. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 988](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L988)) ### <internal> update(time) The core game loop. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `time` | number | The current time as provided by RequestAnimationFrame. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 777](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L777)) ### <internal> updateLogic(timeStep) Updates all logic subsystems in Phaser. Called automatically by Game.update. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `timeStep` | number | The current timeStep value as determined by Game.update. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 877](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L877)) ### <internal> updateRender(elapsedTime) Runs the Render cycle. It starts by calling State.preRender. In here you can do any last minute adjustments of display objects as required. It then calls the renderer, which renders the entire display list, starting from the Stage object and working down. It then calls plugin.render on any loaded plugins, in the order in which they were enabled. After this State.render is called. Any rendering that happens here will take place on-top of the display list. Finally plugin.postRender is called on any loaded plugins, in the order in which they were enabled. This method is called automatically by Game.update, you don't need to call it directly. Should you wish to have fine-grained control over when Phaser renders then use the `Game.lockRender` boolean. Phaser will only render when this boolean is `false`. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `elapsedTime` | number | The time elapsed since the last update. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Game.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js) ([Line 925](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Game.js#L925))
programming_docs
phaser Class: Phaser.Easing.Linear Class: Phaser.Easing.Linear =========================== Constructor ----------- ### new Linear() Linear easing. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 21](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L21)) Public Methods -------------- ### None(k) → {number} Linear Easing (no variation). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - k. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 23](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L23)) phaser Class: Phaser.Physics.Ninja.Body Class: Phaser.Physics.Ninja.Body ================================ Constructor ----------- ### new Body(system, sprite, type, id, radius, x, y, width, height) The Physics Body is linked to a single Sprite. All physics operations should be performed against the body rather than the Sprite itself. For example you can set the velocity, bounce values etc all on the Body. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `system` | [Phaser.Physics.Ninja](phaser.physics.ninja) | | | The physics system this Body belongs to. | | `sprite` | [Phaser.Sprite](phaser.sprite) | | | The Sprite object this physics body belongs to. | | `type` | number | <optional> | 1 | The type of Ninja shape to create. 1 = AABB, 2 = Circle or 3 = Tile. | | `id` | number | <optional> | 1 | If this body is using a Tile shape, you can set the Tile id here, i.e. Phaser.Physics.Ninja.Tile.SLOPE\_45DEGpn, Phaser.Physics.Ninja.Tile.CONVEXpp, etc. | | `radius` | number | <optional> | 16 | If this body is using a Circle shape this controls the radius. | | `x` | number | <optional> | 0 | The x coordinate of this Body. This is only used if a sprite is not provided. | | `y` | number | <optional> | 0 | The y coordinate of this Body. This is only used if a sprite is not provided. | | `width` | number | <optional> | 0 | The width of this Body. This is only used if a sprite is not provided. | | `height` | number | <optional> | 0 | The height of this Body. This is only used if a sprite is not provided. | Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 23](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L23)) Public Properties ----------------- ### aabb : [Phaser.Physics.Ninja.AABB](phaser.physics.ninja.aabb) The AABB object this body is using for collision. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L54)) ### [readonly] angle : number The angle of this Body Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 535](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L535)) ### [readonly] bottom : number The bottom value of this Body (same as Body.y + Body.height) Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 496](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L496)) ### bounce : number The bounciness of this object when it collides. A value between 0 and 1. We recommend setting it to 0.999 to avoid jittering. Default Value * 0.3 Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 95](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L95)) ### checkCollision : Object Set the checkCollision properties to control which directions collision is processed for this Body. For example checkCollision.up = false means it won't collide when the collision happened while moving up. An object containing allowed collision. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 125](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L125)) ### circle : [Phaser.Physics.Ninja.Circle](phaser.physics.ninja.circle) The Circle object this body is using for collision. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 64](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L64)) ### collideWorldBounds : boolean A Body can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. Should the Body collide with the World bounds? Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 118](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L118)) ### drag : number The drag applied to this object as it moves. Default Value * 1 Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 77](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L77)) ### facing : number A const reference to the direction the Body is traveling or facing. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 106](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L106)) ### friction : number The friction applied to this object as it moves. Default Value * 0.05 Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 83](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L83)) ### game : [Phaser.Game](phaser.game) Local reference to game. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 39](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L39)) ### gravityScale : number How much of the world gravity should be applied to this object? 1 = all of it, 0.5 = 50%, etc. Default Value * 1 Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 89](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L89)) ### [readonly] height : number The height of this Body Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 483](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L483)) ### immovable : boolean An immovable Body will not receive any impacts from other bodies. Not fully implemented. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L112)) ### maxSpeed : number The maximum speed this body can travel at (taking drag and friction into account) Default Value * 8 Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 144](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L144)) ### [readonly] right : number The right value of this Body (same as Body.x + Body.width) Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 509](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L509)) ### shape : Object A local reference to the body shape. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 69](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L69)) ### [readonly] speed : number The speed of this Body Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 522](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L522)) ### sprite : [Phaser.Sprite](phaser.sprite) Reference to the parent Sprite. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 34](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L34)) ### system : [Phaser.Physics.Ninja](phaser.physics.ninja) The parent physics system. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L49)) ### tile : [Phaser.Physics.Ninja.Tile](phaser.physics.ninja.tile) The Tile object this body is using for collision. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 59](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L59)) ### touching : Object This object is populated with boolean values when the Body collides with another. touching.up = true means the collision happened to the top of this Body for example. An object containing touching results. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L132)) ### type : number The type of physics system this body belongs to. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 44](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L44)) ### velocity : [Phaser.Point](phaser.point) The velocity in pixels per second sq. of the Body. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 100](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L100)) ### wasTouching : Object This object is populated with previous touching values from the bodies previous collision. An object containing previous touching results. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 138](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L138)) ### [readonly] width : number The width of this Body Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 470](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L470)) ### x : number The x position. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 438](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L438)) ### y : number The y position. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 454](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L454)) Public Methods -------------- ### deltaAbsX() → {number} Returns the absolute delta x value. ##### Returns number - The absolute delta value. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 381](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L381)) ### deltaAbsY() → {number} Returns the absolute delta y value. ##### Returns number - The absolute delta value. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 391](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L391)) ### deltaX() → {number} Returns the delta x value. The difference between Body.x now and in the previous step. ##### Returns number - The delta value. Positive if the motion was to the right, negative if to the left. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 401](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L401)) ### deltaY() → {number} Returns the delta y value. The difference between Body.y now and in the previous step. ##### Returns number - The delta value. Positive if the motion was downwards, negative if upwards. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 411](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L411)) ### destroy() Destroys this body's reference to the sprite and system, and destroys its shape. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 421](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L421)) ### <internal> postUpdate() Internal method. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 214](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L214)) ### <internal> preUpdate() Internal method. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 184](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L184)) ### render(context, body, color, filled) Render Sprite's Body. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `context` | object | | | The context to render to. | | `body` | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | | | The Body to render. | | `color` | string | <optional> | 'rgba(0,255,0,0.4)' | color of the debug shape to be rendered. (format is css color string). | | `filled` | boolean | <optional> | true | Render the shape as a filled (default, true) or a stroked (false) | Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 548](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L548)) ### reset() Resets all Body values and repositions on the Sprite. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 365](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L365)) ### setZeroVelocity() Stops all movement of this body. Source code: [physics/ninja/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js) ([Line 257](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Body.js#L257)) phaser Class: Phaser.Frame Class: Phaser.Frame =================== Constructor ----------- ### new Frame(index, x, y, width, height, name) A Frame is a single frame of an animation and is part of a FrameData collection. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | number | The index of this Frame within the FrameData set it is being added to. | | `x` | number | X position of the frame within the texture image. | | `y` | number | Y position of the frame within the texture image. | | `width` | number | Width of the frame within the texture image. | | `height` | number | Height of the frame within the texture image. | | `name` | string | The name of the frame. In Texture Atlas data this is usually set to the filename. | Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 19](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L19)) Public Properties ----------------- ### bottom : number The bottom of the frame (y + height). Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 126](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L126)) ### centerX : number Center X position within the image to cut from. Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L54)) ### centerY : number Center Y position within the image to cut from. Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 59](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L59)) ### distance : number The distance from the top left to the bottom-right of this Frame. Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 64](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L64)) ### height : number Height of the frame. Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 44](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L44)) ### index : number The index of this Frame within the FrameData set it is being added to. Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L24)) ### name : string Useful for Texture Atlas files (is set to the filename value). Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L49)) ### right : number The right of the Frame (x + width). Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 121](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L121)) ### rotated : boolean Rotated? (not yet implemented) Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 70](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L70)) ### rotationDirection : string Either 'cw' or 'ccw', rotation is always 90 degrees. Default Value * 'cw' Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 76](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L76)) ### sourceSizeH : number Height of the original sprite before it was trimmed. Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 92](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L92)) ### sourceSizeW : number Width of the original sprite before it was trimmed. Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L87)) ### spriteSourceSizeH : number Height of the trimmed sprite. Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 116](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L116)) ### spriteSourceSizeW : number Width of the trimmed sprite. Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 110](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L110)) ### spriteSourceSizeX : number X position of the trimmed sprite inside original sprite. Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L98)) ### spriteSourceSizeY : number Y position of the trimmed sprite inside original sprite. Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 104](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L104)) ### trimmed : boolean Was it trimmed when packed? Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 82](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L82)) ### width : number Width of the frame. Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 39](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L39)) ### x : number X position within the image to cut from. Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L29)) ### y : number Y position within the image to cut from. Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 34](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L34)) Public Methods -------------- ### clone() → {[Phaser.Frame](phaser.frame)} Clones this Frame into a new Phaser.Frame object and returns it. Note that all properties are cloned, including the name, index and UUID. ##### Returns [Phaser.Frame](phaser.frame) - An exact copy of this Frame object. Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 183](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L183)) ### getRect(out) → {[Phaser.Rectangle](phaser.rectangle)} Returns a Rectangle set to the dimensions of this Frame. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `out` | [Phaser.Rectangle](phaser.rectangle) | <optional> | A rectangle to copy the frame dimensions to. | ##### Returns [Phaser.Rectangle](phaser.rectangle) - A rectangle. Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 206](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L206)) ### resize(width, height) Adjusts of all the Frame properties based on the given width and height values. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `width` | integer | The new width of the Frame. | | `height` | integer | The new height of the Frame. | Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L132)) ### setTrim(trimmed, actualWidth, actualHeight, destX, destY, destWidth, destHeight) If the frame was trimmed when added to the Texture Atlas this records the trim and source data. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `trimmed` | boolean | If this frame was trimmed or not. | | `actualWidth` | number | The width of the frame before being trimmed. | | `actualHeight` | number | The height of the frame before being trimmed. | | `destX` | number | The destination X position of the trimmed frame for display. | | `destY` | number | The destination Y position of the trimmed frame for display. | | `destWidth` | number | The destination width of the trimmed frame for display. | | `destHeight` | number | The destination height of the trimmed frame for display. | Source code: [animation/Frame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Frame.js#L153))
programming_docs
phaser Class: Phaser.Video Class: Phaser.Video =================== Constructor ----------- ### new Video(game, key, url) A Video object that takes a previously loaded Video from the Phaser Cache and handles playback of it. Alternatively it takes a getUserMedia feed from an active webcam and streams the contents of that to the Video instead (see `startMediaStream` method) The video can then be applied to a Sprite as a texture. If multiple Sprites share the same Video texture and playback changes (i.e. you pause the video, or seek to a new time) then this change will be seen across all Sprites simultaneously. Due to a bug in IE11 you cannot play a video texture to a Sprite in WebGL. For IE11 force Canvas mode. If you need each Sprite to be able to play a video fully independently then you will need one Video object per Sprite. Please understand the obvious performance implications of doing this, and the memory required to hold videos in RAM. On some mobile browsers such as iOS Safari, you cannot play a video until the user has explicitly touched the screen. This works in the same way as audio unlocking. Phaser will handle the touch unlocking for you, however unlike with audio it's worth noting that every single Video needs to be touch unlocked, not just the first one. You can use the `changeSource` method to try and work around this limitation, but see the method help for details. Small screen devices, especially iPod and iPhone will launch the video in its own native video player, outside of the Safari browser. There is no way to avoid this, it's a device imposed limitation. Note: On iOS if you need to detect when the user presses the 'Done' button (before the video ends) then you need to add your own event listener ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | | A reference to the currently running game. | | `key` | string | null | <optional> | null | The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture. | | `url` | string | null | <optional> | null | If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null) | Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L38)) Public Properties ----------------- ### currentTime : number The current time of the video in seconds. If set the video will attempt to seek to that point in time. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 1167](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L1167)) ### disableTextureUpload : boolean If true this video will never send its image data to the GPU when its dirty flag is true. This only applies in WebGL. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 75](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L75)) ### [readonly] duration : number The duration of the video in seconds. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 1187](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L1187)) ### game : [Phaser.Game](phaser.game) A reference to the currently running game. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L46)) ### height : number The height of the video in pixels. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 64](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L64)) ### isStreaming : boolean Is there a streaming video source? I.e. from a webcam. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 140](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L140)) ### key : string The key of the Video in the Cache, if stored there. Will be `null` if this Video is using the webcam instead. Default Value * null Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 52](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L52)) ### loop : boolean Gets or sets if the Video is set to loop. Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping. If the video isn't yet set this will always return false. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 1360](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L1360)) ### mute : boolean Gets or sets the muted state of the Video. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 1217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L1217)) ### onAccess : [Phaser.Signal](phaser.signal) This signal is dispatched if the user allows access to their webcam. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 101](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L101)) ### onChangeSource : [Phaser.Signal](phaser.signal) This signal is dispatched if the Video source is changed. It sends 3 parameters: a reference to the Video object and the new width and height of the new video source. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 91](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L91)) ### onComplete : [Phaser.Signal](phaser.signal) This signal is dispatched when the Video completes playback, i.e. enters an 'ended' state. On iOS specifically it also fires if the user hits the 'Done' button at any point during playback. Videos set to loop will never dispatch this signal. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 96](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L96)) ### onError : [Phaser.Signal](phaser.signal) This signal is dispatched if an error occurs either getting permission to use the webcam (for a Video Stream) or when trying to play back a video file. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 106](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L106)) ### onPlay : [Phaser.Signal](phaser.signal) This signal is dispatched when the Video starts to play. It sends 3 parameters: a reference to the Video object, if the video is set to loop or not and the playback rate. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L86)) ### onTimeout : [Phaser.Signal](phaser.signal) This signal is dispatched if when asking for permission to use the webcam no response is given within a the Video.timeout limit. This may be because the user has picked `Not now` in the permissions window, or there is a delay in establishing the LocalMediaStream. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 113](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L113)) ### paused : boolean Gets or sets the paused state of the Video. If the video is still touch locked (such as on iOS devices) this call has no effect. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 1257](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L1257)) ### playbackRate : number Gets or sets the playback rate of the Video. This is the speed at which the video is playing. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 1337](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L1337)) ### [readonly] playing : boolean True if the video is currently playing (and not paused or ended), otherwise false. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 1391](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L1391)) ### [readonly] progress : number The progress of this video. This is a value between 0 and 1, where 0 is the start and 1 is the end of the video. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 1202](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L1202)) ### retry : integer The current retry attempt. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 155](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L155)) ### retryInterval : integer The number of ms between each retry at monitoring the status of a downloading video. Default Value * 500 Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 161](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L161)) ### retryLimit : integer When starting playback of a video Phaser will monitor its readyState using a setTimeout call. The setTimeout happens once every `Video.retryInterval` ms. It will carry on monitoring the video state in this manner until the `retryLimit` is reached and then abort. Default Value * 20 Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 149](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L149)) ### [readonly] snapshot : [Phaser.BitmapData](phaser.bitmapdata) A snapshot grabbed from the video. This is initially black. Populate it by calling Video.grab(). When called the BitmapData is updated with a grab taken from the current video playing or active video stream. If Phaser has been compiled without BitmapData support this property will always be `null`. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 288](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L288)) ### texture : [PIXI.Texture](pixi.texture) The PIXI.Texture. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 263](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L263)) ### textureFrame : [Phaser.Frame](phaser.frame) The Frame this video uses for rendering. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 269](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L269)) ### timeout : integer The amount of ms allowed to elapsed before the Video.onTimeout signal is dispatched while waiting for webcam access. Default Value * 15000 Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 119](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L119)) ### touchLocked : boolean true if this video is currently locked awaiting a touch event. This happens on some mobile devices, such as iOS. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 81](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L81)) ### type : number The const type of this object. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 70](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L70)) ### video :HTMLVideoElement The HTML Video Element that is added to the document. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 130](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L130)) ### videoStream :MediaStream The Video Stream data. Only set if this Video is streaming from the webcam via `startMediaStream`. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 135](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L135)) ### volume : number Gets or sets the volume of the Video, a value between 0 and 1. The value given is clamped to the range 0 to 1. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 1305](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L1305)) ### width : number The width of the video in pixels. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L58)) Public Methods -------------- ### add(object) → {[Phaser.Video](phaser.video)} Updates the given Display Objects so they use this Video as their texture. This will replace any texture they will currently have set. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `object` | [Phaser.Sprite](phaser.sprite) | Array.<[Phaser.Sprite](phaser.sprite)> | [Phaser.Image](phaser.image) | Array.<[Phaser.Image](phaser.image)> | Either a single Sprite/Image or an Array of Sprites/Images. | ##### Returns [Phaser.Video](phaser.video) - This Video object for method chaining. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 804](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L804)) ### addToWorld(x, y, anchorX, anchorY, scaleX, scaleY) → {[Phaser.Image](phaser.image)} Creates a new Phaser.Image object, assigns this Video to be its texture, adds it to the world then returns it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | <optional> | 0 | The x coordinate to place the Image at. | | `y` | number | <optional> | 0 | The y coordinate to place the Image at. | | `anchorX` | number | <optional> | 0 | Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. | | `anchorY` | number | <optional> | 0 | Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. | | `scaleX` | number | <optional> | 1 | The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. | | `scaleY` | number | <optional> | 1 | The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. | ##### Returns [Phaser.Image](phaser.image) - The newly added Image object. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 833](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L833)) ### changeSource(src, autoplay) → {[Phaser.Video](phaser.video)} On some mobile browsers you cannot play a video until the user has explicitly touched the video to allow it. Phaser handles this via the `setTouchLock` method. However if you have 3 different videos, maybe an "Intro", "Start" and "Game Over" split into three different Video objects, then you will need the user to touch-unlock every single one of them. You can avoid this by using just one Video object and simply changing the video source. Once a Video element is unlocked it remains unlocked, even if the source changes. So you can use this to your benefit to avoid forcing the user to 'touch' the video yet again. As you'd expect there are limitations. So far we've found that the videos need to be in the same encoding format and bitrate. This method will automatically handle a change in video dimensions, but if you try swapping to a different bitrate we've found it cannot render the new video on iOS (desktop browsers cope better). When the video source is changed the video file is requested over the network. Listen for the `onChangeSource` signal to know when the new video has downloaded enough content to be able to be played. Previous settings such as the volume and loop state are adopted automatically by the new video. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `src` | string | | | The new URL to change the video.src to. | | `autoplay` | boolean | <optional> | true | Should the video play automatically after the source has been updated? | ##### Returns [Phaser.Video](phaser.video) - This Video object for method chaining. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 954](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L954)) ### complete() Called when the video completes playback (reaches and ended state). Dispatches the Video.onComplete signal. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 623](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L623)) ### connectToMediaStream(video, stream) → {[Phaser.Video](phaser.video)} Connects to an external media stream for the webcam, rather than using a local one. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `video` | HTMLVideoElement | The HTML Video Element that the stream uses. | | `stream` | MediaStream | The Video Stream data. | ##### Returns [Phaser.Video](phaser.video) - This Video object for method chaining. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 311](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L311)) ### createVideoFromBlob(blob) → {[Phaser.Video](phaser.video)} Creates a new Video element from the given Blob. The Blob must contain the video data in the correct encoded format. This method is typically called by the Phaser.Loader and Phaser.Cache for you, but is exposed publicly for convenience. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `blob` | Blob | The Blob containing the video data: `Blob([new Uint8Array(data)])` | ##### Returns [Phaser.Video](phaser.video) - This Video object for method chaining. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 507](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L507)) ### createVideoFromURL(url, autoplay) → {[Phaser.Video](phaser.video)} Creates a new Video element from the given URL. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `url` | string | | | The URL of the video. | | `autoplay` | boolean | <optional> | false | Automatically start the video? | ##### Returns [Phaser.Video](phaser.video) - This Video object for method chaining. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 530](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L530)) ### destroy() Destroys the Video object. This calls `Video.stop` and then `Video.removeVideoElement`. If any Sprites are using this Video as their texture it is up to you to manage those. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 1141](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L1141)) ### grab(clear, alpha, blendMode) → {[Phaser.BitmapData](phaser.bitmapdata)} Grabs the current frame from the Video or Video Stream and renders it to the Video.snapshot BitmapData. You can optionally set if the BitmapData should be cleared or not, the alpha and the blend mode of the draw. If you need more advanced control over the grabbing them call `Video.snapshot.copy` directly with the same parameters as BitmapData.copy. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `clear` | boolean | <optional> | false | Should the BitmapData be cleared before the Video is grabbed? Unless you are using alpha or a blend mode you can usually leave this set to false. | | `alpha` | number | <optional> | 1 | The alpha that will be set on the video before drawing. A value between 0 (fully transparent) and 1, opaque. | | `blendMode` | string | <optional> | null | The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - A reference to the Video.snapshot BitmapData object for further method chaining. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 1075](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L1075)) ### play(loop, playbackRate) → {[Phaser.Video](phaser.video)} Starts this video playing if it's not already doing so. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `loop` | boolean | <optional> | false | Should the video loop automatically when it reaches the end? Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping. | | `playbackRate` | number | <optional> | 1 | The playback rate of the video. 1 is normal speed, 2 is x2 speed, and so on. You cannot set a negative playback rate. | ##### Returns [Phaser.Video](phaser.video) - This Video object for method chaining. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 635](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L635)) ### removeVideoElement() Removes the Video element from the DOM by calling parentNode.removeChild on itself. Also removes the autoplay and src attributes and nulls the reference. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 1111](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L1111)) ### render() If the game is running in WebGL this will push the texture up to the GPU if it's dirty. This is called automatically if the Video is being used by a Sprite, otherwise you need to remember to call it in your render function. If you wish to suppress this functionality set Video.disableTextureUpload to `true`. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 859](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L859)) ### setTouchLock() Sets the Input Manager touch callback to be Video.unlock. Required for mobile video unlocking. Mostly just used internally. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 1033](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L1033)) ### startMediaStream(captureAudio, width, height) → {[Phaser.Video](phaser.video)} Instead of playing a video file this method allows you to stream video data from an attached webcam. As soon as this method is called the user will be prompted by their browser to "Allow" access to the webcam. If they allow it the webcam feed is directed to this Video. Call `Video.play` to start the stream. If they block the webcam the onError signal will be dispatched containing the NavigatorUserMediaError or MediaStreamError event. You can optionally set a width and height for the stream. If set the input will be cropped to these dimensions. If not given then as soon as the stream has enough data the video dimensions will be changed to match the webcam device. You can listen for this with the onChangeSource signal. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `captureAudio` | boolean | <optional> | false | Controls if audio should be captured along with video in the video stream. | | `width` | integer | <optional> | | The width is used to create the video stream. If not provided the video width will be set to the width of the webcam input source. | | `height` | integer | <optional> | | The height is used to create the video stream. If not provided the video height will be set to the height of the webcam input source. | ##### Returns [Phaser.Video](phaser.video) - This Video object for method chaining or false if the device doesn't support getUserMedia. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 337](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L337)) ### stop() → {[Phaser.Video](phaser.video)} Stops the video playing. This removes all locally set signals. If you only wish to pause playback of the video, to resume at a later time, use `Video.paused = true` instead. If the video hasn't finished downloading calling `Video.stop` will not abort the download. To do that you need to call `Video.destroy` instead. If you are using a video stream from a webcam then calling Stop will disconnect the MediaStream session and disable the webcam. ##### Returns [Phaser.Video](phaser.video) - This Video object for method chaining. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 723](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L723)) ### unlock() Enables the video on mobile devices, usually after the first touch. If the SoundManager hasn't been unlocked then this will automatically unlock that as well. Only one video can be pending unlock at any one time. Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 1046](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L1046)) ### updateTexture(event, width, height) Called automatically if the video source changes and updates the internal texture dimensions. Then dispatches the onChangeSource signal. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `event` | object | <optional> | The event which triggered the texture update. | | `width` | integer | <optional> | The new width of the video. If undefined `video.videoWidth` is used. | | `height` | integer | <optional> | The new height of the video. If undefined `video.videoHeight` is used. | Source code: [gameobjects/Video.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js) ([Line 572](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Video.js#L572))
programming_docs
phaser Class: PIXI.Sprite Class: PIXI.Sprite ================== Constructor ----------- ### new Sprite(texture) The Sprite object is the base for all textured objects that are rendered to the screen ##### Parameters | Name | Type | Description | | --- | --- | --- | | `texture` | [PIXI.Texture](pixi.texture) | The texture for this sprite | Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 5](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L5)) Extends ------- * [PIXI.DisplayObjectContainer](pixi.displayobjectcontainer) Public Properties ----------------- ### anchor :Point The anchor sets the origin point of the texture. The default is 0,0 this means the texture's origin is the top left Setting than anchor to 0.5,0.5 means the textures origin is centered Setting the anchor to 1,1 would mean the textures origin points will be the bottom right corner Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L17)) ### blendMode : number The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode. Warning: You cannot have a blend mode and a filter active on the same Sprite. Doing so will render the sprite invisible. Default Value * PIXI.blendModes.NORMAL; Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 82](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L82)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### exists : boolean Controls if this Sprite is processed by the core Phaser game loops and Group loops. Default Value * true Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 103](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L103)) ### height : number The height of the sprite, setting this will actually modify the scale to achieve the value set Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 144](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L144)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### shader : [PIXI.AbstractFilter](pixi.abstractfilter) The shader that will be used to render this Sprite. Set to null to remove a current shader. Default Value * null Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L93)) ### texture : [PIXI.Texture](pixi.texture) The texture that the sprite is using Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L28)) ### tint : number The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. Default Value * 0xFFFFFF Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L54)) ### tintedTexture :Canvas A canvas that contains the tinted version of the Sprite (in Canvas mode, WebGL doesn't populate this) Default Value * null Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 73](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L73)) ### width : number The width of the sprite, setting this will actually modify the scale to achieve the value set Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 125](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L125)) Public Methods -------------- ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### getBounds(matrix) → {Rectangle} Returns the bounds of the Sprite as a rectangle. The bounds calculation takes the worldTransform into account. It is important to note that the transform is not updated when you call this method. So if this Sprite is the child of a Display Object which has had its transform updated since the last render pass, those changes will not yet have been applied to this Sprites worldTransform. If you need to ensure that all parent transforms are factored into this getBounds operation then you should call `updateTransform` on the root most object in this Sprites display list first. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `matrix` | Matrix | the transformation matrix of the sprite | ##### Returns Rectangle - the framing rectangle Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 199](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L199)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the Sprite as a rectangle. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 315](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L315)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### setTexture(texture, destroy) Sets the texture of the sprite. Be warned that this doesn't remove or destroy the previous texture this Sprite was using. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `texture` | [PIXI.Texture](pixi.texture) | | | The PIXI texture that is displayed by the sprite | | `destroy` | Boolean | <optional> | false | Call Texture.destroy on the current texture before replacing it with the new one? | Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 163](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L163)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) phaser Class: Phaser.MSPointer Class: Phaser.MSPointer ======================= Constructor ----------- ### new MSPointer(game) The MSPointer class handles Microsoft touch interactions with the game and the resulting Pointer objects. It will work only in Internet Explorer 10+ and Windows Store or Windows Phone 8 apps using JavaScript. http://msdn.microsoft.com/en-us/library/ie/hh673557(v=vs.85).aspx You should not normally access this class directly, but instead use a Phaser.Pointer object which normalises all game input for you including accurate button handling. Please note that at the current time of writing Phaser does not yet support chorded button interactions: http://www.w3.org/TR/pointerevents/#chorded-button-interactions ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | Source code: [input/MSPointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js) ([Line 23](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js#L23)) Public Properties ----------------- ### button : number This property was removed in Phaser 2.4 and should no longer be used. Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on. Or Pointer.button holds the DOM event button value if you require that. Source code: [input/MSPointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js) ([Line 67](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js#L67)) ### callbackContext : Object The context under which callbacks are called (defaults to game). Source code: [input/MSPointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js) ([Line 39](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js#L39)) ### capture : boolean If true the Pointer events will have event.preventDefault applied to them, if false they will propagate fully. Source code: [input/MSPointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js) ([Line 59](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js#L59)) ### enabled : boolean MSPointer input will only be processed if enabled. Default Value * true Source code: [input/MSPointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js) ([Line 82](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js#L82)) ### event :MSPointerEvent | null The browser MSPointer DOM event. Will be null if no event has ever been received. Access this property only inside a Pointer event handler and do not keep references to it. ##### Type * MSPointerEvent | null Source code: [input/MSPointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js) ([Line 75](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js#L75)) ### game : [Phaser.Game](phaser.game) A reference to the currently running game. Source code: [input/MSPointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js#L28)) ### <internal> input : [Phaser.Input](phaser.input) A reference to the Phaser Input Manager. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/MSPointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js) ([Line 34](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js#L34)) ### pointerDownCallback : Function A callback that can be fired on a MSPointerDown event. Source code: [input/MSPointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js) ([Line 44](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js#L44)) ### pointerMoveCallback : Function A callback that can be fired on a MSPointerMove event. Source code: [input/MSPointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js#L49)) ### pointerUpCallback : Function A callback that can be fired on a MSPointerUp event. Source code: [input/MSPointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js#L54)) Public Methods -------------- ### onPointerDown(event) The function that handles the PointerDown event. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | PointerEvent | The native DOM event. | Source code: [input/MSPointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js) ([Line 193](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js#L193)) ### onPointerMove(event) The function that handles the PointerMove event. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | PointerEvent | The native DOM event. | Source code: [input/MSPointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js) ([Line 231](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js#L231)) ### onPointerOut(event) The internal method that handles the pointer out event from the browser. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | PointerEvent | The native event from the browser. This gets stored in MSPointer.event. | Source code: [input/MSPointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js) ([Line 329](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js#L329)) ### onPointerOut(event) The internal method that handles the pointer out event from the browser. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | PointerEvent | The native event from the browser. This gets stored in MSPointer.event. | Source code: [input/MSPointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js) ([Line 384](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js#L384)) ### onPointerUp(event) The function that handles the PointerUp event. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | PointerEvent | The native DOM event. | Source code: [input/MSPointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js) ([Line 268](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js#L268)) ### onPointerUpGlobal(event) The internal method that handles the mouse up event from the window. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | PointerEvent | The native event from the browser. This gets stored in MSPointer.event. | Source code: [input/MSPointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js) ([Line 305](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js#L305)) ### start() Starts the event listeners running. Source code: [input/MSPointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js#L124)) ### stop() Stop the event listeners. Source code: [input/MSPointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js) ([Line 420](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/MSPointer.js#L420))
programming_docs
phaser Class: Phaser.LoaderParser Class: Phaser.LoaderParser ========================== Constructor ----------- ### new LoaderParser() Phaser.LoaderParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into the Cache. Source code: [loader/LoaderParser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/LoaderParser.js) ([Line 12](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/LoaderParser.js#L12)) Public Methods -------------- ### <static> bitmapFont(xml, baseTexture, xSpacing, ySpacing) → {object} Alias for xmlBitmapFont, for backwards compatibility. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `xml` | object | | | XML data you want to parse. | | `baseTexture` | [PIXI.BaseTexture](pixi.basetexture) | | | The BaseTexture this font uses. | | `xSpacing` | number | <optional> | 0 | Additional horizontal spacing between the characters. | | `ySpacing` | number | <optional> | 0 | Additional vertical spacing between the characters. | ##### Returns object - The parsed Bitmap Font data. Source code: [loader/LoaderParser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/LoaderParser.js) ([Line 14](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/LoaderParser.js#L14)) ### <static> jsonBitmapFont(json, baseTexture, xSpacing, ySpacing) → {object} Parse a Bitmap Font from a JSON file. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `json` | object | | | JSON data you want to parse. | | `baseTexture` | [PIXI.BaseTexture](pixi.basetexture) | | | The BaseTexture this font uses. | | `xSpacing` | number | <optional> | 0 | Additional horizontal spacing between the characters. | | `ySpacing` | number | <optional> | 0 | Additional vertical spacing between the characters. | ##### Returns object - The parsed Bitmap Font data. Source code: [loader/LoaderParser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/LoaderParser.js) ([Line 84](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/LoaderParser.js#L84)) ### <static> xmlBitmapFont(xml, baseTexture, xSpacing, ySpacing) → {object} Parse a Bitmap Font from an XML file. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `xml` | object | | | XML data you want to parse. | | `baseTexture` | [PIXI.BaseTexture](pixi.basetexture) | | | The BaseTexture this font uses. | | `xSpacing` | number | <optional> | 0 | Additional horizontal spacing between the characters. | | `ySpacing` | number | <optional> | 0 | Additional vertical spacing between the characters. | ##### Returns object - The parsed Bitmap Font data. Source code: [loader/LoaderParser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/LoaderParser.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/LoaderParser.js#L30)) phaser Class: PIXI.DisplayObjectContainer Class: PIXI.DisplayObjectContainer ================================== Constructor ----------- ### new DisplayObjectContainer() A DisplayObjectContainer represents a collection of display objects. It is the base class of all display objects that act as a container for other objects. Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 5](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L5)) Extends ------- * [DisplayObject](global#DisplayObject) Public Properties ----------------- ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### height : number The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 600](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L600)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### width : number The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 571](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L571)) Public Methods -------------- ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### getBounds(targetCoordinateSpace) → {Rectangle} Retrieves the global bounds of the displayObjectContainer as a rectangle. The bounds calculation takes all visible children into consideration. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `targetCoordinateSpace` | PIXIDisplayObject | PIXIMatrix | <optional> | Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object. | ##### Returns Rectangle - The rectangular bounding area Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 280](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L280)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the displayObjectContainer as a rectangle without any transformations. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 437](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L437)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) phaser Class: Phaser.Keyboard Class: Phaser.Keyboard ====================== Constructor ----------- ### new Keyboard(game) The Keyboard class monitors keyboard input and dispatches keyboard events. *Note*: many keyboards are unable to process certain combinations of keys due to hardware limitations known as ghosting. See http://www.html5gamedevs.com/topic/4876-impossible-to-use-more-than-2-keyboard-input-buttons-at-the-same-time/ for more details. Also please be aware that certain browser extensions can disable or override Phaser keyboard handling. For example the Chrome extension vimium is known to disable Phaser from using the D key. And there are others. So please check your extensions before opening Phaser issues. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 21](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L21)) Public Properties ----------------- ### callbackContext : Object The context under which the callbacks are run. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 48](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L48)) ### enabled : boolean Keyboard input will only be processed if enabled. Default Value * true Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 33](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L33)) ### event : Object The most recent DOM event from keydown or keyup. This is updated every time a new key is pressed or released. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L38)) ### game : [Phaser.Game](phaser.game) Local reference to game. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L26)) ### [readonly] lastChar : string Returns the string value of the most recently pressed key. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 553](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L553)) ### [readonly] lastKey : [Phaser.Key](phaser.key) Returns the most recently pressed Key. This is a Phaser.Key object and it changes every time a key is pressed. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 576](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L576)) ### onDownCallback : Function This callback is invoked every time a key is pressed down, including key repeats when a key is held down. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 53](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L53)) ### onPressCallback : Function This callback is invoked every time a DOM onkeypress event is raised, which is only for printable keys. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L58)) ### onUpCallback : Function This callback is invoked every time a key is released. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 63](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L63)) ### pressEvent : Object The most recent DOM event from keypress. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 43](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L43)) Public Methods -------------- ### addCallbacks(context, onDown, onUp, onPress) Add callbacks to the Keyboard handler so that each time a key is pressed down or released the callbacks are activated. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `context` | object | | | The context under which the callbacks are run. | | `onDown` | function | <optional> | null | This callback is invoked every time a key is pressed down. | | `onUp` | function | <optional> | null | This callback is invoked every time a key is released. | | `onPress` | function | <optional> | null | This callback is invoked every time the onkeypress event is raised. | Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 114](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L114)) ### addKey(keycode) → {[Phaser.Key](phaser.key)} If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method. The Key object can then be polled, have events attached to it, etc. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `keycode` | integer | The [keycode](phaser.keycode) of the key. | ##### Returns [Phaser.Key](phaser.key) - The Key object which you can store locally and reference directly. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 144](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L144)) ### addKeyCapture(keycode) By default when a key is pressed Phaser will not stop the event from propagating up to the browser. There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. The `addKeyCapture` method enables consuming keyboard event for specific keys so it doesn't bubble up to the the browser and cause the default browser behavior. Pass in either a single keycode or an array/hash of keycodes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `keycode` | integer | Array.<integer> | object | Either a single [keycode](phaser.keycode) or an array/hash of keycodes such as `[65, 67, 68]`. | Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 294](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L294)) ### addKeys(keys) → {object} A practical way to create an object containing user selected hotkeys. For example, ``` addKeys( { 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S, 'left': Phaser.KeyCode.A, 'right': Phaser.KeyCode.D } ); ``` would return an object containing properties (`up`, `down`, `left` and `right`) referring to [Phaser.Key](phaser.key) object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `keys` | object | A key mapping object, i.e. `{ 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S }` or `{ 'up': 52, 'down': 53 }`. | ##### Returns object - An object containing the properties mapped to [Phaser.Key](phaser.key) values. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 165](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L165)) ### clearCaptures() Clear all set key captures. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 333](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L333)) ### createCursorKeys() → {object} Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right. ##### Returns object - An object containing properties: `up`, `down`, `left` and `right` of [Phaser.Key](phaser.key) objects. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 208](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L208)) ### destroy() Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the window. Also clears all key captures and currently created Key objects. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 277](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L277)) ### downDuration(keycode, duration) → {boolean} Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, or was pressed down longer ago than then given duration. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `keycode` | integer | | | The [keycode](phaser.keycode) of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. | | `duration` | number | <optional> | 50 | The duration within which the key is considered as being just pressed. Given in ms. | ##### Returns boolean - True if the key was pressed down within the given duration, false if not or null if the Key wasn't found. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 487](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L487)) ### isDown(keycode) → {boolean} Returns true of the key is currently pressed down. Note that it can only detect key presses on the web browser. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `keycode` | integer | The [keycode](phaser.keycode) of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. | ##### Returns boolean - True if the key is currently down, false if not or null if the Key wasn't found. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 531](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L531)) ### <internal> processKeyDown(event) Process the keydown event. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | KeyboardEvent | | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 363](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L363)) ### <internal> processKeyPress(event) Process the keypress event. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | KeyboardEvent | | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 403](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L403)) ### <internal> processKeyUp(event) Process the keyup event. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | KeyboardEvent | | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 426](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L426)) ### removeKey(keycode) Removes a Key object from the Keyboard manager. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `keycode` | integer | The [keycode](phaser.keycode) of the key to remove. | Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L191)) ### removeKeyCapture(keycode) Removes an existing key capture. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `keycode` | integer | The [keycode](phaser.keycode) to remove capturing of. | Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 321](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L321)) ### reset(hard) Resets all Keys. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `hard` | boolean | <optional> | true | A soft reset won't reset any events or callbacks that are bound to the Keys. A hard reset will. | Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 463](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L463)) ### <internal> start() Starts the Keyboard event listeners running (keydown and keyup). They are attached to the window. This is called automatically by Phaser.Input and should not normally be invoked directly. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 220](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L220)) ### stop() Stops the Keyboard event listeners from running (keydown, keyup and keypress). They are removed from the window. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 260](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L260)) ### update() Updates all currently defined keys. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 344](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L344)) ### upDuration(keycode, duration) → {boolean} Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, or was pressed down longer ago than then given duration. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `keycode` | [Phaser.KeyCode](phaser.keycode) | integer | | | The keycode of the key to check, i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. | | `duration` | number | <optional> | 50 | The duration within which the key is considered as being just released. Given in ms. | ##### Returns boolean - True if the key was released within the given duration, false if not or null if the Key wasn't found. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 509](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L509))
programming_docs
phaser Class: Phaser.Events Class: Phaser.Events ==================== Constructor ----------- ### new Events(sprite) The Events component is a collection of events fired by the parent Game Object. Phaser uses what are known as 'Signals' for all event handling. All of the events in this class are signals you can subscribe to, much in the same way you'd "listen" for an event. For example to tell when a Sprite has been added to a new group, you can bind a function to the `onAddedToGroup` signal: `sprite.events.onAddedToGroup.add(yourFunction, this);` Where `yourFunction` is the function you want called when this event occurs. For more details about how signals work please see the Phaser.Signal class. The Input-related events will only be dispatched if the Sprite has had `inputEnabled` set to `true` and the Animation-related events only apply to game objects with animations like [Phaser.Sprite](phaser.sprite). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `sprite` | [Phaser.Sprite](phaser.sprite) | A reference to the game object / Sprite that owns this Events object. | Source code: [gameobjects/components/Events.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js#L30)) Public Properties ----------------- ### onAddedToGroup : [Phaser.Signal](phaser.signal) This signal is dispatched when this Game Object is added to a new Group. It is sent two arguments: {any} The Game Object that was added to the Group. {Phaser.Group} The Group it was added to. Source code: [gameobjects/components/Events.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js) ([Line 84](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js#L84)) ### onAnimationComplete : [Phaser.Signal](phaser.signal) This signal is dispatched if the Game Object has the AnimationManager component, and an Animation has been stopped (via `animation.stop()` and the `dispatchComplete` argument has been set. You can also listen to `Animation.onComplete` rather than via the Game Objects events. It is sent two arguments: {any} The Game Object that received the event. {Phaser.Animation} The Phaser.Animation that was stopped. Source code: [gameobjects/components/Events.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js) ([Line 249](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js#L249)) ### onAnimationLoop : [Phaser.Signal](phaser.signal) This signal is dispatched if the Game Object has the AnimationManager component, and an Animation has looped playback. You can also listen to `Animation.onLoop` rather than via the Game Objects events. It is sent two arguments: {any} The Game Object that received the event. {Phaser.Animation} The Phaser.Animation that looped. Source code: [gameobjects/components/Events.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js) ([Line 260](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js#L260)) ### onAnimationStart : [Phaser.Signal](phaser.signal) This signal is dispatched if the Game Object has the AnimationManager component, and an Animation has been played. You can also listen to `Animation.onStart` rather than via the Game Objects events. It is sent two arguments: {any} The Game Object that received the event. {Phaser.Animation} The Phaser.Animation that was started. Source code: [gameobjects/components/Events.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js) ([Line 238](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js#L238)) ### onDestroy : [Phaser.Signal](phaser.signal) This signal is dispatched when the Game Object is destroyed. This happens when `Sprite.destroy()` is called, or `Group.destroy()` with `destroyChildren` set to true. It is sent one argument: {any} The Game Object that was destroyed. Source code: [gameobjects/components/Events.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js) ([Line 109](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js#L109)) ### onDragStart : [Phaser.Signal](phaser.signal) This signal is dispatched if the Game Object has been `inputEnabled` and `enableDrag` has been set. It is sent when a Phaser.Pointer starts to drag the Game Object, taking into consideration the various drag limitations that may be set. It is sent four arguments: {any} The Game Object that received the event. {Phaser.Pointer} The Phaser.Pointer object that caused the event. {number} The x coordinate that the drag started from. {number} The y coordinate that the drag started from. Source code: [gameobjects/components/Events.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js) ([Line 202](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js#L202)) ### onDragStop : [Phaser.Signal](phaser.signal) This signal is dispatched if the Game Object has been `inputEnabled` and `enableDrag` has been set. It is sent when a Phaser.Pointer stops dragging the Game Object. It is sent two arguments: {any} The Game Object that received the event. {Phaser.Pointer} The Phaser.Pointer object that caused the event. Source code: [gameobjects/components/Events.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js) ([Line 227](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js#L227)) ### onDragUpdate : [Phaser.Signal](phaser.signal) This signal is dispatched if the Game Object has been `inputEnabled` and `enableDrag` has been set. It is sent when a Phaser.Pointer is actively dragging the Game Object. Be warned: This is a high volume Signal. Be careful what you bind to it. It is sent six arguments: {any} The Game Object that received the event. {Phaser.Pointer} The Phaser.Pointer object that caused the event. {number} The new x coordinate of the Game Object. {number} The new y coordinate of the Game Object. {Phaser.Point} A Point object that contains the point the Game Object was snapped to, if `snapOnDrag` has been enabled. {boolean} The `fromStart` boolean, indicates if this is the first update immediately after the drag has started. Source code: [gameobjects/components/Events.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js) ([Line 217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js#L217)) ### onEnterBounds : [Phaser.Signal](phaser.signal) This signal is dispatched when the Game Object returns within the Phaser.World bounds, having previously been outside of them. This signal is only if `Sprite.checkWorldBounds` is set to `true`. It is sent one argument: {any} The Game Object that entered the World bounds. Source code: [gameobjects/components/Events.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js) ([Line 146](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js#L146)) ### onInputDown : [Phaser.Signal](phaser.signal) This signal is dispatched if the Game Object has `inputEnabled` set to `true`, and receives a down event from a Phaser.Pointer. This effectively means the Pointer has been pressed down (but not yet released) on the Game Object. It is sent two arguments: {any} The Game Object that received the event. {Phaser.Pointer} The Phaser.Pointer object that caused the event. Source code: [gameobjects/components/Events.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js) ([Line 177](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js#L177)) ### onInputOut : [Phaser.Signal](phaser.signal) This signal is dispatched if the Game Object has `inputEnabled` set to `true`, and receives an out event from a Phaser.Pointer, which was previously over it. It is sent two arguments: {any} The Game Object that received the event. {Phaser.Pointer} The Phaser.Pointer object that caused the event. Source code: [gameobjects/components/Events.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js) ([Line 166](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js#L166)) ### onInputOver : [Phaser.Signal](phaser.signal) This signal is dispatched if the Game Object has `inputEnabled` set to `true`, and receives an over event from a Phaser.Pointer. It is sent two arguments: {any} The Game Object that received the event. {Phaser.Pointer} The Phaser.Pointer object that caused the event. Source code: [gameobjects/components/Events.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js) ([Line 156](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js#L156)) ### onInputUp : [Phaser.Signal](phaser.signal) This signal is dispatched if the Game Object has `inputEnabled` set to `true`, and receives an up event from a Phaser.Pointer. This effectively means the Pointer had been pressed down, and was then released on the Game Object. It is sent three arguments: {any} The Game Object that received the event. {Phaser.Pointer} The Phaser.Pointer object that caused the event. {boolean} isOver - Is the Pointer still over the Game Object? Source code: [gameobjects/components/Events.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js) ([Line 189](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js#L189)) ### onKilled : [Phaser.Signal](phaser.signal) This signal is dispatched when the Game Object is killed. This happens when `Sprite.kill()` is called. Please understand the difference between `kill` and `destroy` by looking at their respective methods. It is sent one argument: {any} The Game Object that was killed. Source code: [gameobjects/components/Events.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js) ([Line 119](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js#L119)) ### onOutOfBounds : [Phaser.Signal](phaser.signal) This signal is dispatched when the Game Object leaves the Phaser.World bounds. This signal is only if `Sprite.checkWorldBounds` is set to `true`. It is sent one argument: {any} The Game Object that left the World bounds. Source code: [gameobjects/components/Events.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js) ([Line 137](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js#L137)) ### onRemovedFromGroup : [Phaser.Signal](phaser.signal) This signal is dispatched when the Game Object is removed from a Group. It is sent two arguments: {any} The Game Object that was removed from the Group. {Phaser.Group} The Group it was removed from. Source code: [gameobjects/components/Events.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js#L93)) ### onRemovedFromWorld : [Phaser.Signal](phaser.signal) This method is *deprecated* and should not be used. It may be removed in the future. This Signal is never used internally by Phaser and is now deprecated. Deprecated: * Yes Source code: [gameobjects/components/Events.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js) ([Line 100](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js#L100)) ### onRevived : [Phaser.Signal](phaser.signal) This signal is dispatched when the Game Object is revived from a previously killed state. This happens when `Sprite.revive()` is called. It is sent one argument: {any} The Game Object that was revived. Source code: [gameobjects/components/Events.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js) ([Line 128](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js#L128)) ### parent : [Phaser.Sprite](phaser.sprite) The Sprite that owns these events. Source code: [gameobjects/components/Events.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js) ([Line 35](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js#L35)) Public Methods -------------- ### destroy() Removes all events. Source code: [gameobjects/components/Events.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js) ([Line 43](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Events.js#L43)) phaser Class: Phaser.Physics.P2.InversePointProxy Class: Phaser.Physics.P2.InversePointProxy ========================================== Constructor ----------- ### new InversePointProxy(world, destination) A InversePointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays but inverses the values on set. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `world` | [Phaser.Physics.P2](phaser.physics.p2) | A reference to the P2 World. | | `destination` | any | The object to bind to. | Source code: [physics/p2/InversePointProxy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/InversePointProxy.js) ([Line 15](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/InversePointProxy.js#L15)) Public Properties ----------------- ### mx : number The x property of this InversePointProxy get and set in meters. Source code: [physics/p2/InversePointProxy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/InversePointProxy.js) ([Line 64](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/InversePointProxy.js#L64)) ### my : number The y property of this InversePointProxy get and set in meters. Source code: [physics/p2/InversePointProxy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/InversePointProxy.js) ([Line 84](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/InversePointProxy.js#L84)) ### x : number The x property of this InversePointProxy get and set in pixels. Source code: [physics/p2/InversePointProxy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/InversePointProxy.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/InversePointProxy.js#L24)) ### y : number The y property of this InversePointProxy get and set in pixels. Source code: [physics/p2/InversePointProxy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/InversePointProxy.js) ([Line 44](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/InversePointProxy.js#L44)) phaser Class: Phaser.DOM Class: Phaser.DOM ================= Constructor ----------- ### new DOM() DOM utility class. Provides a useful Window and Element functions as well as cross-browser compatibility buffer. Some code originally derived from [verge](https://github.com/ryanve/verge). Some parts were inspired by the research of Ryan Van Etten, released under MIT License 2013. Source code: [utils/DOM.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/DOM.js) ([Line 18](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/DOM.js#L18)) Public Properties ----------------- ### <static, readonly> documentBounds : [Phaser.Rectangle](phaser.rectangle) The size of the document / Layout viewport. This incorrectly reports the dimensions in IE. The properties change dynamically. ##### Properties: | Name | Type | Description | | --- | --- | --- | | `width` | number | Document width in pixels. | | `height` | number | Document height in pixels. | Source code: [utils/DOM.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/DOM.js) ([Line 274](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/DOM.js#L274)) ### <static, readonly> layoutBounds : [Phaser.Rectangle](phaser.rectangle) The bounds of the Layout viewport, as discussed in [A tale of two viewports — part two](http://www.quirksmode.org/mobile/viewports2.html); but honoring the constraints as specified applicable viewport meta-tag. The bounds returned are not guaranteed to be fully aligned with CSS media queries (see [What size is my viewport?](http://www.matanich.com/2013/01/07/viewport-size/)). This is *not* representative of the Visual bounds: in particular the non-primary axis will generally be significantly larger than the screen height on mobile devices when running with a constrained viewport. The properties change dynamically. ##### Properties: | Name | Type | Description | | --- | --- | --- | | `width` | number | Viewport width in pixels. | | `height` | number | Viewport height in pixels. | Source code: [utils/DOM.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/DOM.js) ([Line 260](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/DOM.js#L260)) ### <internal, static, readonly> scrollX : number A cross-browser window.scrollX. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [utils/DOM.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/DOM.js) ([Line 289](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/DOM.js#L289)) ### <internal, static, readonly> scrollY : number A cross-browser window.scrollY. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [utils/DOM.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/DOM.js) ([Line 301](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/DOM.js#L301)) ### <static, readonly> visualBounds : [Phaser.Rectangle](phaser.rectangle) The bounds of the Visual viewport, as discussed in [A tale of two viewports — part one](http://www.quirksmode.org/mobile/viewports.html) with one difference: the viewport size *excludes* scrollbars, as found on some desktop browsers. Supported mobile: iOS/Safari, Android 4, IE10, Firefox OS (maybe not Firefox Android), Opera Mobile 16 The properties change dynamically. ##### Properties: | Name | Type | Description | | --- | --- | --- | | `x` | number | Scroll, left offset - eg. "scrollX" | | `y` | number | Scroll, top offset - eg. "scrollY" | | `width` | number | Viewport width in pixels. | | `height` | number | Viewport height in pixels. | Source code: [utils/DOM.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/DOM.js) ([Line 239](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/DOM.js#L239)) Public Methods -------------- ### <static> getAspectRatio(object) → {number} Get the Visual viewport aspect ratio (or the aspect ratio of an object or element) ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `object` | DOMElement | Object | <optional> | (visualViewport) | The object to determine the aspect ratio for. Must have public `width` and `height` properties or methods. | ##### Returns number - The aspect ratio. Source code: [utils/DOM.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/DOM.js) ([Line 100](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/DOM.js#L100)) ### <static> getBounds(element, cushion) → {Object | boolean} A cross-browser element.getBoundingClientRect method with optional cushion. Returns a plain object containing the properties `top/bottom/left/right/width/height` with respect to the top-left corner of the current viewport. Its properties match the native rectangle. The cushion parameter is an amount of pixels (+/-) to cushion the element. It adjusts the measurements such that it is possible to detect when an element is near the viewport. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `element` | DOMElement | Object | | The element or stack (uses first item) to get the bounds for. | | `cushion` | number | <optional> | A +/- pixel adjustment amount. | ##### Returns Object | boolean - A plain object containing the properties `top/bottom/left/right/width/height` or `false` if a non-valid element is given. Source code: [utils/DOM.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/DOM.js) ([Line 48](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/DOM.js#L48)) ### <static> getOffset(element, point) → {[Phaser.Point](phaser.point)} Get the [absolute] position of the element relative to the Document. The value may vary slightly as the page is scrolled due to rounding errors. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `element` | DOMElement | | The targeted element that we want to retrieve the offset. | | `point` | [Phaser.Point](phaser.point) | <optional> | The point we want to take the x/y values of the offset. | ##### Returns [Phaser.Point](phaser.point) - * A point objet with the offsetX and Y as its properties. Source code: [utils/DOM.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/DOM.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/DOM.js#L20)) ### <internal, static> getScreenOrientation(primaryFallback) Returns the device screen orientation. Orientation values: 'portrait-primary', 'landscape-primary', 'portrait-secondary', 'landscape-secondary'. Order of resolving: * Screen Orientation API, or variation of - Future track. Most desktop and mobile browsers. * Screen size ratio check - If fallback is 'screen', suited for desktops. * Viewport size ratio check - If fallback is 'viewport', suited for mobile. * window.orientation - If fallback is 'window.orientation', works iOS and probably most Android; non-recommended track. * Media query * Viewport size ratio check (probably only IE9 and legacy mobile gets here..) See * https://w3c.github.io/screen-orientation/ (conflicts with mozOrientation/msOrientation) * https://developer.mozilla.org/en-US/docs/Web/API/Screen.orientation (mozOrientation) * http://msdn.microsoft.com/en-us/library/ie/dn342934(v=vs.85).aspx * https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Testing\_media\_queries * http://stackoverflow.com/questions/4917664/detect-viewport-orientation * http://www.matthewgifford.com/blog/2011/12/22/a-misconception-about-window-orientation ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `primaryFallback` | string | <optional> | (none) | Specify 'screen', 'viewport', or 'window.orientation'. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [utils/DOM.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/DOM.js) ([Line 149](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/DOM.js#L149)) ### <static> inLayoutViewport(element, cushion) → {boolean} Tests if the given DOM element is within the Layout viewport. The optional cushion parameter allows you to specify a distance. inLayoutViewport(element, 100) is `true` if the element is in the viewport or 100px near it. inLayoutViewport(element, -100) is `true` if the element is in the viewport or at least 100px near it. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `element` | DOMElement | Object | | The DOM element to check. If no element is given it defaults to the Phaser game canvas. | | `cushion` | number | <optional> | The cushion allows you to specify a distance within which the element must be within the viewport. | ##### Returns boolean - True if the element is within the viewport, or within `cushion` distance from it. Source code: [utils/DOM.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/DOM.js) ([Line 128](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/DOM.js#L128))
programming_docs
phaser Class: Phaser.Point Class: Phaser.Point =================== Constructor ----------- ### new Point(x, y) A Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis. The following code creates a point at (0,0): `var myPoint = new Phaser.Point();` You can also use them as 2D Vectors and you'll find different vector related methods in this class. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | <optional> | 0 | The horizontal position of this Point. | | `y` | number | <optional> | 0 | The vertical position of this Point. | Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 18](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L18)) Public Properties ----------------- ### [readonly] type : number The const type of this object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L37)) ### x : number The x value of the point. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L26)) ### y : number The y value of the point. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 31](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L31)) Public Methods -------------- ### <static> add(a, b, out) → {[Phaser.Point](phaser.point)} Adds the coordinates of two points together to create a new point. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `a` | [Phaser.Point](phaser.point) | | The first Point object. | | `b` | [Phaser.Point](phaser.point) | | The second Point object. | | `out` | [Phaser.Point](phaser.point) | <optional> | Optional Point to store the value in, if not supplied a new Point object will be created. | ##### Returns [Phaser.Point](phaser.point) - The new Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 491](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L491)) ### <static> angle(a, b) → {number} Returns the angle between two Point objects. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | [Phaser.Point](phaser.point) | The first Point object. | | `b` | [Phaser.Point](phaser.point) | The second Point object. | ##### Returns number - The angle between the two Points. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 585](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L585)) ### <static> centroid(points, out) → {[Phaser.Point](phaser.point)} Calculates centroid (or midpoint) from an array of points. If only one point is provided, that point is returned. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `points` | Array.<[Phaser.Point](phaser.point)> | | The array of one or more points. | | `out` | [Phaser.Point](phaser.point) | <optional> | Optional Point to store the value in, if not supplied a new Point object will be created. | ##### Returns [Phaser.Point](phaser.point) - The new Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 832](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L832)) ### <static> distance(a, b, round) → {number} Returns the euclidian distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties). ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `a` | object | | | The target object. Must have visible x and y properties that represent the center of the object. | | `b` | object | | | The target object. Must have visible x and y properties that represent the center of the object. | | `round` | boolean | <optional> | false | Round the distance to the nearest integer. | ##### Returns number - The distance between this Point object and the destination Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 684](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L684)) ### <static> divide(a, b, out) → {[Phaser.Point](phaser.point)} Divides the coordinates of two points to create a new point. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `a` | [Phaser.Point](phaser.point) | | The first Point object. | | `b` | [Phaser.Point](phaser.point) | | The second Point object. | | `out` | [Phaser.Point](phaser.point) | <optional> | Optional Point to store the value in, if not supplied a new Point object will be created. | ##### Returns [Phaser.Point](phaser.point) - The new Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 551](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L551)) ### <static> equals(a, b) → {boolean} Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | [Phaser.Point](phaser.point) | The first Point object. | | `b` | [Phaser.Point](phaser.point) | The second Point object. | ##### Returns boolean - A value of true if the Points are equal, otherwise false. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 571](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L571)) ### <static> interpolate(a, b, f, out) → {[Phaser.Point](phaser.point)} Interpolates the two given Points, based on the `f` value (between 0 and 1) and returns a new Point. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `a` | [Phaser.Point](phaser.point) | | The first Point object. | | `b` | [Phaser.Point](phaser.point) | | The second Point object. | | `f` | number | | The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned. | | `out` | [Phaser.Point](phaser.point) | <optional> | Optional Point to store the value in, if not supplied a new Point object will be created. | ##### Returns [Phaser.Point](phaser.point) - The new Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 634](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L634)) ### <static> multiply(a, b, out) → {[Phaser.Point](phaser.point)} Multiplies the coordinates of two points to create a new point. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `a` | [Phaser.Point](phaser.point) | | The first Point object. | | `b` | [Phaser.Point](phaser.point) | | The second Point object. | | `out` | [Phaser.Point](phaser.point) | <optional> | Optional Point to store the value in, if not supplied a new Point object will be created. | ##### Returns [Phaser.Point](phaser.point) - The new Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 531](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L531)) ### <static> multiplyAdd(a, b, s, out) → {[Phaser.Point](phaser.point)} Adds two 2D Points together and multiplies the result by the given scalar. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `a` | [Phaser.Point](phaser.point) | | The first Point object. | | `b` | [Phaser.Point](phaser.point) | | The second Point object. | | `s` | number | | The scaling value. | | `out` | [Phaser.Point](phaser.point) | <optional> | Optional Point to store the value in, if not supplied a new Point object will be created. | ##### Returns [Phaser.Point](phaser.point) - The new Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 616](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L616)) ### <static> negative(a, out) → {[Phaser.Point](phaser.point)} Creates a negative Point. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `a` | [Phaser.Point](phaser.point) | | The first Point object. | | `out` | [Phaser.Point](phaser.point) | <optional> | Optional Point to store the value in, if not supplied a new Point object will be created. | ##### Returns [Phaser.Point](phaser.point) - The new Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 600](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L600)) ### <static> normalize(a, out) → {[Phaser.Point](phaser.point)} Normalize (make unit length) a Point. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `a` | [Phaser.Point](phaser.point) | | The Point object. | | `out` | [Phaser.Point](phaser.point) | <optional> | Optional Point to store the value in, if not supplied a new Point object will be created. | ##### Returns [Phaser.Point](phaser.point) - The new Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 764](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L764)) ### <static> normalRightHand(a, out) → {[Phaser.Point](phaser.point)} Right-hand normalize (make unit length) a Point. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `a` | [Phaser.Point](phaser.point) | | The Point object. | | `out` | [Phaser.Point](phaser.point) | <optional> | Optional Point to store the value in, if not supplied a new Point object will be created. | ##### Returns [Phaser.Point](phaser.point) - The new Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 748](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L748)) ### <static> parse(obj, xProp, yProp) → {[Phaser.Point](phaser.point)} Parses an object for x and/or y properties and returns a new Phaser.Point with matching values. If the object doesn't contain those properties a Point with x/y of zero will be returned. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `obj` | object | | | The object to parse. | | `xProp` | string | <optional> | 'x' | The property used to set the Point.x value. | | `yProp` | string | <optional> | 'y' | The property used to set the Point.y value. | ##### Returns [Phaser.Point](phaser.point) - The new Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 873](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L873)) ### <static> perp(a, out) → {[Phaser.Point](phaser.point)} Return a perpendicular vector (90 degrees rotation) ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `a` | [Phaser.Point](phaser.point) | | The Point object. | | `out` | [Phaser.Point](phaser.point) | <optional> | Optional Point to store the value in, if not supplied a new Point object will be created. | ##### Returns [Phaser.Point](phaser.point) - The new Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 652](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L652)) ### <static> project(a, b, out) → {[Phaser.Point](phaser.point)} Project two Points onto another Point. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `a` | [Phaser.Point](phaser.point) | | The first Point object. | | `b` | [Phaser.Point](phaser.point) | | The second Point object. | | `out` | [Phaser.Point](phaser.point) | <optional> | Optional Point to store the value in, if not supplied a new Point object will be created. | ##### Returns [Phaser.Point](phaser.point) - The new Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 700](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L700)) ### <static> projectUnit(a, b, out) → {[Phaser.Point](phaser.point)} Project two Points onto a Point of unit length. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `a` | [Phaser.Point](phaser.point) | | The first Point object. | | `b` | [Phaser.Point](phaser.point) | | The second Point object. | | `out` | [Phaser.Point](phaser.point) | <optional> | Optional Point to store the value in, if not supplied a new Point object will be created. | ##### Returns [Phaser.Point](phaser.point) - The new Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 724](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L724)) ### <static> rotate(a, x, y, angle, asDegrees, distance) → {[Phaser.Point](phaser.point)} Rotates a Point object, or any object with exposed x/y properties, around the given coordinates by the angle specified. If the angle between the point and coordinates was 45 deg and the angle argument is 45 deg then the resulting angle will be 90 deg, as the angle argument is added to the current angle. The distance allows you to specify a distance constraint for the rotation between the point and the coordinates. If none is given the distance between the two is calculated and used. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `a` | [Phaser.Point](phaser.point) | | | The Point object to rotate. | | `x` | number | | | The x coordinate of the anchor point | | `y` | number | | | The y coordinate of the anchor point | | `angle` | number | | | The angle in radians (unless asDegrees is true) to rotate the Point by. | | `asDegrees` | boolean | <optional> | false | Is the given angle in radians (false) or degrees (true)? | | `distance` | number | <optional> | | An optional distance constraint between the Point and the anchor. | ##### Returns [Phaser.Point](phaser.point) - The modified point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 787](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L787)) ### <static> rperp(a, out) → {[Phaser.Point](phaser.point)} Return a perpendicular vector (-90 degrees rotation) ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `a` | [Phaser.Point](phaser.point) | | The Point object. | | `out` | [Phaser.Point](phaser.point) | <optional> | Optional Point to store the value in, if not supplied a new Point object will be created. | ##### Returns [Phaser.Point](phaser.point) - The new Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 668](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L668)) ### <static> subtract(a, b, out) → {[Phaser.Point](phaser.point)} Subtracts the coordinates of two points to create a new point. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `a` | [Phaser.Point](phaser.point) | | The first Point object. | | `b` | [Phaser.Point](phaser.point) | | The second Point object. | | `out` | [Phaser.Point](phaser.point) | <optional> | Optional Point to store the value in, if not supplied a new Point object will be created. | ##### Returns [Phaser.Point](phaser.point) - The new Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 511](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L511)) ### add(x, y) → {[Phaser.Point](phaser.point)} Adds the given x and y values to this Point. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The value to add to Point.x. | | `y` | number | The value to add to Point.y. | ##### Returns [Phaser.Point](phaser.point) - This Point object. Useful for chaining method calls. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 106](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L106)) ### angle(a, asDegrees) → {number} Returns the angle between this Point object and another object with public x and y properties. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `a` | [Phaser.Point](phaser.point) | any | | | The object to get the angle from this Point to. | | `asDegrees` | boolean | <optional> | false | Is the given angle in radians (false) or degrees (true)? | ##### Returns number - The angle between the two objects. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 281](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L281)) ### ceil() → {[Phaser.Point](phaser.point)} Math.ceil() both the x and y properties of this Point. ##### Returns [Phaser.Point](phaser.point) - This Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 463](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L463)) ### clamp(min, max) → {[Phaser.Point](phaser.point)} Clamps this Point object values to be between the given min and max. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `min` | number | The minimum value to clamp this Point to. | | `max` | number | The maximum value to clamp this Point to. | ##### Returns [Phaser.Point](phaser.point) - This Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 200](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L200)) ### clampX(min, max) → {[Phaser.Point](phaser.point)} Clamps the x value of this Point to be between the given min and max. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `min` | number | The minimum value to clamp this Point to. | | `max` | number | The maximum value to clamp this Point to. | ##### Returns [Phaser.Point](phaser.point) - This Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 170](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L170)) ### clampY(min, max) → {[Phaser.Point](phaser.point)} Clamps the y value of this Point to be between the given min and max ##### Parameters | Name | Type | Description | | --- | --- | --- | | `min` | number | The minimum value to clamp this Point to. | | `max` | number | The maximum value to clamp this Point to. | ##### Returns [Phaser.Point](phaser.point) - This Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 185](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L185)) ### clone(output) → {[Phaser.Point](phaser.point)} Creates a copy of the given Point. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `output` | [Phaser.Point](phaser.point) | <optional> | Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned. | ##### Returns [Phaser.Point](phaser.point) - The new Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 216](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L216)) ### copyFrom(source) → {[Phaser.Point](phaser.point)} Copies the x and y properties from any given object to this Point. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `source` | any | The object to copy from. | ##### Returns [Phaser.Point](phaser.point) - This Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 43](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L43)) ### copyTo(dest) → {object} Copies the x and y properties from this Point to any given object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `dest` | any | The object to copy to. | ##### Returns object - The dest object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 238](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L238)) ### cross(a) → {number} The cross product of this and another Point object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | [Phaser.Point](phaser.point) | The Point object to get the cross product combined with this Point. | ##### Returns number - The result. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 402](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L402)) ### distance(dest, round) → {number} Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties) ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `dest` | object | | The target object. Must have visible x and y properties that represent the center of the object. | | `round` | boolean | <optional> | Round the distance to the nearest integer (default false). | ##### Returns number - The distance between this Point object and the destination Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 254](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L254)) ### divide(x, y) → {[Phaser.Point](phaser.point)} Divides Point.x and Point.y by the given x and y values. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The value to divide Point.x by. | | `y` | number | The value to divide Point.x by. | ##### Returns [Phaser.Point](phaser.point) - This Point object. Useful for chaining method calls. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 154](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L154)) ### dot(a) → {number} The dot product of this and another Point object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | [Phaser.Point](phaser.point) | The Point object to get the dot product combined with this Point. | ##### Returns number - The result. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 389](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L389)) ### equals(a) → {boolean} Determines whether the given objects x/y values are equal to this Point object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | [Phaser.Point](phaser.point) | any | The object to compare with this Point. | ##### Returns boolean - A value of true if the x and y points are equal, otherwise false. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 268](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L268)) ### floor() → {[Phaser.Point](phaser.point)} Math.floor() both the x and y properties of this Point. ##### Returns [Phaser.Point](phaser.point) - This Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 451](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L451)) ### getMagnitude() → {number} Calculates the length of the Point object. ##### Returns number - The length of the Point. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 321](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L321)) ### getMagnitudeSq() → {number} Calculates the length squared of the Point object. ##### Returns number - The length ^ 2 of the Point. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 333](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L333)) ### invert() → {[Phaser.Point](phaser.point)} Inverts the x and y values of this Point ##### Returns [Phaser.Point](phaser.point) - This Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 56](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L56)) ### isZero() → {boolean} Determine if this point is at 0,0. ##### Returns boolean - True if this Point is 0,0, otherwise false. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 377](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L377)) ### multiply(x, y) → {[Phaser.Point](phaser.point)} Multiplies Point.x and Point.y by the given x and y values. Sometimes known as `Scale`. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The value to multiply Point.x by. | | `y` | number | The value to multiply Point.x by. | ##### Returns [Phaser.Point](phaser.point) - This Point object. Useful for chaining method calls. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 138](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L138)) ### normalize() → {[Phaser.Point](phaser.point)} Alters the Point object so that its length is 1, but it retains the same direction. ##### Returns [Phaser.Point](phaser.point) - This Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 358](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L358)) ### normalRightHand() → {[Phaser.Point](phaser.point)} Right-hand normalize (make unit length) this Point. ##### Returns [Phaser.Point](phaser.point) - This Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 439](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L439)) ### perp() → {[Phaser.Point](phaser.point)} Make this Point perpendicular (90 degrees rotation) ##### Returns [Phaser.Point](phaser.point) - This Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 415](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L415)) ### rotate(x, y, angle, asDegrees, distance) → {[Phaser.Point](phaser.point)} Rotates this Point around the x/y coordinates given to the desired angle. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate of the anchor point. | | `y` | number | | | The y coordinate of the anchor point. | | `angle` | number | | | The angle in radians (unless asDegrees is true) to rotate the Point to. | | `asDegrees` | boolean | <optional> | false | Is the given angle in radians (false) or degrees (true)? | | `distance` | number | <optional> | | An optional distance constraint between the Point and the anchor. | ##### Returns [Phaser.Point](phaser.point) - The modified point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 304](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L304)) ### rperp() → {[Phaser.Point](phaser.point)} Make this Point perpendicular (-90 degrees rotation) ##### Returns [Phaser.Point](phaser.point) - This Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 427](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L427)) ### set(x, y) → {[Phaser.Point](phaser.point)} Sets the `x` and `y` values of this Point object to the given values. If you omit the `y` value then the `x` value will be applied to both, for example: `Point.set(2)` is the same as `Point.set(2, 2)` ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `x` | number | | The horizontal value of this point. | | `y` | number | <optional> | The vertical value of this point. If not given the x value will be used in its place. | ##### Returns [Phaser.Point](phaser.point) - This Point object. Useful for chaining method calls. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L87)) ### setMagnitude(magnitude) → {[Phaser.Point](phaser.point)} Alters the length of the Point without changing the direction. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `magnitude` | number | The desired magnitude of the resulting Point. | ##### Returns [Phaser.Point](phaser.point) - This Point object. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 345](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L345)) ### setTo(x, y) → {[Phaser.Point](phaser.point)} Sets the `x` and `y` values of this Point object to the given values. If you omit the `y` value then the `x` value will be applied to both, for example: `Point.setTo(2)` is the same as `Point.setTo(2, 2)` ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `x` | number | | The horizontal value of this point. | | `y` | number | <optional> | The vertical value of this point. If not given the x value will be used in its place. | ##### Returns [Phaser.Point](phaser.point) - This Point object. Useful for chaining method calls. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 68](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L68)) ### subtract(x, y) → {[Phaser.Point](phaser.point)} Subtracts the given x and y values from this Point. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The value to subtract from Point.x. | | `y` | number | The value to subtract from Point.y. | ##### Returns [Phaser.Point](phaser.point) - This Point object. Useful for chaining method calls. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 122](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L122)) ### toString() → {string} Returns a string representation of this object. ##### Returns string - A string representation of the instance. Source code: [geom/Point.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js) ([Line 475](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Point.js#L475))
programming_docs
phaser Class: Phaser.Physics.P2.Body Class: Phaser.Physics.P2.Body ============================= Constructor ----------- ### new Body(game, sprite, x, y, mass) The Physics Body is typically linked to a single Sprite and defines properties that determine how the physics body is simulated. These properties affect how the body reacts to forces, what forces it generates on itself (to simulate friction), and how it reacts to collisions in the scene. In most cases, the properties are used to simulate physical effects. Each body also has its own property values that determine exactly how it reacts to forces and collisions in the scene. By default a single Rectangle shape is added to the Body that matches the dimensions of the parent Sprite. See addShape, removeShape, clearShapes to add extra shapes around the Body. Note: When bound to a Sprite to avoid single-pixel jitters on mobile devices we strongly recommend using Sprite sizes that are even on both axis, i.e. 128x128 not 127x127. Note: When a game object is given a P2 body it has its anchor x/y set to 0.5, so it becomes centered. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | | Game reference to the currently running game. | | `sprite` | [Phaser.Sprite](phaser.sprite) | <optional> | | The Sprite object this physics body belongs to. | | `x` | number | <optional> | 0 | The x coordinate of this Body. | | `y` | number | <optional> | 0 | The y coordinate of this Body. | | `mass` | number | <optional> | 1 | The default mass of this Body (0 = static). | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 23](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L23)) Public Properties ----------------- ### <static> DYNAMIC : number Dynamic body. Dynamic bodies body can move and respond to collisions and forces. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1498](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1498)) ### <static> KINEMATIC : number Kinematic body. Kinematic bodies only moves according to its .velocity, and does not respond to collisions or force. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1514](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1514)) ### <static> STATIC : number Static body. Static bodies do not move, and they do not respond to forces or collision. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1506](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1506)) ### allowSleep : boolean - Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1603](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1603)) ### angle : number The angle of the Body in degrees from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement Body.angle = 450 is the same as Body.angle = 90. If you wish to work in radians instead of degrees use the property Body.rotation instead. Working in radians is faster as it doesn't have to convert values. The angle of this Body in degrees. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1626](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1626)) ### angularDamping : number Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. The angular damping acting acting on the body. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1650](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1650)) ### angularForce : number The angular force acting on the body. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1671](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1671)) ### angularVelocity : number The angular velocity of the body. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1691](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1691)) ### collidesWith :array Array of CollisionGroups that this Bodies shapes collide with. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L112)) ### collideWorldBounds : boolean A Body can be set to collide against the World bounds automatically if this is set to true. Otherwise it will leave the World. Note that this only applies if your World has bounds! The response to the collision should be managed via CollisionMaterials. Also note that when you set this it will only effect Body shapes that already exist. If you then add further shapes to your Body after setting this it will *not* proactively set them to collide with the bounds. Should the Body collide with the World bounds? Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1949](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1949)) ### damping : number Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. The linear damping acting on the body in the velocity direction. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1711](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1711)) ### <internal> data : [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) The p2 Body data. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 59](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L59)) ### debug : boolean Enable or disable debug drawing of this body Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1920](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1920)) ### debugBody : [Phaser.Physics.P2.BodyDebug](phaser.physics.p2.bodydebug) Reference to the debug body. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 122](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L122)) ### dirty : boolean Internally used by Sprite.x/y Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 127](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L127)) ### dynamic : boolean Returns true if the Body is dynamic. Setting Body.dynamic to 'false' will make it static. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1545](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1545)) ### fixedRotation : boolean - Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1732](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1732)) ### force : [Phaser.Physics.P2.InversePointProxy](phaser.physics.p2.inversepointproxy) The force applied to the body. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 71](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L71)) ### game : [Phaser.Game](phaser.game) Local reference to game. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 33](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L33)) ### gravity : [Phaser.Point](phaser.point) A locally applied gravity force to the Body. Applied directly before the world step. NOTE: Not currently implemented. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 76](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L76)) ### [readonly] id : number The Body ID. Each Body that has been added to the World has a unique ID. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1905](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1905)) ### inertia : number The inertia of the body around the Z axis.. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1755](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1755)) ### kinematic : boolean Returns true if the Body is kinematic. Setting Body.kinematic to 'false' will make it static. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1574](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1574)) ### mass : number The mass of the body. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1775](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1775)) ### motionState : number The type of motion this body has. Should be one of: Body.STATIC (the body does not move), Body.DYNAMIC (body can move and respond to collisions) and Body.KINEMATIC (only moves according to its .velocity). Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1799](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1799)) ### offset : [Phaser.Point](phaser.point) The offset of the Physics Body from the Sprite x/y position. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 53](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L53)) ### onBeginContact : [Phaser.Signal](phaser.signal) Dispatched when a first contact is created between shapes in two bodies. This event is fired during the step, so collision has already taken place. The event will be sent 5 arguments in this order: The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world. The p2.Body this Body is in contact with. The Shape from this body that caused the contact. The Shape from the contact body. The Contact Equation data array. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 92](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L92)) ### onEndContact : [Phaser.Signal](phaser.signal) Dispatched when contact ends between shapes in two bodies. This event is fired during the step, so collision has already taken place. The event will be sent 4 arguments in this order: The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world. The p2.Body this Body has ended contact with. The Shape from this body that caused the original contact. The Shape from the contact body. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 107](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L107)) ### removeNextStep : boolean To avoid deleting this body during a physics step, and causing all kinds of problems, set removeNextStep to true to have it removed in the next preUpdate. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 117](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L117)) ### rotation : number The angle of the Body in radians. If you wish to work in degrees instead of radians use the Body.angle property instead. Working in radians is faster as it doesn't have to convert values. The angle of this Body in radians. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1822](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1822)) ### sleepSpeedLimit : number . Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1845](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1845)) ### sprite : [Phaser.Sprite](phaser.sprite) Reference to the parent Sprite. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 43](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L43)) ### static : boolean Returns true if the Body is static. Setting Body.static to 'false' will make it dynamic. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1516](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1516)) ### type : number The type of physics system this body belongs to. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 48](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L48)) ### velocity : [Phaser.Physics.P2.InversePointProxy](phaser.physics.p2.inversepointproxy) The velocity of the body. Set velocity.x to a negative value to move to the left, position to the right. velocity.y negative values move up, positive move down. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 66](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L66)) ### world : [Phaser.Physics.P2](phaser.physics.p2) Local reference to the P2 World. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L38)) ### x : number The x coordinate of this Body. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1865](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1865)) ### y : number The y coordinate of this Body. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1885](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1885)) Public Methods -------------- ### addCapsule(length, radius, offsetX, offsetY, rotation) → {p2.Capsule} Adds a Capsule shape to this Body. You can control the offset from the center of the body and the rotation. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `length` | number | | | The distance between the end points in pixels. | | `radius` | number | | | Radius of the capsule in pixels. | | `offsetX` | number | <optional> | 0 | Local horizontal offset of the shape relative to the body center of mass. | | `offsetY` | number | <optional> | 0 | Local vertical offset of the shape relative to the body center of mass. | | `rotation` | number | <optional> | 0 | Local rotation of the shape relative to the body center of mass, specified in radians. | ##### Returns p2.Capsule - The Capsule shape that was added to the Body. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1108](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1108)) ### addCircle(radius, offsetX, offsetY, rotation) → {p2.Circle} Adds a Circle shape to this Body. You can control the offset from the center of the body and the rotation. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `radius` | number | | | The radius of this circle (in pixels) | | `offsetX` | number | <optional> | 0 | Local horizontal offset of the shape relative to the body center of mass. | | `offsetY` | number | <optional> | 0 | Local vertical offset of the shape relative to the body center of mass. | | `rotation` | number | <optional> | 0 | Local rotation of the shape relative to the body center of mass, specified in radians. | ##### Returns p2.Circle - The Circle shape that was added to the Body. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1017](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1017)) ### addFixture(fixtureData) → {array} Add a polygon fixture. This is used during #loadPolygon. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `fixtureData` | string | The data for the fixture. It contains: isSensor, filter (collision) and the actual polygon shapes. | ##### Returns array - An array containing the generated shapes for the given polygon. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1350](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1350)) ### addLine(length, offsetX, offsetY, rotation) → {p2.Line} Adds a Line shape to this Body. The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. You can control the offset from the center of the body and the rotation. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `length` | number | | | The length of this line (in pixels) | | `offsetX` | number | <optional> | 0 | Local horizontal offset of the shape relative to the body center of mass. | | `offsetY` | number | <optional> | 0 | Local vertical offset of the shape relative to the body center of mass. | | `rotation` | number | <optional> | 0 | Local rotation of the shape relative to the body center of mass, specified in radians. | ##### Returns p2.Line - The Line shape that was added to the Body. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1088](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1088)) ### addParticle(offsetX, offsetY, rotation) → {p2.Particle} Adds a Particle shape to this Body. You can control the offset from the center of the body and the rotation. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `offsetX` | number | <optional> | 0 | Local horizontal offset of the shape relative to the body center of mass. | | `offsetY` | number | <optional> | 0 | Local vertical offset of the shape relative to the body center of mass. | | `rotation` | number | <optional> | 0 | Local rotation of the shape relative to the body center of mass, specified in radians. | ##### Returns p2.Particle - The Particle shape that was added to the Body. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1071](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1071)) ### addPhaserPolygon(key, object) → {Array} Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. The shape data format is based on the output of the [custom phaser exporter](https://github.com/photonstorm/phaser/tree/master/resources/PhysicsEditor%2520Exporter) for [PhysicsEditor](https://www.codeandweb.com/physicseditor) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the Physics Data file as stored in Game.Cache. | | `object` | string | The key of the object within the Physics data file that you wish to load the shape data from. | ##### Returns Array - A list of created fixtures to be used with Phaser.Physics.P2.FixtureList Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1310](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1310)) ### addPlane(offsetX, offsetY, rotation) → {p2.Plane} Adds a Plane shape to this Body. The plane is facing in the Y direction. You can control the offset from the center of the body and the rotation. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `offsetX` | number | <optional> | 0 | Local horizontal offset of the shape relative to the body center of mass. | | `offsetY` | number | <optional> | 0 | Local vertical offset of the shape relative to the body center of mass. | | `rotation` | number | <optional> | 0 | Local rotation of the shape relative to the body center of mass, specified in radians. | ##### Returns p2.Plane - The Plane shape that was added to the Body. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1054](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1054)) ### addPolygon(options, points) → {boolean} Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. The shape must be simple and without holes. This function expects the x.y values to be given in pixels. If you want to provide them at p2 world scales then call Body.data.fromPolygon directly. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `options` | object | An object containing the build options: Properties | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `optimalDecomp` | boolean | <optional> | false | Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. | | `skipSimpleCheck` | boolean | <optional> | false | Set to true if you already know that the path is not intersecting itself. | | `removeCollinearPoints` | boolean | number | <optional> | false | Set to a number (angle threshold value) to remove collinear points, or false to keep all points. | | | `points` | Array.<number> | number | An array of 2d vectors that form the convex or concave polygon. Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. | ##### Returns boolean - True on success, else false. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1128](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1128)) ### addRectangle(width, height, offsetX, offsetY, rotation) → {p2.Box} Adds a Rectangle shape to this Body. You can control the offset from the center of the body and the rotation. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `width` | number | | | The width of the rectangle in pixels. | | `height` | number | | | The height of the rectangle in pixels. | | `offsetX` | number | <optional> | 0 | Local horizontal offset of the shape relative to the body center of mass. | | `offsetY` | number | <optional> | 0 | Local vertical offset of the shape relative to the body center of mass. | | `rotation` | number | <optional> | 0 | Local rotation of the shape relative to the body center of mass, specified in radians. | ##### Returns p2.Box - The shape that was added to the Body. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1035](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1035)) ### addShape(shape, offsetX, offsetY, rotation) → {p2.Shape} Add a shape to the body. You can pass a local transform when adding a shape, so that the shape gets an offset and an angle relative to the body center of mass. Will automatically update the mass properties and bounding radius. If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `shape` | p2.Shape | | | The shape to add to the body. | | `offsetX` | number | <optional> | 0 | Local horizontal offset of the shape relative to the body center of mass. | | `offsetY` | number | <optional> | 0 | Local vertical offset of the shape relative to the body center of mass. | | `rotation` | number | <optional> | 0 | Local rotation of the shape relative to the body center of mass, specified in radians. | ##### Returns p2.Shape - The shape that was added to the body. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 992](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L992)) ### addToWorld() Adds this physics body to the world. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 904](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L904)) ### adjustCenterOfMass() Moves the shape offsets so their center of mass becomes the body center of mass. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 490](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L490)) ### applyDamping(dt) Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `dt` | number | Current time step. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 516](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L516)) ### applyForce(force, worldX, worldY) Apply force to a world point. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `force` | Float32Array | Array | The force vector to add. | | `worldX` | number | The world x point to apply the force on. | | `worldY` | number | The world y point to apply the force on. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 561](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L561)) ### applyImpulse(impulse, worldX, worldY) Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force \* time). Impulses will be added to Body.velocity and Body.angularVelocity. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `impulse` | Float32Array | Array | The impulse vector to add, oriented in world space. | | `worldX` | number | A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass. | | `worldY` | number | A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 528](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L528)) ### applyImpulseLocal(impulse, localX, localY) Apply impulse to a point local to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force \* time). Impulses will be added to Body.velocity and Body.angularVelocity. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `impulse` | Float32Array | Array | The impulse vector to add, oriented in local space. | | `localX` | number | A local point on the body. | | `localY` | number | A local point on the body. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 544](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L544)) ### clearCollision(clearGroup, clearMask, shape) Clears the collision data from the shapes in this Body. Optionally clears Group and/or Mask. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `clearGroup` | boolean | <optional> | true | Clear the collisionGroup value from the shape/s? | | `clearMask` | boolean | <optional> | true | Clear the collisionMask value from the shape/s? | | `shape` | p2.Shape | <optional> | | An optional Shape. If not provided the collision data will be cleared from all Shapes in this Body. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 323](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L323)) ### clearShapes() Removes all Shapes from this Body. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 974](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L974)) ### collides(group, callback, callbackContext, shape) Adds the given CollisionGroup, or array of CollisionGroups, to the list of groups that this body will collide with and updates the collision masks. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `group` | Phaser.Physics.CollisionGroup | array | | The Collision Group or Array of Collision Groups that this Bodies shapes will collide with. | | `callback` | function | <optional> | Optional callback that will be triggered when this Body impacts with the given Group. | | `callbackContext` | object | <optional> | The context under which the callback will be called. | | `shape` | p2.Shape | <optional> | An optional Shape. If not provided the collision mask will be added to all Shapes in this Body. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 435](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L435)) ### createBodyCallback(object, callback, callbackContext) Sets a callback to be fired any time a shape in this Body impacts with a shape in the given Body. The impact test is performed against body.id values. The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `object` | [Phaser.Sprite](phaser.sprite) | [Phaser.TileSprite](phaser.tilesprite) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | The object to send impact events for. | | `callback` | function | The callback to fire on impact. Set to null to clear a previously set callback. | | `callbackContext` | object | The context under which the callback will fire. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 180](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L180)) ### createGroupCallback(group, callback, callbackContext) Sets a callback to be fired any time this Body impacts with the given Group. The impact test is performed against shape.collisionGroup values. The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. This callback will only fire if this Body has been assigned a collision group. Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `group` | Phaser.Physics.CollisionGroup | The Group to send impact events for. | | `callback` | function | The callback to fire on impact. Set to null to clear a previously set callback. | | `callbackContext` | object | The context under which the callback will fire. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 220](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L220)) ### destroy() Destroys this Body and all references it holds to other objects. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 943](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L943)) ### getCollisionMask() → {number} Gets the collision bitmask from the groups this body collides with. ##### Returns number - The bitmask. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 247](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L247)) ### getVelocityAtPoint(result, relativePoint) → {Array} Gets the velocity of a point in the body. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `result` | Array | A vector to store the result in. | | `relativePoint` | Array | A world oriented vector, indicating the position of the point to get the velocity from. | ##### Returns Array - The result vector. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 502](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L502)) ### loadPolygon(key, object) → {boolean} Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. As well as reading the data from the Cache you can also pass `null` as the first argument and a physics data object as the second. When doing this you must ensure the structure of the object is correct in advance. For more details see the format of the Lime / Corona Physics Editor export. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the Physics Data file as stored in Game.Cache. Alternatively set to `null` and pass the data as the 2nd argument. | | `object` | string | object | The key of the object within the Physics data file that you wish to load the shape data from, or if key is null pass the actual physics data object itself as this parameter. | ##### Returns boolean - True on success, else false. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1422](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1422)) ### moveBackward(speed) Moves the Body backwards based on its current angle and the given speed. The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `speed` | number | The speed at which it should move backwards. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 691](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L691)) ### moveDown(speed) If this Body is dynamic then this will move it down by setting its y velocity to the given speed. The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `speed` | number | The speed at which it should move down, in pixels per second. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 815](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L815)) ### moveForward(speed) Moves the Body forwards based on its current angle and the given speed. The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `speed` | number | The speed at which it should move forwards. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 674](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L674)) ### moveLeft(speed) If this Body is dynamic then this will move it to the left by setting its x velocity to the given speed. The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `speed` | number | The speed at which it should move to the left, in pixels per second. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 776](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L776)) ### moveRight(speed) If this Body is dynamic then this will move it to the right by setting its x velocity to the given speed. The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `speed` | number | The speed at which it should move to the right, in pixels per second. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 789](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L789)) ### moveUp(speed) If this Body is dynamic then this will move it up by setting its y velocity to the given speed. The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `speed` | number | The speed at which it should move up, in pixels per second. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 802](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L802)) ### <internal> postUpdate() Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 846](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L846)) ### <internal> preUpdate() Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 828](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L828)) ### removeCollisionGroup(group, clearCallback, shape) Removes the given CollisionGroup, or array of CollisionGroups, from the list of groups that this body will collide with and updates the collision masks. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `group` | Phaser.Physics.CollisionGroup | array | | | The Collision Group or Array of Collision Groups that this Bodies shapes should not collide with anymore. | | `clearCallback` | boolean | <optional> | true | Clear the callback that will be triggered when this Body impacts with the given Group? | | `shape` | p2.Shape | <optional> | | An optional Shape. If not provided the updated collision mask will be added to all Shapes in this Body. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 371](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L371)) ### removeFromWorld() Removes this physics body from the world. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 929](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L929)) ### removeShape(shape) → {boolean} Remove a shape from the body. Will automatically update the mass properties and bounding radius. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `shape` | p2.Circle | p2.Rectangle | p2.Plane | p2.Line | p2.Particle | The shape to remove from the body. | ##### Returns boolean - True if the shape was found and removed, else false. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1194](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1194)) ### reset(x, y, resetDamping, resetMass) Resets the Body force, velocity (linear and angular) and rotation. Optionally resets damping and mass. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The new x position of the Body. | | `y` | number | | | The new x position of the Body. | | `resetDamping` | boolean | <optional> | false | Resets the linear and angular damping. | | `resetMass` | boolean | <optional> | false | Sets the Body mass back to 1. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 871](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L871)) ### reverse(speed) Applies a force to the Body that causes it to 'thrust' backwards (in reverse), based on its current angle and the given speed. The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `speed` | number | The speed at which it should reverse. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 759](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L759)) ### rotateLeft(speed) This will rotate the Body by the given speed to the left (counter-clockwise). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `speed` | number | The speed at which it should rotate. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 650](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L650)) ### rotateRight(speed) This will rotate the Body by the given speed to the left (clockwise). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `speed` | number | The speed at which it should rotate. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 662](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L662)) ### setCircle(radius, offsetX, offsetY, rotation) Clears any previously set shapes. Then creates a new Circle shape and adds it to this Body. If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `radius` | number | | | The radius of this circle (in pixels) | | `offsetX` | number | <optional> | 0 | Local horizontal offset of the shape relative to the body center of mass. | | `offsetY` | number | <optional> | 0 | Local vertical offset of the shape relative to the body center of mass. | | `rotation` | number | <optional> | 0 | Local rotation of the shape relative to the body center of mass, specified in radians. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1210](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1210)) ### setCollisionGroup(group, shape) Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. This also resets the collisionMask. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `group` | Phaser.Physics.CollisionGroup | | The Collision Group that this Bodies shapes will use. | | `shape` | p2.Shape | <optional> | An optional Shape. If not provided the collision group will be added to all Shapes in this Body. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 295](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L295)) ### setMaterial(material, shape) Adds the given Material to all Shapes that belong to this Body. If you only wish to apply it to a specific Shape in this Body then provide that as the 2nd parameter. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `material` | [Phaser.Physics.P2.Material](phaser.physics.p2.material) | | The Material that will be applied. | | `shape` | p2.Shape | <optional> | An optional Shape. If not provided the Material will be added to all Shapes in this Body. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1272](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1272)) ### setRectangle(width, height, offsetX, offsetY, rotation) → {p2.Rectangle} Clears any previously set shapes. The creates a new Rectangle shape at the given size and offset, and adds it to this Body. If you wish to create a Rectangle to match the size of a Sprite or Image see Body.setRectangleFromSprite. If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `width` | number | <optional> | 16 | The width of the rectangle in pixels. | | `height` | number | <optional> | 16 | The height of the rectangle in pixels. | | `offsetX` | number | <optional> | 0 | Local horizontal offset of the shape relative to the body center of mass. | | `offsetY` | number | <optional> | 0 | Local vertical offset of the shape relative to the body center of mass. | | `rotation` | number | <optional> | 0 | Local rotation of the shape relative to the body center of mass, specified in radians. | ##### Returns p2.Rectangle - The Rectangle shape that was added to the Body. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1228](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1228)) ### setRectangleFromSprite(sprite) → {p2.Rectangle} Clears any previously set shapes. Then creates a Rectangle shape sized to match the dimensions and orientation of the Sprite given. If no Sprite is given it defaults to using the parent of this Body. If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `sprite` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | <optional> | The Sprite on which the Rectangle will get its dimensions. | ##### Returns p2.Rectangle - The Rectangle shape that was added to the Body. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1252](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1252)) ### setZeroDamping() Sets the Body damping and angularDamping to zero. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 612](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L612)) ### setZeroForce() Sets the force on the body to zero. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 578](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L578)) ### setZeroRotation() If this Body is dynamic then this will zero its angular velocity. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 589](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L589)) ### setZeroVelocity() If this Body is dynamic then this will zero its velocity on both axis. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 600](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L600)) ### shapeChanged() Updates the debug draw if any body shapes change. Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 1296](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L1296)) ### thrust(speed) Applies a force to the Body that causes it to 'thrust' forwards, based on its current angle and the given speed. The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `speed` | number | The speed at which it should thrust. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 708](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L708)) ### thrustLeft(speed) Applies a force to the Body that causes it to 'thrust' to the left, based on its current angle and the given speed. The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `speed` | number | The speed at which it should move to the left. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 725](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L725)) ### thrustRight(speed) Applies a force to the Body that causes it to 'thrust' to the right, based on its current angle and the given speed. The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `speed` | number | The speed at which it should move to the right. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 742](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L742)) ### toLocalFrame(out, worldPoint) Transform a world point to local body frame. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `out` | Float32Array | Array | The vector to store the result in. | | `worldPoint` | Float32Array | Array | The input world vector. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 624](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L624)) ### toWorldFrame(out, localPoint) Transform a local point to world frame. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `out` | Array | The vector to store the result in. | | `localPoint` | Array | The input local vector. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 637](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L637)) ### updateCollisionMask(shape) Updates the collisionMask. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `shape` | p2.Shape | <optional> | An optional Shape. If not provided the collision group will be added to all Shapes in this Body. | Source code: [physics/p2/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js) ([Line 271](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Body.js#L271))
programming_docs
phaser Class: Phaser.QuadTree Class: Phaser.QuadTree ====================== Constructor ----------- ### new QuadTree(x, y, width, height, maxObjects, maxLevels, level) A QuadTree implementation. The original code was a conversion of the Java code posted to GameDevTuts. However I've tweaked it massively to add node indexing, removed lots of temp. var creation and significantly increased performance as a result. Original version at https://github.com/timohausmann/quadtree-js/ ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The top left coordinate of the quadtree. | | `y` | number | | | The top left coordinate of the quadtree. | | `width` | number | | | The width of the quadtree in pixels. | | `height` | number | | | The height of the quadtree in pixels. | | `maxObjects` | number | <optional> | 10 | The maximum number of objects per node. | | `maxLevels` | number | <optional> | 4 | The maximum number of levels to iterate to. | | `level` | number | <optional> | 0 | Which level is this? | Source code: [math/QuadTree.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js) ([Line 23](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js#L23)) Public Properties ----------------- ### bounds : Object Object that contains the quadtree bounds. Source code: [math/QuadTree.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js#L45)) ### level : number The current level. Source code: [math/QuadTree.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js) ([Line 40](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js#L40)) ### maxLevels : number The maximum number of levels to break down to. Default Value * 4 Source code: [math/QuadTree.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js) ([Line 35](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js#L35)) ### maxObjects : number The maximum number of objects per node. Default Value * 10 Source code: [math/QuadTree.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js#L29)) ### nodes :array Array of associated child nodes. Source code: [math/QuadTree.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js#L55)) ### objects :array Array of quadtree children. Source code: [math/QuadTree.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js#L50)) Public Methods -------------- ### clear() Clear the quadtree. Source code: [math/QuadTree.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js) ([Line 295](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js#L295)) ### getIndex(rect) → {number} Determine which node the object belongs to. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `rect` | [Phaser.Rectangle](phaser.rectangle) | object | The bounds in which to check. | ##### Returns number - index - Index of the subnode (0-3), or -1 if rect cannot completely fit within a subnode and is part of the parent node. Source code: [math/QuadTree.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js) ([Line 203](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js#L203)) ### insert(body) Insert the object into the node. If the node exceeds the capacity, it will split and add all objects to their corresponding subnodes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `body` | [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | object | The Body object to insert into the quadtree. Can be any object so long as it exposes x, y, right and bottom properties. | Source code: [math/QuadTree.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js) ([Line 151](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js#L151)) ### populate(group) Populates this quadtree with the children of the given Group. In order to be added the child must exist and have a body property. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `group` | [Phaser.Group](phaser.group) | The Group to add to the quadtree. | Source code: [math/QuadTree.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js) ([Line 103](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js#L103)) ### populateHandler(sprite) Handler for the populate method. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `sprite` | [Phaser.Sprite](phaser.sprite) | object | The Sprite to check. | Source code: [math/QuadTree.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js) ([Line 115](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js#L115)) ### reset(x, y, width, height, maxObjects, maxLevels, level) Resets the QuadTree. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The top left coordinate of the quadtree. | | `y` | number | | | The top left coordinate of the quadtree. | | `width` | number | | | The width of the quadtree in pixels. | | `height` | number | | | The height of the quadtree in pixels. | | `maxObjects` | number | <optional> | 10 | The maximum number of objects per node. | | `maxLevels` | number | <optional> | 4 | The maximum number of levels to iterate to. | | `level` | number | <optional> | 0 | Which level is this? | Source code: [math/QuadTree.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js) ([Line 69](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js#L69)) ### retrieve(source) → {array} Return all objects that could collide with the given Sprite or Rectangle. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `source` | [Phaser.Sprite](phaser.sprite) | [Phaser.Rectangle](phaser.rectangle) | The source object to check the QuadTree against. Either a Sprite or Rectangle. | ##### Returns array - * Array with all detected objects. Source code: [math/QuadTree.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js) ([Line 247](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js#L247)) ### split() Split the node into 4 subnodes Source code: [math/QuadTree.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js) ([Line 130](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/QuadTree.js#L130)) phaser Class: Phaser.Physics.Arcade Class: Phaser.Physics.Arcade ============================ Constructor ----------- ### new Arcade(game) The Arcade Physics world. Contains Arcade Physics related collision, overlap and motion methods. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | reference to the current game instance. | Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 14](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L14)) Classes ------- [Body](phaser.physics.arcade.body) [TilemapCollision](phaser.physics.arcade.tilemapcollision) Public Properties ----------------- ### [static] BOTTOM\_TOP : number A constant used for the sortDirection value. Use this if your game world is narrow but tall and scrolls from the bottom to the top (i.e. Commando or a vertically scrolling shoot-em-up) Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 130](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L130)) ### [static] LEFT\_RIGHT : number A constant used for the sortDirection value. Use this if your game world is wide but short and scrolls from the left to the right (i.e. Mario) Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 106](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L106)) ### [static] RIGHT\_LEFT : number A constant used for the sortDirection value. Use this if your game world is wide but short and scrolls from the right to the left (i.e. Mario backwards) Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 114](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L114)) ### [static] SORT\_NONE : number A constant used for the sortDirection value. Use this if you don't wish to perform any pre-collision sorting at all, or will manually sort your Groups. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L98)) ### [static] TOP\_BOTTOM : number A constant used for the sortDirection value. Use this if your game world is narrow but tall and scrolls from the top to the bottom (i.e. Dig Dug) Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 122](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L122)) ### bounds : [Phaser.Rectangle](phaser.rectangle) The bounds inside of which the physics world exists. Defaults to match the world bounds. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L29)) ### checkCollision : Object Set the checkCollision properties to control for which bounds collision is processed. For example checkCollision.down = false means Bodies cannot collide with the World.bounds.bottom. An object containing allowed collision flags. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 36](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L36)) ### forceX : boolean If true World.separate will always separate on the X axis before Y. Otherwise it will check gravity totals first. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 56](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L56)) ### game : [Phaser.Game](phaser.game) Local reference to game. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 19](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L19)) ### gravity : [Phaser.Point](phaser.point) The World gravity setting. Defaults to x: 0, y: 0, or no gravity. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L24)) ### isPaused : boolean If `true` the `Body.preUpdate` method will be skipped, halting all motion for all bodies. Note that other methods such as `collide` will still work, so be careful not to call them on paused bodies. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 72](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L72)) ### maxLevels : number Used by the QuadTree to set the maximum number of iteration levels. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L46)) ### maxObjects : number Used by the QuadTree to set the maximum number of objects per quad. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 41](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L41)) ### OVERLAP\_BIAS : number A value added to the delta values during collision checks. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L51)) ### quadTree : [Phaser.QuadTree](phaser.quadtree) The world QuadTree. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 77](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L77)) ### skipQuadTree : boolean If true the QuadTree will not be used for any collision. QuadTrees are great if objects are well spread out in your game, otherwise they are a performance hit. If you enable this you can disable on a per body basis via `Body.skipQuadTree`. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 67](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L67)) ### sortDirection : number Used when colliding a Sprite vs. a Group, or a Group vs. a Group, this defines the direction the sort is based on. Default is Phaser.Physics.Arcade.LEFT\_RIGHT. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 62](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L62)) Public Methods -------------- ### accelerateToObject(displayObject, destination, speed, xSpeedMax, ySpeedMax) → {number} Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) You must give a maximum speed value, beyond which the display object won't go any faster. Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. Note: The display object doesn't stop moving once it reaches the destination coordinates. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `displayObject` | any | | | The display object to move. | | `destination` | any | | | The display object to move towards. Can be any object but must have visible x/y properties. | | `speed` | number | <optional> | 60 | The speed it will accelerate in pixels per second. | | `xSpeedMax` | number | <optional> | 500 | The maximum x velocity the display object can reach. | | `ySpeedMax` | number | <optional> | 500 | The maximum y velocity the display object can reach. | ##### Returns number - The angle (in radians) that the object should be visually set to in order to match its new trajectory. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 1829](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L1829)) ### accelerateToPointer(displayObject, pointer, speed, xSpeedMax, ySpeedMax) → {number} Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) You must give a maximum speed value, beyond which the display object won't go any faster. Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. Note: The display object doesn't stop moving once it reaches the destination coordinates. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `displayObject` | any | | | The display object to move. | | `pointer` | [Phaser.Pointer](phaser.pointer) | <optional> | | The pointer to move towards. Defaults to Phaser.Input.activePointer. | | `speed` | number | <optional> | 60 | The speed it will accelerate in pixels per second. | | `xSpeedMax` | number | <optional> | 500 | The maximum x velocity the display object can reach. | | `ySpeedMax` | number | <optional> | 500 | The maximum y velocity the display object can reach. | ##### Returns number - The angle (in radians) that the object should be visually set to in order to match its new trajectory. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 1858](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L1858)) ### accelerateToXY(displayObject, x, y, speed, xSpeedMax, ySpeedMax) → {number} Sets the acceleration.x/y property on the display object so it will move towards the x/y coordinates at the given speed (in pixels per second sq.) You must give a maximum speed value, beyond which the display object won't go any faster. Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. Note: The display object doesn't stop moving once it reaches the destination coordinates. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `displayObject` | any | | | The display object to move. | | `x` | number | | | The x coordinate to accelerate towards. | | `y` | number | | | The y coordinate to accelerate towards. | | `speed` | number | <optional> | 60 | The speed it will accelerate in pixels per second. | | `xSpeedMax` | number | <optional> | 500 | The maximum x velocity the display object can reach. | | `ySpeedMax` | number | <optional> | 500 | The maximum y velocity the display object can reach. | ##### Returns number - The angle (in radians) that the object should be visually set to in order to match its new trajectory. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 1888](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L1888)) ### accelerationFromRotation(rotation, speed, point) → {[Phaser.Point](phaser.point)} Given the rotation (in radians) and speed calculate the acceleration and return it as a Point object, or set it to the given point object. One way to use this is: accelerationFromRotation(rotation, 200, sprite.acceleration) which will set the values directly to the sprites acceleration and not create a new Point object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `rotation` | number | | | The angle in radians. | | `speed` | number | <optional> | 60 | The speed it will move, in pixels per second sq. | | `point` | [Phaser.Point](phaser.point) | object | <optional> | | The Point object in which the x and y properties will be set to the calculated acceleration. | ##### Returns [Phaser.Point](phaser.point) - * A Point where point.x contains the acceleration x value and point.y contains the acceleration y value. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 1810](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L1810)) ### angleBetween(source, target, world) → {number} Find the angle in radians between two display objects (like Sprites). The optional `world` argument allows you to return the result based on the Game Objects `world` property, instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, or parent Game Object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `source` | any | | | The Display Object to test from. | | `target` | any | | | The Display Object to test to. | | `world` | boolean | <optional> | false | Calculate the angle using World coordinates (true), or Object coordinates (false, the default) | ##### Returns number - The angle in radians between the source and target display objects. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 1996](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L1996)) ### angleBetweenCenters(source, target) → {number} Find the angle in radians between centers of two display objects (like Sprites). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `source` | any | The Display Object to test from. | | `target` | any | The Display Object to test to. | ##### Returns number - The angle in radians between the source and target display objects. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 2024](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L2024)) ### angleToPointer(displayObject, pointer, world) → {number} Find the angle in radians between a display object (like a Sprite) and a Pointer, taking their x/y and center into account. The optional `world` argument allows you to return the result based on the Game Objects `world` property, instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, or parent Game Object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `displayObject` | any | | | The Display Object to test from. | | `pointer` | [Phaser.Pointer](phaser.pointer) | <optional> | | The Phaser.Pointer to test to. If none is given then Input.activePointer is used. | | `world` | boolean | <optional> | false | Calculate the angle using World coordinates (true), or Object coordinates (false, the default) | ##### Returns number - The angle in radians between displayObject.x/y to Pointer.x/y Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 2070](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L2070)) ### angleToXY(displayObject, x, y, world) → {number} Find the angle in radians between a display object (like a Sprite) and the given x/y coordinate. The optional `world` argument allows you to return the result based on the Game Objects `world` property, instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, or parent Game Object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `displayObject` | any | | | The Display Object to test from. | | `x` | number | | | The x coordinate to get the angle to. | | `y` | number | | | The y coordinate to get the angle to. | | `world` | boolean | <optional> | false | Calculate the angle using World coordinates (true), or Object coordinates (false, the default) | ##### Returns number - The angle in radians between displayObject.x/y to Pointer.x/y Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 2041](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L2041)) ### circleBodyIntersects(circle, body) → {boolean} Checks to see if a circular Body intersects with a Rectangular Body. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `circle` | [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | The Body with `isCircle` set. | | `body` | [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | The Body with `isCircle` not set (i.e. uses Rectangle shape) | ##### Returns boolean - Returns true if the bodies intersect, otherwise false. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 1125](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L1125)) ### collide(object1, object2, collideCallback, processCallback, callbackContext) → {boolean} Checks for collision between two game objects. You can perform Sprite vs. Sprite, Sprite vs. Group, Group vs. Group, Sprite vs. Tilemap Layer or Group vs. Tilemap Layer collisions. Both the first and second parameter can be arrays of objects, of differing types. If two arrays are passed, the contents of the first parameter will be tested against all contents of the 2nd parameter. The objects are also automatically separated. If you don't require separation then use ArcadePhysics.overlap instead. An optional processCallback can be provided. If given this function will be called when two sprites are found to be colliding. It is called before any separation takes place, giving you the chance to perform additional checks. If the function returns true then the collision and separation is carried out. If it returns false it is skipped. The collideCallback is an optional function that is only called if two sprites collide. If a processCallback has been set then it needs to return true for collideCallback to be called. NOTE: This function is not recursive, and will not test against children of objects passed (i.e. Groups or Tilemaps within other Groups). ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `object1` | [Phaser.Sprite](phaser.sprite) | [Phaser.Group](phaser.group) | Phaser.Particles.Emitter | [Phaser.TilemapLayer](phaser.tilemaplayer) | array | | | The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer. | | `object2` | [Phaser.Sprite](phaser.sprite) | [Phaser.Group](phaser.group) | Phaser.Particles.Emitter | [Phaser.TilemapLayer](phaser.tilemaplayer) | array | | | The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. | | `collideCallback` | function | <optional> | null | An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter. | | `processCallback` | function | <optional> | null | A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter. | | `callbackContext` | object | <optional> | | The context in which to run the callbacks. | ##### Returns boolean - True if a collision occurred otherwise false. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 375](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L375)) ### computeVelocity(axis, body, velocity, acceleration, drag, max) → {number} A tween-like function that takes a starting velocity and some other factors and returns an altered velocity. Based on a function in Flixel by @ADAMATOMIC ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `axis` | number | | | 0 for nothing, 1 for horizontal, 2 for vertical. | | `body` | [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | | | The Body object to be updated. | | `velocity` | number | | | Any component of velocity (e.g. 20). | | `acceleration` | number | | | Rate at which the velocity is changing. | | `drag` | number | | | Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set. | | `max` | number | <optional> | 10000 | An absolute value cap for the velocity. | ##### Returns number - The altered Velocity value. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 257](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L257)) ### distanceBetween(source, target, world) → {number} Find the distance between two display objects (like Sprites). The optional `world` argument allows you to return the result based on the Game Objects `world` property, instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, or parent Game Object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `source` | any | | | The Display Object to test from. | | `target` | any | | | The Display Object to test to. | | `world` | boolean | <optional> | false | Calculate the distance using World coordinates (true), or Object coordinates (false, the default) | ##### Returns number - The distance between the source and target objects. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 1918](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L1918)) ### distanceToPointer(displayObject, pointer, world) → {number} Find the distance between a display object (like a Sprite) and a Pointer. If no Pointer is given the Input.activePointer is used. The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. If you need to calculate from the center of a display object instead use the method distanceBetweenCenters() The optional `world` argument allows you to return the result based on the Game Objects `world` property, instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, or parent Game Object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `displayObject` | any | | | The Display Object to test from. | | `pointer` | [Phaser.Pointer](phaser.pointer) | <optional> | | The Phaser.Pointer to test to. If none is given then Input.activePointer is used. | | `world` | boolean | <optional> | false | Calculate the distance using World coordinates (true), or Object coordinates (false, the default) | ##### Returns number - The distance between the object and the Pointer. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 1969](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L1969)) ### distanceToXY(displayObject, x, y, world) → {number} Find the distance between a display object (like a Sprite) and the given x/y coordinates. The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. If you need to calculate from the center of a display object instead use the method distanceBetweenCenters() The optional `world` argument allows you to return the result based on the Game Objects `world` property, instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, or parent Game Object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `displayObject` | any | | | The Display Object to test from. | | `x` | number | | | The x coordinate to move towards. | | `y` | number | | | The y coordinate to move towards. | | `world` | boolean | <optional> | false | Calculate the distance using World coordinates (true), or Object coordinates (false, the default) | ##### Returns number - The distance between the object and the x/y coordinates. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 1942](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L1942)) ### enable(object, children) This will create an Arcade Physics body on the given game object or array of game objects. A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `object` | object | array | [Phaser.Group](phaser.group) | | | The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. | | `children` | boolean | <optional> | true | Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. | Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 160](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L160)) ### enableBody(object) Creates an Arcade Physics body on the given game object. A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. When you add an Arcade Physics body to an object it will automatically add the object into its parent Groups hash array. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `object` | object | The game object to create the physics body on. A body will only be created if this object has a null `body` property. | Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 216](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L216)) ### getObjectsAtLocation(x, y, group, callback, callbackContext, callbackArg) → {Array.<PIXI.DisplayObject>} Given a Group and a location this will check to see which Group children overlap with the coordinates. Each child will be sent to the given callback for further processing. Note that the children are not checked for depth order, but simply if they overlap the coordinate or not. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `x` | number | | The x coordinate to check. | | `y` | number | | The y coordinate to check. | | `group` | [Phaser.Group](phaser.group) | | The Group to check. | | `callback` | function | <optional> | A callback function that is called if the object overlaps the coordinates. The callback will be sent two parameters: the callbackArg and the Object that overlapped the location. | | `callbackContext` | object | <optional> | The context in which to run the callback. | | `callbackArg` | object | <optional> | An argument to pass to the callback. | ##### Returns Array.<PIXI.DisplayObject> - An array of the Sprites from the Group that overlapped the coordinates. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 1622](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L1622)) ### getObjectsUnderPointer(pointer, group, callback, callbackContext) → {Array.<PIXI.DisplayObject>} Given a Group and a Pointer this will check to see which Group children overlap with the Pointer coordinates. Each child will be sent to the given callback for further processing. Note that the children are not checked for depth order, but simply if they overlap the Pointer or not. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `pointer` | [Phaser.Pointer](phaser.pointer) | | The Pointer to check. | | `group` | [Phaser.Group](phaser.group) | | The Group to check. | | `callback` | function | <optional> | A callback function that is called if the object overlaps with the Pointer. The callback will be sent two parameters: the Pointer and the Object that overlapped with it. | | `callbackContext` | object | <optional> | The context in which to run the callback. | ##### Returns Array.<PIXI.DisplayObject> - An array of the Sprites from the Group that overlapped the Pointer coordinates. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 1599](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L1599)) ### getOverlapX(body1, body2, overlapOnly) → {float} Calculates the horizontal overlap between two Bodies and sets their properties accordingly, including: `touching.left`, `touching.right` and `overlapX`. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `body1` | [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | The first Body to separate. | | `body2` | [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | The second Body to separate. | | `overlapOnly` | boolean | Is this an overlap only check, or part of separation? | ##### Returns float - Returns the amount of horizontal overlap between the two bodies. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 1331](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L1331)) ### getOverlapY(body1, body2, overlapOnly) → {float} Calculates the vertical overlap between two Bodies and sets their properties accordingly, including: `touching.up`, `touching.down` and `overlapY`. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `body1` | [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | The first Body to separate. | | `body2` | [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | The second Body to separate. | | `overlapOnly` | boolean | Is this an overlap only check, or part of separation? | ##### Returns float - Returns the amount of vertical overlap between the two bodies. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 1395](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L1395)) ### intersects(body1, body2) → {boolean} Check for intersection against two bodies. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `body1` | [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | The first Body object to check. | | `body2` | [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | The second Body object to check. | ##### Returns boolean - True if they intersect, otherwise false. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 1061](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L1061)) ### moveToObject(displayObject, destination, speed, maxTime) → {number} Move the given display object towards the destination object at a steady velocity. If you specify a maxTime then it will adjust the speed (overwriting what you set) so it arrives at the destination in that number of seconds. Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. Note: The display object doesn't stop moving once it reaches the destination coordinates. Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `displayObject` | any | | | The display object to move. | | `destination` | any | | | The display object to move towards. Can be any object but must have visible x/y properties. | | `speed` | number | <optional> | 60 | The speed it will move, in pixels per second (default is 60 pixels/sec) | | `maxTime` | number | <optional> | 0 | Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. | ##### Returns number - The angle (in radians) that the object should be visually set to in order to match its new velocity. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 1666](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L1666)) ### moveToPointer(displayObject, speed, pointer, maxTime) → {number} Move the given display object towards the pointer at a steady velocity. If no pointer is given it will use Phaser.Input.activePointer. If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. Note: The display object doesn't stop moving once it reaches the destination coordinates. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `displayObject` | any | | | The display object to move. | | `speed` | number | <optional> | 60 | The speed it will move, in pixels per second (default is 60 pixels/sec) | | `pointer` | [Phaser.Pointer](phaser.pointer) | <optional> | | The pointer to move towards. Defaults to Phaser.Input.activePointer. | | `maxTime` | number | <optional> | 0 | Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. | ##### Returns number - The angle (in radians) that the object should be visually set to in order to match its new velocity. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 1701](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L1701)) ### moveToXY(displayObject, x, y, speed, maxTime) → {number} Move the given display object towards the x/y coordinates at a steady velocity. If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. Note: The display object doesn't stop moving once it reaches the destination coordinates. Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `displayObject` | any | | | The display object to move. | | `x` | number | | | The x coordinate to move towards. | | `y` | number | | | The y coordinate to move towards. | | `speed` | number | <optional> | 60 | The speed it will move, in pixels per second (default is 60 pixels/sec) | | `maxTime` | number | <optional> | 0 | Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. | ##### Returns number - The angle (in radians) that the object should be visually set to in order to match its new velocity. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 1736](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L1736)) ### overlap(object1, object2, overlapCallback, processCallback, callbackContext) → {boolean} Checks for overlaps between two game objects. The objects can be Sprites, Groups or Emitters. You can perform Sprite vs. Sprite, Sprite vs. Group and Group vs. Group overlap checks. Unlike collide the objects are NOT automatically separated or have any physics applied, they merely test for overlap results. Both the first and second parameter can be arrays of objects, of differing types. If two arrays are passed, the contents of the first parameter will be tested against all contents of the 2nd parameter. NOTE: This function is not recursive, and will not test against children of objects passed (i.e. Groups within Groups). ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `object1` | [Phaser.Sprite](phaser.sprite) | [Phaser.Group](phaser.group) | Phaser.Particles.Emitter | array | | | The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. | | `object2` | [Phaser.Sprite](phaser.sprite) | [Phaser.Group](phaser.group) | Phaser.Particles.Emitter | array | | | The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. | | `overlapCallback` | function | <optional> | null | An optional callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you specified them, unless you are checking Group vs. Sprite, in which case Sprite will always be the first parameter. | | `processCallback` | function | <optional> | null | A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then `overlapCallback` will only be called if this callback returns `true`. | | `callbackContext` | object | <optional> | | The context in which to run the callbacks. | ##### Returns boolean - True if an overlap occurred otherwise false. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 318](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L318)) ### setBounds(x, y, width, height) Updates the size of this physics world. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Top left most corner of the world. | | `y` | number | Top left most corner of the world. | | `width` | number | New width of the world. Can never be smaller than the Game.width. | | `height` | number | New height of the world. Can never be smaller than the Game.height. | Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 134](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L134)) ### setBoundsToWorld() Updates the size of this physics world to match the size of the game world. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 149](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L149)) ### sort(group, sortDirection) This method will sort a Groups hash array. If the Group has `physicsSortDirection` set it will use the sort direction defined. Otherwise if the sortDirection parameter is undefined, or Group.physicsSortDirection is null, it will use Phaser.Physics.Arcade.sortDirection. By changing Group.physicsSortDirection you can customise each Group to sort in a different order. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `group` | [Phaser.Group](phaser.group) | | The Group to sort. | | `sortDirection` | integer | <optional> | The sort direction used to sort this Group. | Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 518](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L518)) ### sortBottomTop(a, b) → {integer} A Sort function for sorting two bodies based on a BOTTOM to TOP sort direction. This is called automatically by World.sort ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | [Phaser.Sprite](phaser.sprite) | The first Sprite to test. The Sprite must have an Arcade Physics Body. | | `b` | [Phaser.Sprite](phaser.sprite) | The second Sprite to test. The Sprite must have an Arcade Physics Body. | ##### Returns integer - A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 497](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L497)) ### sortLeftRight(a, b) → {integer} A Sort function for sorting two bodies based on a LEFT to RIGHT sort direction. This is called automatically by World.sort ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | [Phaser.Sprite](phaser.sprite) | The first Sprite to test. The Sprite must have an Arcade Physics Body. | | `b` | [Phaser.Sprite](phaser.sprite) | The second Sprite to test. The Sprite must have an Arcade Physics Body. | ##### Returns integer - A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 434](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L434)) ### sortRightLeft(a, b) → {integer} A Sort function for sorting two bodies based on a RIGHT to LEFT sort direction. This is called automatically by World.sort ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | [Phaser.Sprite](phaser.sprite) | The first Sprite to test. The Sprite must have an Arcade Physics Body. | | `b` | [Phaser.Sprite](phaser.sprite) | The second Sprite to test. The Sprite must have an Arcade Physics Body. | ##### Returns integer - A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 455](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L455)) ### sortTopBottom(a, b) → {integer} A Sort function for sorting two bodies based on a TOP to BOTTOM sort direction. This is called automatically by World.sort ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | [Phaser.Sprite](phaser.sprite) | The first Sprite to test. The Sprite must have an Arcade Physics Body. | | `b` | [Phaser.Sprite](phaser.sprite) | The second Sprite to test. The Sprite must have an Arcade Physics Body. | ##### Returns integer - A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 476](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L476)) ### updateMotion(The) Called automatically by a Physics body, it updates all motion related values on the Body unless `World.isPaused` is `true`. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `The` | [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | Body object to be updated. | Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 240](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L240)) ### velocityFromAngle(angle, speed, point) → {[Phaser.Point](phaser.point)} Given the angle (in degrees) and speed calculate the velocity and return it as a Point object, or set it to the given point object. One way to use this is: velocityFromAngle(angle, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `angle` | number | | | The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) | | `speed` | number | <optional> | 60 | The speed it will move, in pixels per second sq. | | `point` | [Phaser.Point](phaser.point) | object | <optional> | | The Point object in which the x and y properties will be set to the calculated velocity. | ##### Returns [Phaser.Point](phaser.point) - * A Point where point.x contains the velocity x value and point.y contains the velocity y value. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 1772](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L1772)) ### velocityFromRotation(rotation, speed, point) → {[Phaser.Point](phaser.point)} Given the rotation (in radians) and speed calculate the velocity and return it as a Point object, or set it to the given point object. One way to use this is: velocityFromRotation(rotation, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `rotation` | number | | | The angle in radians. | | `speed` | number | <optional> | 60 | The speed it will move, in pixels per second sq. | | `point` | [Phaser.Point](phaser.point) | object | <optional> | | The Point object in which the x and y properties will be set to the calculated velocity. | ##### Returns [Phaser.Point](phaser.point) - * A Point where point.x contains the velocity x value and point.y contains the velocity y value. Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 1791](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L1791)) ### worldAngleToPointer(displayObject, pointer) → {number} Find the angle in radians between a display object (like a Sprite) and a Pointer, taking their x/y and center into account relative to the world. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `displayObject` | any | | The DisplayObjerct to test from. | | `pointer` | [Phaser.Pointer](phaser.pointer) | <optional> | The Phaser.Pointer to test to. If none is given then Input.activePointer is used. | ##### Returns number - The angle in radians between displayObject.world.x/y to Pointer.worldX / worldY Source code: [physics/arcade/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js) ([Line 2099](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/World.js#L2099))
programming_docs
phaser Class: Phaser.Filter Class: Phaser.Filter ==================== Constructor ----------- ### new Filter(game, uniforms, fragmentSrc) This is a base Filter class to use for any Phaser filter development. The vast majority of filters (including all of those that ship with Phaser) use fragment shaders, and therefore only work in WebGL and are not supported by Canvas at all. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | | `uniforms` | object | Uniform mappings object | | `fragmentSrc` | Array | string | The fragment shader code. Either an array, one element per line of code, or a string. | Source code: [core/Filter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js) ([Line 19](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js#L19)) Public Properties ----------------- ### dirty : boolean Internal PIXI var. Default Value * true Source code: [core/Filter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js#L50)) ### fragmentSrc :array | string The fragment shader code. ##### Type * array | string Source code: [core/Filter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js#L98)) ### game : [Phaser.Game](phaser.game) A reference to the currently running game. Source code: [core/Filter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js#L24)) ### height : number The height (resolution uniform) Source code: [core/Filter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js) ([Line 233](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js#L233)) ### padding : number Internal PIXI var. Source code: [core/Filter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js) ([Line 56](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js#L56)) ### prevPoint : [Phaser.Point](phaser.point) The previous position of the pointer (we don't update the uniform if the same) Source code: [core/Filter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js) ([Line 61](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js#L61)) ### type : number The const type of this object, either Phaser.WEBGL\_FILTER or Phaser.CANVAS\_FILTER. Source code: [core/Filter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js#L30)) ### uniforms : Object Default uniform mappings. Compatible with ShaderToy and GLSLSandbox. Source code: [core/Filter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js) ([Line 72](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js#L72)) ### width : number The width (resolution uniform) Source code: [core/Filter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js) ([Line 217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js#L217)) Public Methods -------------- ### addToWorld(x, y, width, height, anchorX, anchorY) → {[Phaser.Image](phaser.image)} Creates a new Phaser.Image object using a blank texture and assigns this Filter to it. The image is then added to the world. If you don't provide width and height values then Filter.width and Filter.height are used. If you do provide width and height values then this filter will be resized to match those values. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | <optional> | 0 | The x coordinate to place the Image at. | | `y` | number | <optional> | 0 | The y coordinate to place the Image at. | | `width` | number | <optional> | | The width of the Image. If not specified (or null) it will use Filter.width. If specified Filter.width will be set to this value. | | `height` | number | <optional> | | The height of the Image. If not specified (or null) it will use Filter.height. If specified Filter.height will be set to this value. | | `anchorX` | number | <optional> | 0 | Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. | | `anchorY` | number | <optional> | 0 | Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. | ##### Returns [Phaser.Image](phaser.image) - The newly added Image object. Source code: [core/Filter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js) ([Line 149](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js#L149)) ### destroy() Clear down this Filter and null out references Source code: [core/Filter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js) ([Line 203](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js#L203)) ### init() Should be over-ridden. Source code: [core/Filter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js) ([Line 104](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js#L104)) ### setResolution(width, height) Set the resolution uniforms on the filter. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `width` | number | The width of the display. | | `height` | number | The height of the display. | Source code: [core/Filter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js#L112)) ### update(pointer) Updates the filter. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `pointer` | [Phaser.Pointer](phaser.pointer) | <optional> | A Pointer object to use for the filter. The coordinates are mapped to the mouse uniform. | Source code: [core/Filter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js) ([Line 125](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Filter.js#L125)) phaser Phaser Phaser ====== Phaser 2.6.2 ------------ **"Via":** If a class has an entry in the *via* column it means you can quickly access it through a local reference. I.e. you can control the camera via `this.camera` from any state, or `game.camera` if game has been globally defined. ### Game States | Class | Via | Description | | --- | --- | --- | | [StateManager](phaser.statemanager) | `state` | Creates, manages and swaps your Game States. | | [State](phaser.state) | | A base Game State object you can extend. | ### Loader | Class | Via | Description | | --- | --- | --- | | [Cache](phaser.cache) | `cache` | The Cache is where all loaded assets are stored and retrieved from. | | [Loader](phaser.loader) | `load` | Loads all external asset types (images, audio, json, xml, txt) and adds them to the Cache. Automatically invoked by a States `preload` method. | | [LoaderParser](phaser.loaderparser) | | A Static Class used by the Loader to handle parsing of complex asset types. | ### Game Scaling | Class | Via | Description | | --- | --- | --- | | [ScaleManager](phaser.scalemanager) | `scale` | Manages the sizing and scaling of your game across devices. | | [FlexGrid](phaser.flexgrid) | `scale.grid` | A responsive layout grid (still in testing) | | [FlexLayer](phaser.flexlayer) | | A responsive grid layer (still in testing) | ### Signals | Class | Description | | --- | --- | | [Signal](phaser.signal) | Signals are Phasers internal Event system. | | [SignalBinding](phaser.signalbinding) | Manages which callbacks are bound to a Signal. | ### Plugins | Class | Via | Description | | --- | --- | --- | | [PluginManager](phaser.pluginmanager) | `plugins` | Installs, updates and destroys Plugins. | | [Plugin](phaser.plugin) | | A base Plugin object you can extend. | Game Objects ------------ | Class | Via | Description | | --- | --- | --- | | [GameObjectFactory](phaser.gameobjectfactory) | `add` | A helper class that can create any of the Phaser Game Objects and adds them to the Game World. | | [GameObjectCreator](phaser.gameobjectcreator) | `make` | A helper class that can creates and returns any Phaser Game Object. | | [Group](phaser.group) | | Groups can contain multiple Game Objects and have the ability to search, sort, call, update and filter them. | | [InputHandler](phaser.inputhandler) | `*object*.input` | If a Game Object is enabled for input this class controls all input related events, including clicks and drag. | | [Events](phaser.events) | `*object*.events` | All of the Game Object level events. | | [Create](phaser.create) | `create` | Dynamic Sprite and Texture generation methods. | ### Display | Class | Description | | --- | --- | | [Sprite](phaser.sprite) | A Game Object with a texture, capable of running animation, input events and physics. | | [Image](phaser.image) | A lighter Game Object with a texture and input, but no physics or animation handlers. | | [TileSprite](phaser.tilesprite) | A Game Object with a repeating texture that can be scrolled and scaled. | | [Button](phaser.button) | An Image Game Object with helper methods and events to turn it into a UI Button. | | [SpriteBatch](phaser.spritebatch) | A custom Sprite Batch. Can render multiple Sprites significantly faster if they share the same texture. | | [Rope](phaser.rope) | A jointed Game Object with a strip-based texture. | ### Graphics | Class | Description | | --- | --- | | [Graphics](phaser.graphics) | Allows you to draw primitive shapes (lines, rects, circles), setting color, stroke and fills. | | [BitmapData](phaser.bitmapdata) | Provides a powerful interface to a blank Canvas object. Can be used as a Sprite texture. | | [RenderTexture](phaser.rendertexture) | A special kind of texture you can draw Sprites to extremely quickly. | ### Text | Class | Description | | --- | --- | | [Text](phaser.text) | Displays text using system fonts or Web Fonts, with optional fills, shadows and strokes. | | [BitmapText](phaser.bitmaptext) | A texture based text object that uses a Bitmap Font file. | | [RetroFont](phaser.retrofont) | Similar to a BitmapText object but uses a classic sprite sheet. Each character is a fixed-width. | ### Animation | Class | Via | Description | | --- | --- | --- | | [AnimationManager](phaser.animationmanager) | `*sprite*.animations` | Adds, plays and updates animations on Sprite Game Objects. | | [Animation](phaser.animation) | | The base Animation object that the Animation Manager creates. | | [AnimationParser](phaser.animationparser) | | Used internally by the Phaser Loader to parse animation data from external files. | | [FrameData](phaser.framedata) | | A collection of Frame objects that comprise an animation. | | [Frame](phaser.frame) | | A single Frame of an Animation. Stored inside of a FrameData object. | Geometry -------- | Class | Description | | --- | --- | | [Circle](phaser.circle) | A Circle object consisting of a position and diameter. | | [Ellipse](phaser.ellipse) | An Ellipse object consisting of a position, width and height. | | [Line](phaser.line) | A Line object consisting of two points at the start and end of the Line. | | [Point](phaser.point) | A Point object consisting of an x and y position. | | [Polygon](phaser.polygon) | A Polygon object consisting of a series of Points. | | [Rectangle](phaser.rectangle) | A Rectangle object consisting of an x, y, width and height. | | [RoundedRectangle](phaser.roundedrectangle) | A Rectangle object consisting of an x, y, width, height and corner radius. | Time ---- | Class | Via | Description | | --- | --- | --- | | [Time](phaser.time) | `time` | The core internal clock on which all Phaser time related operations rely. | | [Timer](phaser.timer) | `time.create` | A custom Timer that contains one or more TimerEvents. Can be used either once or be set to repeat. | | [TimerEvent](phaser.timerevent) | `time.add` | A single time related event object. Belongs to a Phaser.Timer. | Tilemaps -------- | Class | Description | | --- | --- | | [Tilemap](phaser.tilemap) | A Tilemap consists of one or more TilemapLayers and associated tile data. Contains methods for tile data manipulation and TilemapLayer generation. | | [TilemapLayer](phaser.tilemaplayer) | A single layer within a Tilemap. Extends from Phaser.Sprite and is responsible for rendering itself. | | [Tileset](phaser.tileset) | An object containing a texture and data used for rendering tiles by a TilemapLayer. | | [Tile](phaser.tile) | A single Tile object with related properties. One of these exists for every tile in a map. | | [TilemapParser](phaser.tilemapparser) | A Static class used to parse externally loaded map data. Typically called directly by Phaser.Loader. | Math ---- | Class | Via | Description | | --- | --- | --- | | [Math](phaser.math) | `math` | Contains lots of math related helper methods including fuzzy logic and interpolation. | | [QuadTree](phaser.quadtree) | | A stand-alone QuadTree implementation. Used by Arcade Physics but can also be used directly. | | [RandomDataGenerator](phaser.randomdatagenerator) | `rnd` | A seedable repeatable random data generator. | Network ------- | Class | Via | Description | | --- | --- | --- | | [Net](phaser.net) | `net` | Browser URL and query string related methods. | Particles --------- | Class | Via | Description | | --- | --- | --- | | [Particles](phaser.particles) | `particles` | The Phaser Particle Manager. Called during the game loop and updates any associated Particle Emitters. | | [Emitter](phaser.particles.arcade.emitter) | | An Arcade Physics based Particle Emitter. Created via `add.emitter` in the GameObjectFactory. | | [Particle](phaser.particle) | | A single Particle object as emitted by the Emitter. Extends Phaser.Sprite. | Physics ------- | Class | Via | Description | | --- | --- | --- | | [Physics](phaser.physics) | `physics` | The core Physics Manager. Provides access to all of the physics sub-systems. | ### Arcade Physics | Class | Via | Description | | --- | --- | --- | | [Arcade](phaser.physics.arcade) | `physics.arcade` | The Arcade Physics handler. Contains collision, overlap and movement related methods. | | [Body](phaser.physics.arcade.body) | `*sprite*.body` | An Arcade Physics Body. Contains velocity, acceleration, drag and other related properties. | | [Weapon](phaser.weapon) | `game.add.weapon` | An Arcade Physics powered Weapon plugin, for easy bullet pool management. | ### Ninja Physics Ninja Physics is not bundled in Phaser by default. Please see the README custom build details section. | Class | Via | Description | | --- | --- | --- | | [Ninja](phaser.physics.ninja) | `physics.ninja` | The Ninja Physics handler. Contains collision, overlap and movement related methods. | | [Body](phaser.physics.ninja.body) | `*sprite*.body` | A Ninja Physics Body. Contains velocity, acceleration, drag and other related properties. | | [AABB](phaser.physics.ninja.aabb) | | An AABB Ninja Physics Body type. | | [Circle](phaser.physics.ninja.circle) | | A Circle Ninja Physics Body type. | | [Tile](phaser.physics.ninja.tile) | | A Tile Ninja Physics Body type. | ### P2 Physics | Class | Via | Description | | --- | --- | --- | | [P2](phaser.physics.p2) | `phyiscs.p2` | The P2 Physics World. Contains collision, overlap and movement related methods. | | [Body](phaser.physics.p2.body) | `*sprite*.body` | A P2 Physics Body. Contains velocity, acceleration, drag and other related properties. | | [BodyDebug](phaser.physics.p2.bodydebug) | | A Debug specific version of a P2 Body object. Renders out its shape for visual debugging. | | [Material](phaser.physics.p2.material) | | A P2 Material used for world responses, such as friction and restitution. | | [ContactMaterial](phaser.physics.p2.contactmaterial) | | A P2 Contact Material used for contact responses. | | [CollisionGroup](phaser.physics.p2.collisiongroup) | | A P2 Collision Group. | | [FixtureList](phaser.physics.p2.fixturelist) | | The P2 Fixture List handler. | | **Constraints:** | | [Distance Constraint](phaser.physics.p2.distanceconstraint), [GearConstraint](phaser.physics.p2.gearconstraint), [LockConstraint](phaser.physics.p2.lockconstraint), [PrismaticConstraint](phaser.physics.p2.prismaticconstraint), [RevoluteConstraint](phaser.physics.p2.revoluteconstraint) | | [PointProxy](phaser.physics.p2.pointproxy) | | Responsible for proxing Phaser Game World to P2 Physics values. | | [InversePointProxy](phaser.physics.p2.inversepointproxy) | | Responsible for proxing Phaser Game World to inversed P2 Physics values. | | [Spring](phaser.physics.p2.spring) | | A P2 Spring object. | | [RotationalSpring](phaser.physics.p2.rotationalspring) | | A P2 Rotational Spring object. | Input ----- | Class | Via | Description | | --- | --- | --- | | [Input](phaser.input) | `input` | The Input Manager. Responsible for handling all Input sub-systems. Also looks after Input enabled Game Objects. | | [Pointer](phaser.pointer) | `input.pointer` | Pointers encapsulate all mouse or touch related input, regardless of how it was generated. On multi-touch systems more than one Pointer can be active at any one time. In Input related events a reference to the corresponding Pointer is passed. | | [DeviceButton](phaser.devicebutton) | `pointer.leftButton` | Represents a button on a mouse or pen / stylus. | | [Keyboard](phaser.keyboard) | `input.keyboard` | The Keyboard input handler. Listens for device related events. Can also create Key objects. | | [Key](phaser.key) | | A Key object is responsible for listening to a specific Key. Created by the Keyboard class. | | [KeyCode](phaser.keycode) | | The KeyCode consts are used when creating new Key objects. | | [Mouse](phaser.mouse) | `input.mouse` | A Mouse event handler. Listens for device related events and passes them on to the active Pointer. | | [MSPointer](phaser.mspointer) | `input.mspointer` | An MSPointer event handler. Listens for device related events and passes them on to the active Pointer. | | [Touch](phaser.touch) | `input.touch` | A Touch event handler. Listens for device related events and passes them on to the active Pointer. | ### Gamepads | Class | Via | Description | | --- | --- | --- | | [Gamepad](phaser.gamepad) | `input.gamepad` | The Gamepad Manager looks after all connected Gamepads to the device. Creates SinglePad instances. | | [SinglePad](phaser.singlepad) | `input.gamepad.pad<1,4>` | Represents a single connected gamepad. | | [DeviceButton](phaser.devicebutton) | | Represents a button on a SinglePad instance. | Tweens ------ | Class | Via | Description | | --- | --- | --- | | [TweenManager](phaser.tweenmanager) | `tweens` | The Tween Manager creates, updates and destroys all active tweens. | | [Tween](phaser.tween) | | A Tween object. Created via `game.add.tween`. Consists of TweenData objects that represent the tween and any child tweens. | | [TweenData](phaser.tweendata) | | A TweenData object contains all the information related to a tween. Created by and belongs to a Phaser.Tween object. | | [Easing](phaser.easing) | | A static class containing all of the easing functions available to Tweens. | Sound ----- | Class | Via | Description | | --- | --- | --- | | [SoundManager](phaser.soundmanager) | `sound` | The Sound Manager controls all Sound objects and can play, loop, fade and stop Sounds. | | [Sound](phaser.sound) | | A Sound object. Can be played, paused and stopped directly, and have its volume adjusted. | | [AudioSprite](phaser.audiosprite) | | An Audio Sprite is a Sound object with related marker data representing sections of the audio. | System ------ | Class | Via | Description | | --- | --- | --- | | [Canvas](phaser.canvas) | | A static class containing Canvas creation and manipulation methods. Such as adding to the dom, setting touch actions, smoothing and image rendering. | | [Device](phaser.device) | `game.device` | The Device class checks system capabilities and settings on boot and stores them for later access. | | [DOM](phaser.dom) | | A static class containing DOM specific methods including offset handling, viewport calibration and bounds checks. | | [RequestAnimationFrame](phaser.requestanimationframe) | `game.raf` | Abstracts away the use of RAF or setTimeOut for the core game update loop. | Utils ----- | Class | Via | Description | | --- | --- | --- | | [ArraySet](phaser.arrayset) | | ArraySet is a Set data structure (items must be unique within the set) that also maintains order. | | [ArrayUtils](phaser.arrayutils) | | Array specific methods such as getRandomItem, shuffle, transposeMatrix, rotate and numberArray. | | [Color](phaser.color) | | Phaser.Color is a set of static methods that assist in color manipulation and conversion. | | [Debug](phaser.utils.debug) | `game.debug` | A collection of methods for displaying debug information about game objects. | | [LinkedList](phaser.linkedlist) | | A basic Linked List data structure. | | [Utils](phaser.utils) | | Utility methods for Object and String inspection and modification. Including getProperty, pad, isPlainObject, extend and mixin. |
programming_docs
phaser Class: Phaser.Easing.Sinusoidal Class: Phaser.Easing.Sinusoidal =============================== Constructor ----------- ### new Sinusoidal() Sinusoidal easing. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 239](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L239)) Public Methods -------------- ### In(k) → {number} Sinusoidal ease-in. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 241](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L241)) ### InOut(k) → {number} Sinusoidal ease-in/out. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 271](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L271)) ### Out(k) → {number} Sinusoidal ease-out. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 256](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L256)) phaser Class: PIXI.BaseTexture Class: PIXI.BaseTexture ======================= Constructor ----------- ### new BaseTexture(source, scaleMode) A texture stores the information that represents an image. All textures have a base texture. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `source` | String | Canvas | the source object (image or canvas) | | `scaleMode` | Number | See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values | Source code: [pixi/textures/BaseTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js) ([Line 5](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js#L5)) Public Properties ----------------- ### [readonly] hasLoaded : boolean [read-only] Set to true once the base texture has loaded Source code: [pixi/textures/BaseTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js#L51)) ### [readonly] height : number [read-only] The height of the base texture set when the image has loaded Source code: [pixi/textures/BaseTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js) ([Line 33](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js#L33)) ### mipmap : boolean Set this to true if a mipmap of this texture needs to be generated. This value needs to be set before the texture is used Also the texture must be a power of two size to work Source code: [pixi/textures/BaseTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js#L86)) ### premultipliedAlpha : boolean Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) Default Value * true Source code: [pixi/textures/BaseTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js) ([Line 68](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js#L68)) ### resolution : number The Resolution of the texture. Source code: [pixi/textures/BaseTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js) ([Line 16](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js#L16)) ### scaleMode : number The scale mode to apply when scaling this texture Default Value * PIXI.scaleModes.LINEAR Source code: [pixi/textures/BaseTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js#L42)) ### skipRender : boolean A BaseTexture can be set to skip the rendering phase in the WebGL Sprite Batch. You may want to do this if you have a parent Sprite with no visible texture (i.e. uses the internal `__default` texture) that has children that you do want to render, without causing a batch flush in the process. Source code: [pixi/textures/BaseTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js) ([Line 115](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js#L115)) ### source :Image The image source that is used to create the texture. Source code: [pixi/textures/BaseTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js) ([Line 60](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js#L60)) ### [readonly] width : number [read-only] The width of the base texture set when the image has loaded Source code: [pixi/textures/BaseTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js#L24)) Public Methods -------------- ### <static> fromCanvas(canvas, scaleMode) → {[PIXI.BaseTexture](pixi.basetexture)} Helper function that creates a base texture from the given canvas element. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `canvas` | Canvas | The canvas element source of the texture | | `scaleMode` | Number | See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values | ##### Returns [PIXI.BaseTexture](pixi.basetexture) - Source code: [pixi/textures/BaseTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js) ([Line 224](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js#L224)) ### destroy() Destroys this base texture Source code: [pixi/textures/BaseTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js) ([Line 154](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js#L154)) ### dirty() Sets all glTextures to be dirty. Source code: [pixi/textures/BaseTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js) ([Line 183](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js#L183)) ### forceLoaded(width, height) Forces this BaseTexture to be set as loaded, with the given width and height. Then calls BaseTexture.dirty. Important for when you don't want to modify the source object by forcing in `complete` or dimension properties it may not have. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `width` | Number | * The new width to force the BaseTexture to be. | | `height` | Number | * The new height to force the BaseTexture to be. | Source code: [pixi/textures/BaseTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js) ([Line 137](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js#L137)) ### unloadFromGPU() Removes the base texture from the GPU, useful for managing resources on the GPU. Atexture is still 100% usable and will simply be reuploaded if there is a sprite on screen that is using it. Source code: [pixi/textures/BaseTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js) ([Line 196](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js#L196)) ### updateSourceImage(newSrc) This method is *deprecated* and should not be used. It may be removed in the future. Changes the source image of the texture ##### Parameters | Name | Type | Description | | --- | --- | --- | | `newSrc` | String | the path of the image | Deprecated: * true Source code: [pixi/textures/BaseTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/BaseTexture.js#L171)) phaser Class: Phaser.TweenData Class: Phaser.TweenData ======================= Constructor ----------- ### new TweenData(parent) A Phaser.Tween contains at least one TweenData object. It contains all of the tween data values, such as the starting and ending values, the ease function, interpolation and duration. The Tween acts as a timeline manager for TweenData objects and can contain multiple TweenData objects. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `parent` | [Phaser.Tween](phaser.tween) | The Tween that owns this TweenData object. | Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 16](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L16)) Public Properties ----------------- ### [static] COMPLETE : number Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 179](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L179)) ### [static] LOOPED : number Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 173](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L173)) ### [static] PENDING : number Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 161](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L161)) ### [static] RUNNING : number Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 167](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L167)) ### delay : number The amount to delay by until the Tween starts (in ms). Only applies to the start, use repeatDelay to handle repeats. Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 113](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L113)) ### dt : number Current time value. Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 118](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L118)) ### duration : number The duration of the tween in ms. Default Value * 1000 Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 56](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L56)) ### easingFunction : Function The easing function used for the Tween. Default Value * Phaser.Easing.Default Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 129](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L129)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L26)) ### inReverse : boolean When a Tween is yoyoing this value holds if it's currently playing forwards (false) or in reverse (true). Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 107](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L107)) ### interpolate : boolean True if the Tween will use interpolation (i.e. is an Array to Array tween) Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 90](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L90)) ### interpolationContext : Object The interpolation function context used for the Tween. Default Value * Phaser.Math Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 141](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L141)) ### interpolationFunction : Function The interpolation function used for the Tween. Default Value * Phaser.Math.linearInterpolation Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 135](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L135)) ### isFrom : boolean Is this a from tween or a to tween? Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L153)) ### isRunning : boolean If the tween is running this is set to `true`. Unless Phaser.Tween a TweenData that is waiting for a delay to expire is *not* considered as running. Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 147](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L147)) ### parent : [Phaser.Tween](phaser.tween) The Tween which owns this TweenData. Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 21](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L21)) ### [readonly] percent : number A value between 0 and 1 that represents how far through the duration this tween is. Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 62](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L62)) ### repeatCounter : number If the Tween is set to repeat this contains the current repeat count. Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 73](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L73)) ### repeatDelay : number The amount of time in ms between repeats of this tween. Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L78)) ### [readonly] repeatTotal : number The total number of times this Tween will repeat. Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 84](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L84)) ### startTime : number The time the Tween started or null if it hasn't yet started. Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 123](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L123)) ### [readonly] value : number The current calculated value. Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 68](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L68)) ### yoyo : boolean True if the Tween is set to yoyo, otherwise false. Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 96](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L96)) ### yoyoDelay : number The amount of time in ms between yoyos of this tween. Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 101](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L101)) Public Methods -------------- ### from(properties, duration, ease, delay, repeat, yoyo) → {[Phaser.TweenData](phaser.tweendata)} Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value. For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `properties` | object | | | The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. | | `duration` | number | <optional> | 1000 | Duration of this tween in ms. | | `ease` | function | <optional> | null | Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will. | | `delay` | number | <optional> | 0 | Delay before this tween will start, defaults to 0 (no delay). Value given is in ms. | | `repeat` | number | <optional> | 0 | Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens. | | `yoyo` | boolean | <optional> | false | A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. | ##### Returns [Phaser.TweenData](phaser.tweendata) - This Tween object. Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 211](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L211)) ### generateData(frameRate) → {array} This will generate an array populated with the tweened object values from start to end. It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from. Just one play through of the tween data is returned, including yoyo if set. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `frameRate` | number | <optional> | 60 | The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates. | ##### Returns array - An array of tweened values. Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 411](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L411)) ### start() → {[Phaser.TweenData](phaser.tweendata)} Starts the Tween running. ##### Returns [Phaser.TweenData](phaser.tweendata) - This Tween object. Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 239](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L239)) ### to(properties, duration, ease, delay, repeat, yoyo) → {[Phaser.TweenData](phaser.tweendata)} Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given. For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `properties` | object | | | The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. | | `duration` | number | <optional> | 1000 | Duration of this tween in ms. | | `ease` | function | <optional> | null | Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will. | | `delay` | number | <optional> | 0 | Delay before this tween will start, defaults to 0 (no delay). Value given is in ms. | | `repeat` | number | <optional> | 0 | Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens. | | `yoyo` | boolean | <optional> | false | A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. | ##### Returns [Phaser.TweenData](phaser.tweendata) - This Tween object. Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 183](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L183)) ### <internal> update(time) → {number} Updates this Tween. This is called automatically by Phaser.Tween. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `time` | number | A timestamp passed in by the Tween parent. | ##### Returns number - The current status of this Tween. One of the Phaser.TweenData constants: PENDING, RUNNING, LOOPED or COMPLETE. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [tween/TweenData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js) ([Line 340](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenData.js#L340))
programming_docs
phaser Class: Phaser.ArraySet Class: Phaser.ArraySet ====================== Constructor ----------- ### new ArraySet(list) ArraySet is a Set data structure (items must be unique within the set) that also maintains order. This allows specific items to be easily added or removed from the Set. Item equality (and uniqueness) is determined by the behavior of `Array.indexOf`. This used primarily by the Input subsystem. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `list` | Array.<any> | <optional> | (new array) | The backing array: if specified the items in the list *must* be unique, per `Array.indexOf`, and the ownership of the array *should* be relinquished to the ArraySet. | Source code: [utils/ArraySet.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js) ([Line 19](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js#L19)) Public Properties ----------------- ### first :any Returns the first item and resets the cursor to the start. Source code: [utils/ArraySet.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js) ([Line 231](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js#L231)) ### list : Array.<any> The backing array. ##### Type * Array.<any> Source code: [utils/ArraySet.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js) ([Line 32](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js#L32)) ### next :any Returns the the next item (based on the cursor) and advances the cursor. Source code: [utils/ArraySet.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js) ([Line 256](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js#L256)) ### position : integer Current cursor position as established by `first` and `next`. Source code: [utils/ArraySet.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js#L26)) ### total : integer Number of items in the ArraySet. Same as `list.length`. Source code: [utils/ArraySet.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js) ([Line 217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js#L217)) Public Methods -------------- ### add(item) → {any} Adds a new element to the end of the list. If the item already exists in the list it is not moved. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `item` | any | The element to add to this list. | ##### Returns any - The item that was added. Source code: [utils/ArraySet.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js#L38)) ### callAll(key, parameter) Calls a function on all members of this list, using the member as the context for the callback. If the `key` property is present it must be a function. The function is invoked using the item as the context. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `key` | string | | The name of the property with the function to call. | | `parameter` | \* | <repeatable> | Additional parameters that will be passed to the callback. | Source code: [utils/ArraySet.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js) ([Line 159](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js#L159)) ### exists(item) → {boolean} Checks for the item within this list. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `item` | any | The element to get the list index for. | ##### Returns boolean - True if the item is found in the list, otherwise false. Source code: [utils/ArraySet.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js) ([Line 95](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js#L95)) ### getByKey(property, value) → {any} Gets an item from the set based on the property strictly equaling the value given. Returns null if not found. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to check against the value. | | `value` | any | The value to check if the property strictly equals. | ##### Returns any - The item that was found, or null if nothing matched. Source code: [utils/ArraySet.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js) ([Line 70](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js#L70)) ### getIndex(item) → {integer} Gets the index of the item in the list, or -1 if it isn't in the list. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `item` | any | The element to get the list index for. | ##### Returns integer - The index of the item or -1 if not found. Source code: [utils/ArraySet.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js) ([Line 57](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js#L57)) ### remove(item) → {any} Removes the given element from this list if it exists. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `item` | any | The item to be removed from the list. | ##### Returns any - item - The item that was removed. Source code: [utils/ArraySet.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js) ([Line 119](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js#L119)) ### removeAll(destroy) Removes every member from this ArraySet and optionally destroys it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroy` | boolean | <optional> | false | Call `destroy` on each member as it's removed from this set. | Source code: [utils/ArraySet.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js) ([Line 185](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js#L185)) ### reset() Removes all the items. Source code: [utils/ArraySet.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js) ([Line 108](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js#L108)) ### setAll(key, value) Sets the property `key` to the given value on all members of this list. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | any | The property of the item to set. | | `value` | any | The value to set the property to. | Source code: [utils/ArraySet.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js) ([Line 138](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArraySet.js#L138)) phaser Class: Phaser.Physics.P2.PrismaticConstraint Class: Phaser.Physics.P2.PrismaticConstraint ============================================ Constructor ----------- ### new PrismaticConstraint(world, bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) Connects two bodies at given offset points, letting them rotate relative to each other around this point. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `world` | [Phaser.Physics.P2](phaser.physics.p2) | | | A reference to the P2 World. | | `bodyA` | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | First connected body. | | `bodyB` | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | Second connected body. | | `lockRotation` | boolean | <optional> | true | If set to false, bodyB will be free to rotate around its anchor point. | | `anchorA` | Array | <optional> | | Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. | | `anchorB` | Array | <optional> | | Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. | | `axis` | Array | <optional> | | An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. | | `maxForce` | number | <optional> | | The maximum force that should be applied to constrain the bodies. | Source code: [physics/p2/PrismaticConstraint.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/PrismaticConstraint.js) ([Line 21](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/PrismaticConstraint.js#L21)) Public Properties ----------------- ### game : [Phaser.Game](phaser.game) Local reference to game. Source code: [physics/p2/PrismaticConstraint.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/PrismaticConstraint.js) ([Line 32](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/PrismaticConstraint.js#L32)) ### world : [Phaser.Physics.P2](phaser.physics.p2) Local reference to P2 World. Source code: [physics/p2/PrismaticConstraint.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/PrismaticConstraint.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/PrismaticConstraint.js#L37)) phaser Class: Phaser.Weapon Class: Phaser.Weapon ==================== Constructor ----------- ### new Weapon(game, parent) The Weapon Plugin provides the ability to easily create a bullet pool and manager. Weapons fire Phaser.Bullet objects, which are essentially Sprites with a few extra properties. The Bullets are enabled for Arcade Physics. They do not currently work with P2 Physics. The Bullets are created inside of `Weapon.bullets`, which is a Phaser.Group instance. Anything you can usually do with a Group, such as move it around the display list, iterate it, etc can be done to the bullets Group too. Bullets can have textures and even animations. You can control the speed at which they are fired, the firing rate, the firing angle, and even set things like gravity for them. A small example, assumed to be running from within a Phaser.State create method. `var weapon = this.add.weapon(10, 'bullet');` `weapon.fireFrom.set(300, 300);` `this.input.onDown.add(weapon.fire, this);` ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the current Phaser.Game instance. | | `parent` | [Phaser.PluginManager](phaser.pluginmanager) | The Phaser Plugin Manager which looks after this plugin. | Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 31](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L31)) Public Properties ----------------- ### [static] KILL\_CAMERA\_BOUNDS : integer A `bulletKillType` constant that automatically kills the bullets when they leave the `Camera.bounds` rectangle. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 417](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L417)) ### [static] KILL\_DISTANCE : integer A `bulletKillType` constant that automatically kills the bullets after they exceed the `bulletDistance` from their original firing position. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 403](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L403)) ### [static] KILL\_LIFESPAN : integer A `bulletKillType` constant that automatically kills the bullets when their `bulletLifespan` expires. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 395](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L395)) ### [static] KILL\_NEVER : integer A `bulletKillType` constant that stops the bullets from ever being destroyed automatically. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 388](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L388)) ### [static] KILL\_STATIC\_BOUNDS : integer A `bulletKillType` constant that automatically kills the bullets when they leave the `Weapon.bounds` rectangle. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 431](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L431)) ### [static] KILL\_WEAPON\_BOUNDS : integer A `bulletKillType` constant that automatically kills the bullets when they leave the `Weapon.bounds` rectangle. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 410](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L410)) ### [static] KILL\_WORLD\_BOUNDS : integer A `bulletKillType` constant that automatically kills the bullets when they leave the `World.bounds` rectangle. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 424](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L424)) ### autoExpandBulletsGroup : boolean Should the bullet pool run out of bullets (i.e. they are all in flight) then this boolean controls if the Group will create a brand new bullet object or not. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L46)) ### autofire : boolean Will this weapon auto fire? If set to true then a new bullet will be fired based on the `fireRate` value. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 53](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L53)) ### bounds : [Phaser.Rectangle](phaser.rectangle) This Rectangle defines the bounds that are used when determining if a Bullet should be killed or not. It's used in combination with `Weapon.bulletKillType` when that is set to either `Phaser.Weapon.KILL_WEAPON_BOUNDS` or `Phaser.Weapon.KILL_STATIC_BOUNDS`. If you are not using either of these kill types then the bounds are ignored. If you are tracking a Sprite or Point then the bounds are centered on that object every frame. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 266](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L266)) ### bulletAngleOffset : number An optional angle offset applied to the Bullets when they are launched. This is useful if for example your bullet sprites have been drawn facing up, instead of to the right, and you want to fire them at an angle. In which case you can set the angle offset to be 90 and they'll be properly rotated when fired. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L153)) ### bulletAngleVariance : number This is a variance added to the angle of Bullets when they are fired. If you fire from an angle of 90 and have a `bulletAngleVariance` of 20 then the actual angle of the Bullets will be between 70 and 110 degrees. This is a quick way to add a great 'spread' effect to a Weapon. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 162](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L162)) ### bulletAnimation : string The string based name of the animation that the Bullet will be given on launch. This is set via `Weapon.addBulletAnimation`. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L112)) ### bulletClass : Object The Class of the bullets that are launched by this Weapon. Defaults `Phaser.Bullet`, but can be overridden before calling `createBullets` and set to your own class type. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 1111](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L1111)) ### bulletCollideWorldBounds : boolean Should bullets collide with the World bounds or not? Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 1199](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L1199)) ### bulletFrame : string | integer The Texture Frame that the Bullets use when rendering. Changing this has no effect on bullets in-flight, only on newly spawned bullets. ##### Type * string | integer Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 221](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L221)) ### bulletFrameCycle : boolean If you've added a set of frames via `Weapon.setBulletFrames` then you can optionally chose for each Bullet fired to use the next frame in the set. The frame index is then advanced one frame until it reaches the end of the set, then it starts from the start again. Cycling frames like this allows you to create varied bullet effects via sprite sheets. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 129](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L129)) ### bulletFrameRandom : boolean If you've added a set of frames via `Weapon.setBulletFrames` then you can optionally chose for each Bullet fired to pick a random frame from the set. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 119](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L119)) ### <internal> bulletFrames : Array This array stores the frames added via `Weapon.setBulletFrames`. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 282](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L282)) ### bulletGravity : [Phaser.Point](phaser.point) This is the amount of gravity added to the Bullets physics body when fired. Gravity is expressed in pixels / second / second. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 199](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L199)) ### bulletInheritSpriteSpeed : boolean When a Bullet is fired it can optionally inherit the velocity of the `trackedSprite` if set. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 105](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L105)) ### bulletKey : string The Texture Key that the Bullets use when rendering. Changing this has no effect on bullets in-flight, only on newly spawned bullets. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 214](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L214)) ### bulletKillDistance : number If you've set `bulletKillType` to `Phaser.Weapon.KILL_DISTANCE` this controls the distance the Bullet can travel before it is automatically killed. The distance is given in pixels. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 192](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L192)) ### bulletKillType : integer This controls how the bullets will be killed. The default is `Phaser.Weapon.KILL_WORLD_BOUNDS`. There are 7 different "kill types" available: * `Phaser.Weapon.KILL_NEVER` The bullets are never destroyed by the Weapon. It's up to you to destroy them via your own code. * `Phaser.Weapon.KILL_LIFESPAN` The bullets are automatically killed when their `bulletLifespan` amount expires. * `Phaser.Weapon.KILL_DISTANCE` The bullets are automatically killed when they exceed `bulletDistance` pixels away from their original launch position. * `Phaser.Weapon.KILL_WEAPON_BOUNDS` The bullets are automatically killed when they no longer intersect with the `Weapon.bounds` rectangle. * `Phaser.Weapon.KILL_CAMERA_BOUNDS` The bullets are automatically killed when they no longer intersect with the `Camera.bounds` rectangle. * `Phaser.Weapon.KILL_WORLD_BOUNDS` The bullets are automatically killed when they no longer intersect with the `World.bounds` rectangle. * `Phaser.Weapon.KILL_STATIC_BOUNDS` The bullets are automatically killed when they no longer intersect with the `Weapon.bounds` rectangle. The difference between static bounds and weapon bounds, is that a static bounds will never be adjusted to match the position of a tracked sprite or pointer. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 1136](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L1136)) ### bulletLifespan : number If you've set `bulletKillType` to `Phaser.Weapon.KILL_LIFESPAN` this controls the amount of lifespan the Bullets have set on launch. The value is given in milliseconds. When a Bullet hits its lifespan limit it will be automatically killed. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 185](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L185)) ### bulletRotateToVelocity : boolean Bullets can optionally adjust their rotation in-flight to match their velocity. This can create the effect of a bullet 'pointing' to the path it is following, for example an arrow being fired from a bow, and works especially well when added to `bulletGravity`. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 207](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L207)) ### bullets : [Phaser.Group](phaser.group) This is the Phaser.Group that contains all of the bullets managed by this plugin. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 39](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L39)) ### bulletSpeed : number The speed at which the bullets are fired. This value is given in pixels per second, and is used to set the starting velocity of the bullets. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 169](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L169)) ### bulletSpeedVariance : number This is a variance added to the speed of Bullets when they are fired. If bullets have a `bulletSpeed` value of 200, and a `bulletSpeedVariance` of 50 then the actual speed of the Bullets will be between 150 and 250 pixels per second. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 177](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L177)) ### bulletWorldWrap : boolean Should the Bullets wrap around the world bounds? This automatically calls `World.wrap` on the Bullet each frame. See the docs for that method for details. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 136](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L136)) ### bulletWorldWrapPadding : integer If `bulletWorldWrap` is true then you can provide an optional padding value with this property. It's added to the calculations determining when the Bullet should wrap around the world or not. The value is given in pixels. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 144](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L144)) ### fireAngle : integer The angle at which the bullets are fired. This can be a const such as Phaser.ANGLE\_UP or it can be any number from 0 to 360 inclusive, where 0 degrees is to the right. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 99](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L99)) ### fireFrom : [Phaser.Rectangle](phaser.rectangle) This is a Rectangle from within which the bullets are fired. By default it's a 1x1 rectangle, the equivalent of a Point. But you can change the width and height, and if larger than 1x1 it'll pick a random point within the rectangle to launch the bullet from. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 92](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L92)) ### fireLimit : number The maximum number of shots that this Weapon is allowed to fire before it stops. When the limit is his the `Weapon.onFireLimit` Signal is dispatched. You can reset the shot counter via `Weapon.resetShots`. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 69](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L69)) ### fireRate : number The rate at which this Weapon can fire. The value is given in milliseconds. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 75](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L75)) ### fireRateVariance : number This is a modifier that is added to the `fireRate` each update to add variety to the firing rate of the Weapon. The value is given in milliseconds. If you've a `fireRate` of 200 and a `fireRateVariance` of 50 then the actual firing rate of the Weapon will be between 150 and 250. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 84](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L84)) ### onFire : [Phaser.Signal](phaser.signal) The onFire Signal is dispatched each time `Weapon.fire` is called, and a Bullet is *successfully* launched. The callback is set two arguments: a reference to the bullet sprite itself, and a reference to the Weapon that fired the bullet. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 306](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L306)) ### onFireLimit : [Phaser.Signal](phaser.signal) The onFireLimit Signal is dispatched if `Weapon.fireLimit` is > 0, and a bullet launch takes the number of shots fired to equal the fire limit. The callback is sent two arguments: A reference to the Weapon that hit the limit, and the value of `Weapon.fireLimit`. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 325](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L325)) ### onKill : [Phaser.Signal](phaser.signal) The onKill Signal is dispatched each time a Bullet that is in-flight is killed. This can be the result of leaving the Weapon bounds, an expiring lifespan, or exceeding a specified distance. The callback is sent one argument: A reference to the bullet sprite itself. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 315](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L315)) ### shots : number The total number of bullets this Weapon has fired so far. You can limit the number of shots allowed (via `fireLimit`), and reset this total via `Weapon.resetShots`. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 61](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L61)) ### trackedPointer : [Phaser.Pointer](phaser.pointer) The Pointer currently being tracked by the Weapon, if any. This is set via the `Weapon.trackPointer` method. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 341](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L341)) ### trackedSprite : [Phaser.Sprite](phaser.sprite) | Object The Sprite currently being tracked by the Weapon, if any. This is set via the `Weapon.trackSprite` method. ##### Type * [Phaser.Sprite](phaser.sprite) | Object Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 333](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L333)) ### trackOffset : [Phaser.Point](phaser.point) The Track Offset is a Point object that allows you to specify a pixel offset that bullets use when launching from a tracked Sprite or Pointer. For example if you've got a bullet that is 2x2 pixels in size, but you're tracking a Sprite that is 32x32, then you can set `trackOffset.x = 16` to have the bullet launched from the center of the Sprite. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 360](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L360)) ### trackRotation : boolean If the Weapon is tracking a Sprite, should it also track the Sprites rotation? This is useful for a game such as Asteroids, where you want the weapon to fire based on the sprites rotation. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 350](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L350)) ### x : number The x coordinate from which bullets are fired. This is the same as `Weapon.fireFrom.x`, and can be overridden by the `Weapon.fire` arguments. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 1224](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L1224)) ### y : number The y coordinate from which bullets are fired. This is the same as `Weapon.fireFrom.y`, and can be overridden by the `Weapon.fire` arguments. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 1246](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L1246)) Public Methods -------------- ### addBulletAnimation(name, frames, frameRate, loop, useNumericIndex) → {[Phaser.Weapon](phaser.weapon)} Adds a new animation under the given key. Optionally set the frames, frame rate and loop. The arguments are all the same as for `Animation.add`, and work in the same way. `Weapon.bulletAnimation` will be set to this animation after it's created. From that point on, all bullets fired will play using this animation. You can swap between animations by calling this method several times, and then just changing the `Weapon.bulletAnimation` property to the name of the animation you wish to play for the next launched bullet. If you wish to stop using animations at all, set `Weapon.bulletAnimation` to '' (an empty string). ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `name` | string | | | The unique (within the Weapon instance) name for the animation, i.e. "fire", "blast". | | `frames` | Array | <optional> | null | An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used. | | `frameRate` | number | <optional> | 60 | The speed at which the animation should play. The speed is given in frames per second. | | `loop` | boolean | <optional> | false | Whether or not the animation is looped or just plays once. | | `useNumericIndex` | boolean | <optional> | true | Are the given frames using numeric indexes (default) or strings? | ##### Returns [Phaser.Weapon](phaser.weapon) - The Weapon Plugin. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 1048](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L1048)) ### createBullets(quantity, key, frame, group) → {[Phaser.Weapon](phaser.weapon)} This method performs two actions: First it will check to see if the `Weapon.bullets` Group exists or not, and if not it creates it, adding it the `group` given as the 4th argument. Then it will seed the bullet pool with the `quantity` number of Bullets, using the texture key and frame provided (if any). If for example you set the quantity to be 10, then this Weapon will only ever be able to have 10 bullets in-flight simultaneously. If you try to fire an 11th bullet then nothing will happen until one, or more, of the in-flight bullets have been killed, freeing them up for use by the Weapon again. If you do not wish to have a limit set, then pass in -1 as the quantity. In this instance the Weapon will keep increasing the size of the bullet pool as needed. It will never reduce the size of the pool however, so be careful it doesn't grow too large. You can either set the texture key and frame here, or via the `Weapon.bulletKey` and `Weapon.bulletFrame` properties. You can also animate bullets, or set them to use random frames. All Bullets belonging to a single Weapon instance must share the same texture key however. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `quantity` | integer | <optional> | 1 | The quantity of bullets to seed the Weapon with. If -1 it will set the pool to automatically expand. | | `key` | string | <optional> | | The Game.cache key of the image that this Sprite will use. | | `frame` | integer | string | <optional> | | If the Sprite image contains multiple frames you can specify which one to use here. | | `group` | [Phaser.Group](phaser.group) | <optional> | | Optional Group to add the object to. If not specified it will be added to the World group. | ##### Returns [Phaser.Weapon](phaser.weapon) - This Weapon instance. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 433](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L433)) ### debug(x, y, debugBodies) Uses `Game.Debug` to draw some useful information about this Weapon, including the number of bullets both in-flight, and available. And optionally the physics debug bodies of the bullets. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | integer | <optional> | 16 | The coordinate, in screen space, at which to draw the Weapon debug data. | | `y` | integer | <optional> | 32 | The coordinate, in screen space, at which to draw the Weapon debug data. | | `debugBodies` | boolean | <optional> | false | Optionally draw the physics body of every bullet in-flight. | Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 1086](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L1086)) ### destroy() Destroys this Weapon. It removes itself from the PluginManager, destroys the bullets Group, and nulls internal references. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 579](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L579)) ### fire(from, x, y) → {[Phaser.Bullet](phaser.bullet)} Attempts to fire a single Bullet. If there are no more bullets available in the pool, and the pool cannot be extended, then this method returns `false`. It will also return false if not enough time has expired since the last time the Weapon was fired, as defined in the `Weapon.fireRate` property. Otherwise the first available bullet is selected and launched. The arguments are all optional, but allow you to control both where the bullet is launched from, and aimed at. If you don't provide any of the arguments then it uses those set via properties such as `Weapon.trackedSprite`, `Weapon.bulletAngle` and so on. When the bullet is launched it has its texture and frame updated, as required. The velocity of the bullet is calculated based on Weapon properties like `bulletSpeed`. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `from` | [Phaser.Sprite](phaser.sprite) | [Phaser.Point](phaser.point) | Object | <optional> | Optionally fires the bullet **from** the `x` and `y` properties of this object. If set this overrides `Weapon.trackedSprite` or `trackedPointer`. Pass `null` to ignore it. | | `x` | number | <optional> | The x coordinate, in world space, to fire the bullet **towards**. If left as `undefined` the bullet direction is based on its angle. | | `y` | number | <optional> | The y coordinate, in world space, to fire the bullet **towards**. If left as `undefined` the bullet direction is based on its angle. | ##### Returns [Phaser.Bullet](phaser.bullet) - The fired bullet if successful, null otherwise. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 691](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L691)) ### fireAtPointer(pointer) → {[Phaser.Bullet](phaser.bullet)} Fires a bullet **at** the given Pointer. The bullet will be launched from the `Weapon.fireFrom` position, or from a Tracked Sprite or Pointer, if you have one set. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `pointer` | [Phaser.Pointer](phaser.pointer) | <optional> | The Pointer to fire the bullet towards. | ##### Returns [Phaser.Bullet](phaser.bullet) - The fired bullet if successful, null otherwise. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 928](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L928)) ### fireAtSprite(sprite) → {[Phaser.Bullet](phaser.bullet)} Fires a bullet **at** the given Sprite. The bullet will be launched from the `Weapon.fireFrom` position, or from a Tracked Sprite or Pointer, if you have one set. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `sprite` | [Phaser.Sprite](phaser.sprite) | <optional> | The Sprite to fire the bullet towards. | ##### Returns [Phaser.Bullet](phaser.bullet) - The fired bullet if successful, null otherwise. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 944](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L944)) ### fireAtXY(x, y) → {[Phaser.Bullet](phaser.bullet)} Fires a bullet **at** the given coordinates. The bullet will be launched from the `Weapon.fireFrom` position, or from a Tracked Sprite or Pointer, if you have one set. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `x` | number | <optional> | The x coordinate, in world space, to fire the bullet towards. | | `y` | number | <optional> | The y coordinate, in world space, to fire the bullet towards. | ##### Returns [Phaser.Bullet](phaser.bullet) - The fired bullet if successful, null otherwise. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 958](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L958)) ### forEach(callback, callbackContext, args) → {[Phaser.Weapon](phaser.weapon)} Call a function on each in-flight bullet in this Weapon. See [forEachExists](phaser.group#forEachExists) for more details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | ##### Returns [Phaser.Weapon](phaser.weapon) - This Weapon instance. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 490](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L490)) ### killAll() → {[Phaser.Weapon](phaser.weapon)} Calls `Bullet.kill` on every in-flight bullet in this Weapon. Also re-enables their physics bodies, should they have been disabled via `pauseAll`. ##### Returns [Phaser.Weapon](phaser.weapon) - This Weapon instance. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 541](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L541)) ### pauseAll() → {[Phaser.Weapon](phaser.weapon)} Sets `Body.enable` to `false` on each bullet in this Weapon. This has the effect of stopping them in-flight should they be moving. It also stops them being able to be checked for collision. ##### Returns [Phaser.Weapon](phaser.weapon) - This Weapon instance. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 509](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L509)) ### resetShots(newLimit) → {[Phaser.Weapon](phaser.weapon)} Resets the `Weapon.shots` counter back to zero. This is used when you've set `Weapon.fireLimit`, and have hit (or just wish to reset) your limit. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `newLimit` | integer | <optional> | Optionally set a new `Weapon.fireLimit`. | ##### Returns [Phaser.Weapon](phaser.weapon) - This Weapon instance. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 558](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L558)) ### resumeAll() → {[Phaser.Weapon](phaser.weapon)} Sets `Body.enable` to `true` on each bullet in this Weapon. This has the effect of resuming their motion should they be in-flight. It also enables them for collision checks again. ##### Returns [Phaser.Weapon](phaser.weapon) - This Weapon instance. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 525](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L525)) ### setBulletBodyOffset(width, height, offsetX, offsetY) → {[Phaser.Weapon](phaser.weapon)} You can modify the size of the physics Body the Bullets use to be any dimension you need. This allows you to make it smaller, or larger, than the parent Sprite. You can also control the x and y offset of the Body. This is the position of the Body relative to the top-left of the Sprite *texture*. For example: If you have a Sprite with a texture that is 80x100 in size, and you want the physics body to be 32x32 pixels in the middle of the texture, you would do: `setSize(32, 32, 24, 34)` Where the first two parameters is the new Body size (32x32 pixels). 24 is the horizontal offset of the Body from the top-left of the Sprites texture, and 34 is the vertical offset. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `width` | number | | The width of the Body. | | `height` | number | | The height of the Body. | | `offsetX` | number | <optional> | The X offset of the Body from the top-left of the Sprites texture. | | `offsetY` | number | <optional> | The Y offset of the Body from the top-left of the Sprites texture. | ##### Returns [Phaser.Weapon](phaser.weapon) - The Weapon Plugin. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 973](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L973)) ### setBulletFrames(min, max, cycle, random) → {[Phaser.Weapon](phaser.weapon)} Sets the texture frames that the bullets can use when being launched. This is intended for use when you've got numeric based frames, such as those loaded via a Sprite Sheet. It works by calling `Phaser.ArrayUtils.numberArray` internally, using the min and max values provided. Then it sets the frame index to be zero. You can optionally set the cycle and random booleans, to allow bullets to cycle through the frames when they're fired, or pick one at random. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `min` | integer | | | The minimum value the frame can be. Usually zero. | | `max` | integer | | | The maximum value the frame can be. | | `cycle` | boolean | <optional> | true | Should the bullet frames cycle as they are fired? | | `random` | boolean | <optional> | false | Should the bullet frames be picked at random as they are fired? | ##### Returns [Phaser.Weapon](phaser.weapon) - The Weapon Plugin. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 1014](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L1014)) ### trackPointer(pointer, offsetX, offsetY) → {[Phaser.Weapon](phaser.weapon)} Sets this Weapon to track the given Pointer. When a Weapon tracks a Pointer it will automatically update its `fireFrom` value to match the Pointers position within the Game World, adjusting the coordinates based on the offset arguments. This allows you to lock a Weapon to a Pointer, so that bullets are always launched from its location. Calling `trackPointer` will reset `Weapon.trackedSprite` to null, should it have been set, as you can only track *either* a Pointer, or a Sprite, at once, but not both. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `pointer` | [Phaser.Pointer](phaser.pointer) | <optional> | | The Pointer to track the position of. Defaults to `Input.activePointer` if not specified. | | `offsetX` | integer | <optional> | 0 | The horizontal offset from the Pointers position to be applied to the Weapon. | | `offsetY` | integer | <optional> | 0 | The vertical offset from the Pointers position to be applied to the Weapon. | ##### Returns [Phaser.Weapon](phaser.weapon) - This Weapon instance. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 659](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L659)) ### trackSprite(sprite, offsetX, offsetY, trackRotation) → {[Phaser.Weapon](phaser.weapon)} Sets this Weapon to track the given Sprite, or any Object with a public `world` Point object. When a Weapon tracks a Sprite it will automatically update its `fireFrom` value to match the Sprites position within the Game World, adjusting the coordinates based on the offset arguments. This allows you to lock a Weapon to a Sprite, so that bullets are always launched from its location. Calling `trackSprite` will reset `Weapon.trackedPointer` to null, should it have been set, as you can only track *either* a Sprite, or a Pointer, at once, but not both. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `sprite` | [Phaser.Sprite](phaser.sprite) | Object | | | The Sprite to track the position of. | | `offsetX` | integer | <optional> | 0 | The horizontal offset from the Sprites position to be applied to the Weapon. | | `offsetY` | integer | <optional> | 0 | The vertical offset from the Sprites position to be applied to the Weapon. | | `trackRotation` | boolean | <optional> | false | Should the Weapon also track the Sprites rotation? | ##### Returns [Phaser.Weapon](phaser.weapon) - This Weapon instance. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 626](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L626)) ### <internal> update() Internal update method, called by the PluginManager. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [plugins/weapon/WeaponPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js) ([Line 598](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/WeaponPlugin.js#L598))
programming_docs
phaser Class: Phaser.Signal Class: Phaser.Signal ==================== Constructor ----------- ### new Signal() Signals are what Phaser uses to handle events and event dispatching. You can listen for a Signal by binding a callback / function to it. This is done by using either `Signal.add` or `Signal.addOnce`. For example you can listen for a touch or click event from the Input Manager by using its `onDown` Signal: `game.input.onDown.add(function() { ... });` Rather than inline your function, you can pass a reference: `game.input.onDown.add(clicked, this);` `function clicked () { ... }` In this case the second argument (`this`) is the context in which your function should be called. Now every time the InputManager dispatches the `onDown` signal (or event), your function will be called. Very often a Signal will send arguments to your function. This is specific to the Signal itself. If you're unsure then check the documentation, or failing that simply do: `Signal.add(function() { console.log(arguments); })` and it will log all of the arguments your function received from the Signal. Sprites have lots of default signals you can listen to in their Events class, such as: `sprite.events.onKilled` Which is called automatically whenever the Sprite is killed. There are lots of other events, see the Events component for a list. As well as listening to pre-defined Signals you can also create your own: `var mySignal = new Phaser.Signal();` This creates a new Signal. You can bind a callback to it: `mySignal.add(myCallback, this);` and then finally when ready you can dispatch the Signal: `mySignal.dispatch(your arguments);` And your callback will be invoked. See the dispatch method for more details. Source code: [core/Signal.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js) ([Line 60](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js#L60)) Public Properties ----------------- ### active : boolean Is the Signal active? Only active signals will broadcast dispatched events. Setting this property during a dispatch will only affect the next dispatch. To stop the propagation of a signal from a listener use [halt](phaser.signal#halt). Default Value * true Source code: [core/Signal.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js) ([Line 100](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js#L100)) ### memorize : boolean Memorize the previously dispatched event? If an event has been memorized it is automatically dispatched when a new listener is added with [add](phaser.signal#add) or [addOnce](phaser.signal#addOnce). Use [forget](phaser.signal#forget) to clear any currently memorized event. Source code: [core/Signal.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js) ([Line 84](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js#L84)) Public Methods -------------- ### add(listener, listenerContext, priority, args) → {[Phaser.SignalBinding](phaser.signalbinding)} Add an event listener for this signal. An event listener is a callback with a related context and priority. You can optionally provide extra arguments which will be passed to the callback after any internal parameters. For example: `Phaser.Key.onDown` when dispatched will send the Phaser.Key object that caused the signal as the first parameter. Any arguments you've specified after `priority` will be sent as well: `fireButton.onDown.add(shoot, this, 0, 'lazer', 100);` When onDown dispatches it will call the `shoot` callback passing it: `Phaser.Key, 'lazer', 100`. Where the first parameter is the one that Key.onDown dispatches internally and 'lazer', and the value 100 were the custom arguments given in the call to 'add'. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `listener` | function | | | The function to call when this Signal is dispatched. | | `listenerContext` | object | <optional> | | The context under which the listener will be executed (i.e. the object that should represent the `this` variable). | | `priority` | number | <optional> | | The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added (default = 0) | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. | ##### Returns [Phaser.SignalBinding](phaser.signalbinding) - An Object representing the binding between the Signal and listener. Source code: [core/Signal.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js#L232)) ### addOnce(listener, listenerContext, priority, args) → {[Phaser.SignalBinding](phaser.signalbinding)} Add a one-time listener - the listener is automatically removed after the first execution. If there is as [memorized](phaser.signal#memorize) event then it will be dispatched and the listener will be removed immediately. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `listener` | function | | | The function to call when this Signal is dispatched. | | `listenerContext` | object | <optional> | | The context under which the listener will be executed (i.e. the object that should represent the `this` variable). | | `priority` | number | <optional> | | The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added (default = 0) | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. | ##### Returns [Phaser.SignalBinding](phaser.signalbinding) - An Object representing the binding between the Signal and listener. Source code: [core/Signal.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js) ([Line 274](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js#L274)) ### dispatch(params) Dispatch / broadcast the event to all listeners. To create an instance-bound dispatch for this Signal, use boundDispatch. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `params` | any | <optional> | Parameters that should be passed to each handler. | Source code: [core/Signal.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js) ([Line 395](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js#L395)) ### dispose() Dispose the signal - no more events can be dispatched. This removes all event listeners and clears references to external objects. Calling methods on a disposed objects results in undefined behavior. Source code: [core/Signal.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js) ([Line 451](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js#L451)) ### forget() Forget the currently [memorized](phaser.signal#memorize) event, if any. Source code: [core/Signal.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js) ([Line 437](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js#L437)) ### getNumListeners() → {integer} Gets the total number of listeners attached to this Signal. ##### Returns integer - Number of listeners attached to the Signal. Source code: [core/Signal.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js) ([Line 369](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js#L369)) ### halt() Stop propagation of the event, blocking the dispatch to next listener on the queue. This should be called only during event dispatch as calling it before/after dispatch won't affect another broadcast. See [active](phaser.signal#active) to enable/disable the signal entirely. Source code: [core/Signal.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js) ([Line 381](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js#L381)) ### has(listener, context) → {boolean} Check if a specific listener is attached. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `listener` | function | | Signal handler function. | | `context` | object | <optional> | Context on which listener will be executed (object that should represent the `this` variable inside listener function). | ##### Returns boolean - If Signal has the specified listener. Source code: [core/Signal.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js) ([Line 218](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js#L218)) ### remove(listener, context) → {function} Remove a single event listener. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `listener` | function | | | Handler function that should be removed. | | `context` | object | <optional> | null | Execution context (since you can add the same handler multiple times if executing in a different context). | ##### Returns function - Listener handler function. Source code: [core/Signal.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js) ([Line 305](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js#L305)) ### removeAll(context) Remove all event listeners. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `context` | object | <optional> | null | If specified only listeners for the given context will be removed. | Source code: [core/Signal.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js) ([Line 329](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js#L329)) ### toString() → {string} A string representation of the object. ##### Returns string - String representation of the object. Source code: [core/Signal.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js) ([Line 471](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Signal.js#L471)) phaser Class: Phaser.Component.PhysicsBody Class: Phaser.Component.PhysicsBody =================================== Constructor ----------- ### new PhysicsBody() The PhysicsBody component manages the Game Objects physics body and physics enabling. It also overrides the x and y properties, ensuring that any manual adjustment of them is reflected in the physics body itself. Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 13](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L13)) Public Properties ----------------- ### body : [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | null `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated properties and methods via it. By default Game Objects won't add themselves to any physics system and their `body` property will be `null`. To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`. You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group. Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5, so the physics body is centered on the Game Object. If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics. ##### Type * [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | null Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 91](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L91)) ### x : number The position of the Game Object on the x axis relative to the local coordinates of the parent. Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L98)) ### y : number The position of the Game Object on the y axis relative to the local coordinates of the parent. Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L124)) Public Methods -------------- ### <static> postUpdate() The PhysicsBody component postUpdate handler. Called automatically by the Game Object. Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 61](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L61)) ### <static> preUpdate() The PhysicsBody component preUpdate handler. Called automatically by the Game Object. Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 21](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L21)) phaser Class: Phaser.Component.FixedToCamera Class: Phaser.Component.FixedToCamera ===================================== Constructor ----------- ### new FixedToCamera() The FixedToCamera component enables a Game Object to be rendered relative to the game camera coordinates, regardless of where in the world the camera is. This is used for things like sticking game UI to the camera that scrolls as it moves around the world. Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 13](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L13)) Public Properties ----------------- ### cameraOffset : [Phaser.Point](phaser.point) The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L86)) ### fixedToCamera : boolean A Game Object that is "fixed" to the camera uses its x/y coordinates as offsets from the top left of the camera during rendering. The values are adjusted at the rendering stage, overriding the Game Objects actual world position. The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times regardless where in the world the camera is. The offsets are stored in the `cameraOffset` property. Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 56](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L56)) Public Methods -------------- ### <static> postUpdate() The FixedToCamera component postUpdate handler. Called automatically by the Game Object. Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 21](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L21)) phaser Class: Phaser.Cache Class: Phaser.Cache =================== Constructor ----------- ### new Cache(game) Phaser has one single cache in which it stores all assets. The cache is split up into sections, such as images, sounds, video, json, etc. All assets are stored using a unique string-based key as their identifier. Assets stored in different areas of the cache can have the same key, for example 'playerWalking' could be used as the key for both a sprite sheet and an audio file, because they are unique data types. The cache is automatically populated by the Phaser.Loader. When you use the loader to pull in external assets such as images they are automatically placed into their respective cache. Most common Game Objects, such as Sprites and Videos automatically query the cache to extract the assets they need on instantiation. You can access the cache from within a State via `this.cache`. From here you can call any public method it has, including adding new entries to it, deleting them or querying them. Understand that almost without exception when you get an item from the cache it will return a reference to the item stored in the cache, not a copy of it. Therefore if you retrieve an item and then modify it, the original object in the cache will also be updated, even if you don't put it back into the cache again. By default when you change State the cache is *not* cleared, although there is an option to clear it should your game require it. In a typical game set-up the cache is populated once after the main game has loaded and then used as an asset store. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 34](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L34)) Public Properties ----------------- ### [static] BINARY : number Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 166](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L166)) ### [static] BITMAPDATA : number Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 172](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L172)) ### [static] BITMAPFONT : number Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 178](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L178)) ### [static] CANVAS : number Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L124)) ### [static] DEFAULT : [PIXI.Texture](pixi.texture) The default image used for a texture when no other is specified. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 215](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L215)) ### [static] IMAGE : number Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 130](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L130)) ### [static] JSON : number Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 184](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L184)) ### [static] MISSING : [PIXI.Texture](pixi.texture) The default image used for a texture when the source image is missing. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 222](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L222)) ### [static] PHYSICS : number Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 154](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L154)) ### [static] RENDER\_TEXTURE : number Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 208](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L208)) ### [static] SHADER : number Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 202](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L202)) ### [static] SOUND : number Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 142](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L142)) ### [static] TEXT : number Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 148](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L148)) ### [static] TEXTURE : number Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 136](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L136)) ### [static] TILEMAP : number Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 160](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L160)) ### [static] VIDEO : number Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 196](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L196)) ### [static] XML : number Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 190](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L190)) ### autoResolveURL : boolean Automatically resolve resource URLs to absolute paths for use with the Cache.getURL method. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L45)) ### game : [Phaser.Game](phaser.game) Local reference to game. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 39](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L39)) ### onSoundUnlock : [Phaser.Signal](phaser.signal) This event is dispatched when the sound system is unlocked via a touch event on cellular devices. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 91](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L91)) Public Methods -------------- ### addBinary(key, binaryData) Add a binary object in to the cache. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key that this asset will be stored in the cache under. This should be unique within this cache. | | `binaryData` | object | The binary object to be added to the cache. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 424](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L424)) ### addBitmapData(key, bitmapData, frameData) → {[Phaser.BitmapData](phaser.bitmapdata)} Add a BitmapData object to the cache. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The key that this asset will be stored in the cache under. This should be unique within this cache. | | `bitmapData` | [Phaser.BitmapData](phaser.bitmapdata) | | | The BitmapData object to be addded to the cache. | | `frameData` | [Phaser.FrameData](phaser.framedata) | null | <optional> | (auto create) | Optional FrameData set associated with the given BitmapData. If not specified (or `undefined`) a new FrameData object is created containing the Bitmap's Frame. If `null` is supplied then no FrameData will be created. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - The BitmapData object to be addded to the cache. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 437](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L437)) ### addBitmapFont(key, url, data, atlasData, atlasType, xSpacing, ySpacing) Add a new Bitmap Font to the Cache. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The key that this asset will be stored in the cache under. This should be unique within this cache. | | `url` | string | | | The URL the asset was loaded from. If the asset was not loaded externally set to `null`. | | `data` | object | | | Extra font data. | | `atlasData` | object | | | Texture atlas frames data. | | `atlasType` | string | <optional> | 'xml' | The format of the texture atlas ( 'json' or 'xml' ). | | `xSpacing` | number | <optional> | 0 | If you'd like to add additional horizontal spacing between the characters then set the pixel value here. | | `ySpacing` | number | <optional> | 0 | If you'd like to add additional vertical spacing between the lines then set the pixel value here. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 462](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L462)) ### addCanvas(key, canvas, context) Add a new canvas object in to the cache. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `key` | string | | The key that this asset will be stored in the cache under. This should be unique within this cache. | | `canvas` | HTMLCanvasElement | | The Canvas DOM element. | | `context` | CanvasRenderingContext2D | <optional> | The context of the canvas element. If not specified it will default go `getContext('2d')`. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 230](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L230)) ### <internal> addDefaultImage() Adds a default image to be used in special cases such as WebGL Filters. It uses the special reserved key of `__default`. This method is called automatically when the Cache is created. This image is skipped when `Cache.destroy` is called due to its internal requirements. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 291](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L291)) ### addImage(key, url, data) → {object} Adds an Image file into the Cache. The file must have already been loaded, typically via Phaser.Loader, but can also have been loaded into the DOM. If an image already exists in the cache with the same key then it is removed and destroyed, and the new image inserted in its place. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key that this asset will be stored in the cache under. This should be unique within this cache. | | `url` | string | The URL the asset was loaded from. If the asset was not loaded externally set to `null`. | | `data` | object | Extra image data. | ##### Returns object - The full image object that was added to the cache. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 246](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L246)) ### addJSON(key, url, data) Add a new json object into the cache. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key that this asset will be stored in the cache under. This should be unique within this cache. | | `url` | string | The URL the asset was loaded from. If the asset was not loaded externally set to `null`. | | `data` | object | Extra json data. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 501](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L501)) ### <internal> addMissingImage() Adds an image to be used when a key is wrong / missing. It uses the special reserved key of `__missing`. This method is called automatically when the Cache is created. This image is skipped when `Cache.destroy` is called due to its internal requirements. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 316](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L316)) ### addPhysicsData(key, url, JSONData, format) Add a new physics data object to the Cache. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key that this asset will be stored in the cache under. This should be unique within this cache. | | `url` | string | The URL the asset was loaded from. If the asset was not loaded externally set to `null`. | | `JSONData` | object | The physics data object (a JSON file). | | `format` | number | The format of the physics data. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 390](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L390)) ### addRenderTexture(key, texture) Add a new Phaser.RenderTexture in to the cache. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key that this asset will be stored in the cache under. This should be unique within this cache. | | `texture` | [Phaser.RenderTexture](phaser.rendertexture) | The texture to use as the base of the RenderTexture. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 566](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L566)) ### addShader(key, url, data) Adds a Fragment Shader in to the Cache. The file must have already been loaded, typically via Phaser.Loader. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key that this asset will be stored in the cache under. This should be unique within this cache. | | `url` | string | The URL the asset was loaded from. If the asset was not loaded externally set to `null`. | | `data` | object | Extra shader data. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 550](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L550)) ### addSound(key, url, data, webAudio, audioTag) Adds a Sound file into the Cache. The file must have already been loaded, typically via Phaser.Loader. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key that this asset will be stored in the cache under. This should be unique within this cache. | | `url` | string | The URL the asset was loaded from. If the asset was not loaded externally set to `null`. | | `data` | object | Extra sound data. | | `webAudio` | boolean | True if the file is using web audio. | | `audioTag` | boolean | True if the file is using legacy HTML audio. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 338](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L338)) ### addSpriteSheet(key, url, data, frameWidth, frameHeight, frameMax, margin, spacing) Add a new sprite sheet in to the cache. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The key that this asset will be stored in the cache under. This should be unique within this cache. | | `url` | string | | | The URL the asset was loaded from. If the asset was not loaded externally set to `null`. | | `data` | object | | | Extra sprite sheet data. | | `frameWidth` | number | | | Width of the sprite sheet. | | `frameHeight` | number | | | Height of the sprite sheet. | | `frameMax` | number | <optional> | -1 | How many frames stored in the sprite sheet. If -1 then it divides the whole sheet evenly. | | `margin` | number | <optional> | 0 | If the frames have been drawn with a margin, specify the amount here. | | `spacing` | number | <optional> | 0 | If the frames have been drawn with spacing between them, specify the amount here. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 579](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L579)) ### addText(key, url, data) Add a new text data. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key that this asset will be stored in the cache under. This should be unique within this cache. | | `url` | string | The URL the asset was loaded from. If the asset was not loaded externally set to `null`. | | `data` | object | Extra text data. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 374](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L374)) ### addTextureAtlas(key, url, data, atlasData, format) Add a new texture atlas to the Cache. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key that this asset will be stored in the cache under. This should be unique within this cache. | | `url` | string | The URL the asset was loaded from. If the asset was not loaded externally set to `null`. | | `data` | object | Extra texture atlas data. | | `atlasData` | object | Texture atlas frames data. | | `format` | number | The format of the texture atlas. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 616](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L616)) ### addTilemap(key, url, mapData, format) Add a new tilemap to the Cache. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key that this asset will be stored in the cache under. This should be unique within this cache. | | `url` | string | The URL the asset was loaded from. If the asset was not loaded externally set to `null`. | | `mapData` | object | The tilemap data object (either a CSV or JSON file). | | `format` | number | The format of the tilemap data. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 407](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L407)) ### addVideo(key, url, data, isBlob) Adds a Video file into the Cache. The file must have already been loaded, typically via Phaser.Loader. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key that this asset will be stored in the cache under. This should be unique within this cache. | | `url` | string | The URL the asset was loaded from. If the asset was not loaded externally set to `null`. | | `data` | object | Extra video data. | | `isBlob` | boolean | True if the file was preloaded via xhr and the data parameter is a Blob. false if a Video tag was created instead. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 533](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L533)) ### addXML(key, url, data) Add a new xml object into the cache. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key that this asset will be stored in the cache under. This should be unique within this cache. | | `url` | string | The URL the asset was loaded from. If the asset was not loaded externally set to `null`. | | `data` | object | Extra text data. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 517](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L517)) ### checkBinaryKey(key) → {boolean} Checks if the given key exists in the Binary Cache. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset within the cache. | ##### Returns boolean - True if the key exists in the cache, otherwise false. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 915](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L915)) ### checkBitmapDataKey(key) → {boolean} Checks if the given key exists in the BitmapData Cache. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset within the cache. | ##### Returns boolean - True if the key exists in the cache, otherwise false. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 928](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L928)) ### checkBitmapFontKey(key) → {boolean} Checks if the given key exists in the BitmapFont Cache. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset within the cache. | ##### Returns boolean - True if the key exists in the cache, otherwise false. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 941](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L941)) ### checkCanvasKey(key) → {boolean} Checks if the given key exists in the Canvas Cache. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset within the cache. | ##### Returns boolean - True if the key exists in the cache, otherwise false. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 824](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L824)) ### checkImageKey(key) → {boolean} Checks if the given key exists in the Image Cache. Note that this also includes Texture Atlases, Sprite Sheets and Retro Fonts. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset within the cache. | ##### Returns boolean - True if the key exists in the cache, otherwise false. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 837](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L837)) ### checkJSONKey(key) → {boolean} Checks if the given key exists in the JSON Cache. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset within the cache. | ##### Returns boolean - True if the key exists in the cache, otherwise false. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 954](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L954)) ### checkKey(cache, key) → {boolean} Checks if a key for the given cache object type exists. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `cache` | integer | The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. | | `key` | string | The key of the asset within the cache. | ##### Returns boolean - True if the key exists, otherwise false. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 784](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L784)) ### checkPhysicsKey(key) → {boolean} Checks if the given key exists in the Physics Cache. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset within the cache. | ##### Returns boolean - True if the key exists in the cache, otherwise false. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 889](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L889)) ### checkRenderTextureKey(key) → {boolean} Checks if the given key exists in the Render Texture Cache. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset within the cache. | ##### Returns boolean - True if the key exists in the cache, otherwise false. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1006](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1006)) ### checkShaderKey(key) → {boolean} Checks if the given key exists in the Fragment Shader Cache. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset within the cache. | ##### Returns boolean - True if the key exists in the cache, otherwise false. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 993](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L993)) ### checkSoundKey(key) → {boolean} Checks if the given key exists in the Sound Cache. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset within the cache. | ##### Returns boolean - True if the key exists in the cache, otherwise false. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 863](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L863)) ### checkTextKey(key) → {boolean} Checks if the given key exists in the Text Cache. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset within the cache. | ##### Returns boolean - True if the key exists in the cache, otherwise false. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 876](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L876)) ### checkTextureKey(key) → {boolean} Checks if the given key exists in the Texture Cache. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset within the cache. | ##### Returns boolean - True if the key exists in the cache, otherwise false. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 850](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L850)) ### checkTilemapKey(key) → {boolean} Checks if the given key exists in the Tilemap Cache. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset within the cache. | ##### Returns boolean - True if the key exists in the cache, otherwise false. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 902](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L902)) ### checkURL(url) → {boolean} Checks if the given URL has been loaded into the Cache. This method will only work if Cache.autoResolveURL was set to `true` before any preloading took place. The method will make a DOM src call to the URL given, so please be aware of this for certain file types, such as Sound files on Firefox which may cause double-load instances. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `url` | string | The url to check for in the cache. | ##### Returns boolean - True if the url exists, otherwise false. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 803](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L803)) ### checkVideoKey(key) → {boolean} Checks if the given key exists in the Video Cache. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset within the cache. | ##### Returns boolean - True if the key exists in the cache, otherwise false. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 980](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L980)) ### checkXMLKey(key) → {boolean} Checks if the given key exists in the XML Cache. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset within the cache. | ##### Returns boolean - True if the key exists in the cache, otherwise false. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 967](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L967)) ### <internal> clearGLTextures() Empties out all of the GL Textures from Images stored in the cache. This is called automatically when the WebGL context is lost and then restored. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1897](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1897)) ### decodedSound(key, data) Add a new decoded sound. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset within the cache. | | `data` | object | Extra sound data. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 726](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L726)) ### destroy() Clears the cache. Removes every local cache object reference. If an object in the cache has a `destroy` method it will also be called. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1947](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1947)) ### getBaseTexture(key, cache) → {[PIXI.BaseTexture](pixi.basetexture)} Gets a PIXI.BaseTexture by key from the given Cache. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Asset key of the image for which you want the BaseTexture for. | | `cache` | integer | <optional> | Phaser.Cache.IMAGE | The cache to search for the item in. | ##### Returns [PIXI.BaseTexture](pixi.basetexture) - The BaseTexture object. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1426](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1426)) ### getBinary(key) → {object} Gets a binary object from the cache. The object is looked-up based on the key given. Note: If the object cannot be found a `console.warn` message is displayed. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset to retrieve from the cache. | ##### Returns object - The binary data object. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1266](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1266)) ### getBitmapData(key) → {[Phaser.BitmapData](phaser.bitmapdata)} Gets a BitmapData object from the cache. The object is looked-up based on the key given. Note: If the object cannot be found a `console.warn` message is displayed. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset to retrieve from the cache. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - The requested BitmapData object if found, or null if not. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1283](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1283)) ### getBitmapFont(key) → {Phaser.BitmapFont} Gets a Bitmap Font object from the cache. The object is looked-up based on the key given. Note: If the object cannot be found a `console.warn` message is displayed. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset to retrieve from the cache. | ##### Returns Phaser.BitmapFont - The requested BitmapFont object if found, or null if not. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1300](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1300)) ### getCanvas(key) → {object} Gets a Canvas object from the cache. The object is looked-up based on the key given. Note: If the object cannot be found a `console.warn` message is displayed. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset to retrieve from the cache. | ##### Returns object - The canvas object or `null` if no item could be found matching the given key. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1061](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1061)) ### getFrame(key, cache) → {[Phaser.Frame](phaser.frame)} Get a single frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Asset key of the frame data to retrieve from the Cache. | | `cache` | integer | <optional> | Phaser.Cache.IMAGE | The cache to search for the item in. | ##### Returns [Phaser.Frame](phaser.frame) - The frame data. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1442](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1442)) ### getFrameByIndex(key, index, cache) → {[Phaser.Frame](phaser.frame)} Get a single frame out of a frameData set by key. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Asset key of the frame data to retrieve from the Cache. | | `index` | number | | | The index of the frame you want to get. | | `cache` | integer | <optional> | Phaser.Cache.IMAGE | The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. | ##### Returns [Phaser.Frame](phaser.frame) - The frame object. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1536](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1536)) ### getFrameByName(key, name, cache) → {[Phaser.Frame](phaser.frame)} Get a single frame out of a frameData set by key. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Asset key of the frame data to retrieve from the Cache. | | `name` | string | | | The name of the frame you want to get. | | `cache` | integer | <optional> | Phaser.Cache.IMAGE | The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. | ##### Returns [Phaser.Frame](phaser.frame) - The frame object. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1560](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1560)) ### getFrameCount(key, cache) → {number} Get the total number of frames contained in the FrameData object specified by the given key. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Asset key of the FrameData you want. | | `cache` | integer | <optional> | Phaser.Cache.IMAGE | The cache to search for the item in. | ##### Returns number - Then number of frames. 0 if the image is not found. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1458](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1458)) ### getFrameData(key, cache) → {[Phaser.FrameData](phaser.framedata)} Gets a Phaser.FrameData object from the Image Cache. The object is looked-up based on the key given. Note: If the object cannot be found a `console.warn` message is displayed. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Asset key of the frame data to retrieve from the Cache. | | `cache` | integer | <optional> | Phaser.Cache.IMAGE | The cache to search for the item in. | ##### Returns [Phaser.FrameData](phaser.framedata) - The frame data. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1481](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1481)) ### getImage(key, full) → {Image} Gets a Image object from the cache. This returns a DOM Image object, not a Phaser.Image object. The object is looked-up based on the key given. Note: If the object cannot be found a `console.warn` message is displayed. Only the Image cache is searched, which covers images loaded via Loader.image, Sprite Sheets and Texture Atlases. If you need the image used by a bitmap font or similar then please use those respective 'get' methods. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | <optional> | | The key of the asset to retrieve from the cache. If not given or null it will return a default image. If given but not found in the cache it will throw a warning and return the missing image. | | `full` | boolean | <optional> | false | If true the full image object will be returned, if false just the HTML Image object is returned. | ##### Returns Image - The Image object if found in the Cache, otherwise `null`. If `full` was true then a JavaScript object is returned. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1078](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1078)) ### getItem(key, cache, method, property) → {object} Get an item from a cache based on the given key and property. This method is mostly used internally by other Cache methods such as `getImage` but is exposed publicly for your own use as well. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `key` | string | | The key of the asset within the cache. | | `cache` | integer | | The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. | | `method` | string | <optional> | The string name of the method calling getItem. Can be empty, in which case no console warning is output. | | `property` | string | <optional> | If you require a specific property from the cache item, specify it here. | ##### Returns object - The cached item if found, otherwise `null`. If the key is invalid and `method` is set then a console.warn is output. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1023](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1023)) ### getJSON(key, clone) → {object} Gets a JSON object from the cache. The object is looked-up based on the key given. Note: If the object cannot be found a `console.warn` message is displayed. You can either return the object by reference (the default), or return a clone of it by setting the `clone` argument to `true`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The key of the asset to retrieve from the cache. | | `clone` | boolean | <optional> | false | Return a clone of the original object (true) or a reference to it? (false) | ##### Returns object - The JSON object, or an Array if the key points to an Array property. If the property wasn't found, it returns null. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1317](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1317)) ### getKeys(cache) → {Array} Gets all keys used in the requested Cache. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `cache` | integer | <optional> | Phaser.Cache.IMAGE | The Cache you wish to get the keys from. Can be any of the Cache consts such as `Phaser.Cache.IMAGE`, `Phaser.Cache.SOUND` etc. | ##### Returns Array - The array of keys in the requested cache. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1609](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1609)) ### getPhysicsData(key, object, fixtureKey) → {object} Gets a Physics Data object from the cache. The object is looked-up based on the key given. Note: If the object cannot be found a `console.warn` message is displayed. You can get either the entire data set, a single object or a single fixture of an object from it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The key of the asset to retrieve from the cache. | | `object` | string | <optional> | null | If specified it will return just the physics object that is part of the given key, if null it will return them all. | | `fixtureKey` | string | | | Fixture key of fixture inside an object. This key can be set per fixture with the Phaser Exporter. | ##### Returns object - The requested physics object data if found. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1187](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1187)) ### getRenderTexture(key) → {Object} Gets a RenderTexture object from the cache. The object is looked-up based on the key given. Note: If the object cannot be found a `console.warn` message is displayed. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset to retrieve from the cache. | ##### Returns Object - The object with Phaser.RenderTexture and Phaser.Frame. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1405](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1405)) ### getShader(key) → {string} Gets a fragment shader object from the cache. The object is looked-up based on the key given. Note: If the object cannot be found a `console.warn` message is displayed. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset to retrieve from the cache. | ##### Returns string - The shader object. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1388](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1388)) ### getSound(key) → {[Phaser.Sound](phaser.sound)} Gets a Phaser.Sound object from the cache. The object is looked-up based on the key given. Note: If the object cannot be found a `console.warn` message is displayed. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset to retrieve from the cache. | ##### Returns [Phaser.Sound](phaser.sound) - The sound object. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1136](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1136)) ### getSoundData(key) → {object} Gets a raw Sound data object from the cache. The object is looked-up based on the key given. Note: If the object cannot be found a `console.warn` message is displayed. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset to retrieve from the cache. | ##### Returns object - The sound data. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1153)) ### getText(key) → {object} Gets a Text object from the cache. The object is looked-up based on the key given. Note: If the object cannot be found a `console.warn` message is displayed. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset to retrieve from the cache. | ##### Returns object - The text data. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1170](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1170)) ### getTextureFrame(key) → {[Phaser.Frame](phaser.frame)} Get a single texture frame by key. You'd only do this to get the default Frame created for a non-atlas / spritesheet image. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset to retrieve from the cache. | ##### Returns [Phaser.Frame](phaser.frame) - The frame data. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1121](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1121)) ### getTilemapData(key) → {object} Gets a raw Tilemap data object from the cache. This will be in either CSV or JSON format. The object is looked-up based on the key given. Note: If the object cannot be found a `console.warn` message is displayed. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset to retrieve from the cache. | ##### Returns object - The raw tilemap data in CSV or JSON format. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1249](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1249)) ### getURL(url) → {object} Get a cached object by the URL. This only returns a value if you set Cache.autoResolveURL to `true` *before* starting the preload of any assets. Be aware that every call to this function makes a DOM src query, so use carefully and double-check for implications in your target browsers/devices. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `url` | string | The url for the object loaded to get from the cache. | ##### Returns object - The cached object. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1584](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1584)) ### getVideo(key) → {[Phaser.Video](phaser.video)} Gets a Phaser.Video object from the cache. The object is looked-up based on the key given. Note: If the object cannot be found a `console.warn` message is displayed. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset to retrieve from the cache. | ##### Returns [Phaser.Video](phaser.video) - The video object. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1371](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1371)) ### getXML(key) → {object} Gets an XML object from the cache. The object is looked-up based on the key given. Note: If the object cannot be found a `console.warn` message is displayed. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset to retrieve from the cache. | ##### Returns object - The XML object. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1354](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1354)) ### hasFrameData(key, cache) → {boolean} Check if the FrameData for the given key exists in the Image Cache. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Asset key of the frame data to retrieve from the Cache. | | `cache` | integer | <optional> | Phaser.Cache.IMAGE | The cache to search for the item in. | ##### Returns boolean - True if the given key has frameData in the cache, otherwise false. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1501](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1501)) ### isSoundDecoded(key) → {boolean} Check if the given sound has finished decoding. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset within the cache. | ##### Returns boolean - The decoded state of the Sound object. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 743](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L743)) ### isSoundReady(key) → {boolean} Check if the given sound is ready for playback. A sound is considered ready when it has finished decoding and the device is no longer touch locked. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset within the cache. | ##### Returns boolean - True if the sound is decoded and the device is not touch locked. Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 761](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L761)) ### reloadSound(key) Reload a Sound file from the server. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset within the cache. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 666](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L666)) ### reloadSoundComplete(key) Fires the onSoundUnlock event when the sound has completed reloading. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset within the cache. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 691](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L691)) ### removeBinary(key) Removes a binary file from the cache. Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere then it will persist in memory. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | Key of the asset you want to remove. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1747](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1747)) ### removeBitmapData(key) Removes a bitmap data from the cache. Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere then it will persist in memory. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | Key of the asset you want to remove. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1762](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1762)) ### removeBitmapFont(key) Removes a bitmap font from the cache. Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere then it will persist in memory. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | Key of the asset you want to remove. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1777](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1777)) ### removeCanvas(key) Removes a canvas from the cache. Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere then it will persist in memory. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | Key of the asset you want to remove. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1641](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1641)) ### removeImage(key, destroyBaseTexture) Removes an image from the cache. You can optionally elect to destroy it as well. This calls BaseTexture.destroy on it. Note that this only removes it from the Phaser Cache. If you still have references to the data elsewhere then it will persist in memory. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Key of the asset you want to remove. | | `destroyBaseTexture` | boolean | <optional> | true | Should the BaseTexture behind this image also be destroyed? | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1656](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1656)) ### removeJSON(key) Removes a json object from the cache. Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere then it will persist in memory. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | Key of the asset you want to remove. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1792](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1792)) ### removePhysics(key) Removes a physics data file from the cache. Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere then it will persist in memory. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | Key of the asset you want to remove. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1717](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1717)) ### removeRenderTexture(key) Removes a Render Texture from the cache. Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere then it will persist in memory. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | Key of the asset you want to remove. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1852](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1852)) ### removeShader(key) Removes a shader from the cache. Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere then it will persist in memory. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | Key of the asset you want to remove. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1837](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1837)) ### removeSound(key) Removes a sound from the cache. If any `Phaser.Sound` objects use the audio file in the cache that you remove with this method, they will *automatically* destroy themselves. If you wish to have full control over when Sounds are destroyed then you must finish your house-keeping and destroy them all yourself first, before calling this method. Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere then it will persist in memory. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | Key of the asset you want to remove. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1683](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1683)) ### removeSpriteSheet(key) Removes a Sprite Sheet from the cache. Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere then it will persist in memory. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | Key of the asset you want to remove. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1867](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1867)) ### removeText(key) Removes a text file from the cache. Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere then it will persist in memory. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | Key of the asset you want to remove. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1702](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1702)) ### removeTextureAtlas(key) Removes a Texture Atlas from the cache. Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere then it will persist in memory. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | Key of the asset you want to remove. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1882](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1882)) ### removeTilemap(key) Removes a tilemap from the cache. Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere then it will persist in memory. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | Key of the asset you want to remove. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1732](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1732)) ### removeVideo(key) Removes a video from the cache. Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere then it will persist in memory. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | Key of the asset you want to remove. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1822](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1822)) ### removeXML(key) Removes a xml object from the cache. Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere then it will persist in memory. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | Key of the asset you want to remove. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1807](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1807)) ### updateFrameData(key, frameData, cache) Replaces a set of frameData with a new Phaser.FrameData object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The unique key by which you will reference this object. | | `frameData` | number | | | The new FrameData. | | `cache` | integer | <optional> | Phaser.Cache.IMAGE | The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 1517](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L1517)) ### updateSound(key) Updates the sound object in the cache. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the asset within the cache. | Source code: [loader/Cache.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js) ([Line 709](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Cache.js#L709))
programming_docs
phaser Class: Phaser.Utils Class: Phaser.Utils =================== Constructor ----------- ### new Utils() Source code: [utils/Utils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js) ([Line 11](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js#L11)) Classes ------- [Debug](phaser.utils.debug) Public Methods -------------- ### <static> extend(deep, target) → {object} This is a slightly modified version of http://api.jquery.com/jQuery.extend/ ##### Parameters | Name | Type | Description | | --- | --- | --- | | `deep` | boolean | Perform a deep copy? | | `target` | object | The target object to copy to. | ##### Returns object - The extended object. Source code: [utils/Utils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js) ([Line 258](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js#L258)) ### <static> getProperty(obj, prop) → {\*} Gets an objects property by string. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `obj` | object | The object to traverse. | | `prop` | string | The property whose value will be returned. | ##### Returns \* - the value of the property or null if property isn't found . Source code: [utils/Utils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js) ([Line 27](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js#L27)) ### <static> isPlainObject(obj) → {boolean} This is a slightly modified version of jQuery.isPlainObject. A plain object is an object whose internal class property is [object Object]. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `obj` | object | The object to inspect. | ##### Returns boolean - * true if the object is plain, otherwise false. Source code: [utils/Utils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js) ([Line 222](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js#L222)) ### <static> mixin(from, to) → {object} Mixes the source object into the destination object, returning the newly modified destination object. Based on original code by @mudcube ##### Parameters | Name | Type | Description | | --- | --- | --- | | `from` | object | The object to copy (the source object). | | `to` | object | The object to copy to (the destination object). | ##### Returns object - The modified destination object. Source code: [utils/Utils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js) ([Line 390](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js#L390)) ### <static> mixinPrototype(target, mixin, replace) Mixes in an existing mixin object with the target. Values in the mixin that have either `get` or `set` functions are created as properties via `defineProperty` *except* if they also define a `clone` method - if a clone method is defined that is called instead and the result is assigned directly. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `target` | object | | | The target object to receive the new functions. | | `mixin` | object | | | The object to copy the functions from. | | `replace` | boolean | <optional> | false | If the target object already has a matching function should it be overwritten or not? | Source code: [utils/Utils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js) ([Line 338](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js#L338)) ### <static> pad(str, len, pad, dir) → {string} Takes the given string and pads it out, to the length required, using the character specified. For example if you need a string to be 6 characters long, you can call: `pad('bob', 6, '-', 2)` This would return: `bob---` as it has padded it out to 6 characters, using the `-` on the right. You can also use it to pad numbers (they are always returned as strings): `pad(512, 6, '0', 1)` Would return: `000512` with the string padded to the left. If you don't specify a direction it'll pad to both sides: `pad('c64', 7, '*')` Would return: `**c64**` ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `str` | string | | | The target string. `toString()` will be called on the string, which means you can also pass in common data types like numbers. | | `len` | integer | <optional> | 0 | The number of characters to be added. | | `pad` | string | <optional> | " " | The string to pad it out with (defaults to a space). | | `dir` | integer | <optional> | 3 | The direction dir = 1 (left), 2 (right), 3 (both). | ##### Returns string - The padded string. Source code: [utils/Utils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js) ([Line 161](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js#L161)) ### <static> parseDimension(size, dimension) → {number} Get a unit dimension from a string. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `size` | string | number | The size to parse. | | `dimension` | number | The window dimension to check. | ##### Returns number - The parsed dimension. Source code: [utils/Utils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js) ([Line 118](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js#L118)) ### <static> reverseString(string) → {string} Takes the given string and reverses it, returning the reversed string. For example if given the string `Atari 520ST` it would return `TS025 iratA`. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `string` | string | The string to be reversed. | ##### Returns string - The reversed string. Source code: [utils/Utils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js) ([Line 13](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js#L13)) ### <static> setProperty(obj, prop) → {object} Sets an objects property by string. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `obj` | object | The object to traverse | | `prop` | string | The property whose value will be changed | ##### Returns object - The object on which the property was set. Source code: [utils/Utils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js) ([Line 60](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js#L60)) ### chanceRoll(chance) → {boolean} Generate a random bool result based on the chance value. Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `chance` | number | The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%). | ##### Returns boolean - True if the roll passed, or false otherwise. Source code: [utils/Utils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js) ([Line 91](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js#L91)) ### randomChoice(choice1, choice2) → {any} Choose between one of two values randomly. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `choice1` | any | | | `choice2` | any | | ##### Returns any - The randomly selected choice Source code: [utils/Utils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js) ([Line 106](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Utils.js#L106)) phaser Class: Phaser.Canvas Class: Phaser.Canvas ==================== Constructor ----------- ### new Canvas() The Canvas class handles everything related to creating the `canvas` DOM tag that Phaser will use, including styles, offset and aspect ratio. Source code: [utils/Canvas.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js) ([Line 14](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js#L14)) Public Methods -------------- ### <static> addToDOM(canvas, parent, overflowHidden) → {HTMLCanvasElement} Adds the given canvas element to the DOM. The canvas will be added as a child of the given parent. If no parent is given it will be added as a child of the document.body. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `canvas` | HTMLCanvasElement | | | The canvas to be added to the DOM. | | `parent` | string | HTMLElement | | | The DOM element to add the canvas to. | | `overflowHidden` | boolean | <optional> | true | If set to true it will add the overflow='hidden' style to the parent DOM element. | ##### Returns HTMLCanvasElement - Returns the source canvas. Source code: [utils/Canvas.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js) ([Line 109](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js#L109)) ### <static> create(parent, width, height, id, skipPool) → {HTMLCanvasElement} Creates a `canvas` DOM element. The element is not automatically added to the document. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | object | | | The object that will own the canvas that is created. | | `width` | number | <optional> | 256 | The width of the canvas element. | | `height` | number | <optional> | 256 | The height of the canvas element.. | | `id` | string | <optional> | (none) | If specified, and not the empty string, this will be set as the ID of the canvas element. Otherwise no ID will be set. | | `skipPool` | boolean | <optional> | false | If `true` the canvas will not be placed in the CanvasPool global. | ##### Returns HTMLCanvasElement - The newly created canvas element. Source code: [utils/Canvas.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js) ([Line 16](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js#L16)) ### <static> getSmoothingEnabled(context) → {boolean} Returns `true` if the given context has image smoothing enabled, otherwise returns `false`. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `context` | CanvasRenderingContext2D | The context to check for smoothing on. | ##### Returns boolean - True if the given context has image smoothing enabled, otherwise false. Source code: [utils/Canvas.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js) ([Line 242](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js#L242)) ### <static> getSmoothingPrefix(context) → {string | null} Gets the Smoothing Enabled vendor prefix being used on the given context, or null if not set. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `context` | CanvasRenderingContext2D | The context to enable or disable the image smoothing on. | ##### Returns string | null - Returns the smoothingEnabled vendor prefix, or null if not set on the context. Source code: [utils/Canvas.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js) ([Line 217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js#L217)) ### <static> removeFromDOM(canvas) Removes the given canvas element from the DOM. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `canvas` | HTMLCanvasElement | The canvas to be removed from the DOM. | Source code: [utils/Canvas.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js) ([Line 156](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js#L156)) ### <static> setBackgroundColor(canvas, color) → {HTMLCanvasElement} Sets the background color behind the canvas. This changes the canvas style property. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `canvas` | HTMLCanvasElement | | | The canvas to set the background color on. | | `color` | string | <optional> | 'rgb(0,0,0)' | The color to set. Can be in the format 'rgb(r,g,b)', or '#RRGGBB' or any valid CSS color. | ##### Returns HTMLCanvasElement - Returns the source canvas. Source code: [utils/Canvas.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js) ([Line 47](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js#L47)) ### <static> setImageRenderingBicubic(canvas) → {HTMLCanvasElement} Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto'). Note that if this doesn't given the desired result then see the CanvasUtils.setSmoothingEnabled method. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `canvas` | HTMLCanvasElement | The canvas to set image-rendering bicubic on. | ##### Returns HTMLCanvasElement - Returns the source canvas. Source code: [utils/Canvas.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js) ([Line 283](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js#L283)) ### <static> setImageRenderingCrisp(canvas) → {HTMLCanvasElement} Sets the CSS image-rendering property on the given canvas to be 'crisp' (aka 'optimize contrast' on webkit). Note that if this doesn't given the desired result then see the setSmoothingEnabled. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `canvas` | HTMLCanvasElement | The canvas to set image-rendering crisp on. | ##### Returns HTMLCanvasElement - Returns the source canvas. Source code: [utils/Canvas.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js) ([Line 260](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js#L260)) ### <static> setSmoothingEnabled(context, value) → {CanvasRenderingContext2D} Sets the Image Smoothing property on the given context. Set to false to disable image smoothing. By default browsers have image smoothing enabled, which isn't always what you visually want, especially when using pixel art in a game. Note that this sets the property on the context itself, so that any image drawn to the context will be affected. This sets the property across all current browsers but support is patchy on earlier browsers, especially on mobile. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `context` | CanvasRenderingContext2D | The context to enable or disable the image smoothing on. | | `value` | boolean | If set to true it will enable image smoothing, false will disable it. | ##### Returns CanvasRenderingContext2D - Returns the source context. Source code: [utils/Canvas.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js) ([Line 192](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js#L192)) ### <static> setTouchAction(canvas, value) → {HTMLCanvasElement} Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `canvas` | HTMLCanvasElement | | The canvas to set the touch action on. | | `value` | string | <optional> | The touch action to set. Defaults to 'none'. | ##### Returns HTMLCanvasElement - The source canvas. Source code: [utils/Canvas.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js) ([Line 65](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js#L65)) ### <static> setTransform(context, translateX, translateY, scaleX, scaleY, skewX, skewY) → {CanvasRenderingContext2D} Sets the transform of the given canvas to the matrix values provided. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `context` | CanvasRenderingContext2D | The context to set the transform on. | | `translateX` | number | The value to translate horizontally by. | | `translateY` | number | The value to translate vertically by. | | `scaleX` | number | The value to scale horizontally by. | | `scaleY` | number | The value to scale vertically by. | | `skewX` | number | The value to skew horizontaly by. | | `skewY` | number | The value to skew vertically by. | ##### Returns CanvasRenderingContext2D - Returns the source context. Source code: [utils/Canvas.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js#L171)) ### <static> setUserSelect(canvas, value) → {HTMLCanvasElement} Sets the user-select property on the canvas style. Can be used to disable default browser selection actions. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `canvas` | HTMLCanvasElement | | The canvas to set the touch action on. | | `value` | string | <optional> | The touch action to set. Defaults to 'none'. | ##### Returns HTMLCanvasElement - The source canvas. Source code: [utils/Canvas.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Canvas.js#L85)) phaser Class: Phaser.Component.Health Class: Phaser.Component.Health ============================== Constructor ----------- ### new Health() The Health component provides the ability for Game Objects to have a `health` property that can be damaged and reset through game code. Requires the LifeSpan component. Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 14](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L14)) Public Properties ----------------- ### damage Damages the Game Object. This removes the given amount of health from the `health` property. If health is taken below or is equal to zero then the `kill` method is called. Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L46)) ### heal Heal the Game Object. This adds the given amount of health to the `health` property. Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 90](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L90)) ### health : number The Game Objects health value. This is a handy property for setting and manipulating health on a Game Object. It can be used in combination with the `damage` method or modified directly. Default Value * 1 Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L26)) ### maxHealth : number The Game Objects maximum health value. This works in combination with the `heal` method to ensure the health value never exceeds the maximum. Default Value * 100 Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 35](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L35)) ### setHealth Sets the health property of the Game Object to the given amount. Will never exceed the `maxHealth` value. Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 70](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L70))
programming_docs
phaser Class: Phaser.BitmapText Class: Phaser.BitmapText ======================== Constructor ----------- ### new BitmapText(game, x, y, font, text, size, align) BitmapText objects work by taking a texture file and an XML or JSON file that describes the font structure. It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to match the font structure. BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability to use Web Fonts, however you trade this flexibility for rendering speed. You can also create visually compelling BitmapTexts by processing the font texture in an image editor, applying fills and any other effects required. To create multi-line text insert \r, \n or \r\n escape codes into the text string. If you are having performance issues due to the volume of sprites being rendered, and do not require the text to be constantly updating, you can use BitmapText.generateTexture to create a static texture from this BitmapText. To create a BitmapText data files you can use: BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner Littera (Web-based, free): http://kvazars.com/littera/ For most use cases it is recommended to use XML. If you wish to use JSON, the formatting should be equal to the result of converting a valid XML file through the popular X2JS library. An online tool for conversion can be found here: http://codebeautify.org/xmltojson If you were using an older version of Phaser (< 2.4) and using the DOMish parser hack, please remove this. It isn't required any longer. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | | A reference to the currently running game. | | `x` | number | | | X coordinate to display the BitmapText object at. | | `y` | number | | | Y coordinate to display the BitmapText object at. | | `font` | string | | | The key of the BitmapText as stored in Phaser.Cache. | | `text` | string | <optional> | '' | The text that will be rendered. This can also be set later via BitmapText.text. | | `size` | number | <optional> | 32 | The size the font will be rendered at in pixels. | | `align` | string | <optional> | 'left' | The alignment of multi-line text. Has no effect if there is only one line of text. | Source code: [gameobjects/BitmapText.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js#L54)) Extends ------- * [PIXI.DisplayObjectContainer](pixi.displayobjectcontainer) * [Phaser.Component.Core](phaser.component.core) * [Phaser.Component.Angle](phaser.component.angle) * [Phaser.Component.AutoCull](phaser.component.autocull) * [Phaser.Component.Bounds](phaser.component.bounds) * [Phaser.Component.Destroy](phaser.component.destroy) * [Phaser.Component.FixedToCamera](phaser.component.fixedtocamera) * [Phaser.Component.InputEnabled](phaser.component.inputenabled) * [Phaser.Component.InWorld](phaser.component.inworld) * [Phaser.Component.LifeSpan](phaser.component.lifespan) * [Phaser.Component.PhysicsBody](phaser.component.physicsbody) * [Phaser.Component.Reset](phaser.component.reset) Public Properties ----------------- ### align : string Alignment for multi-line text ('left', 'center' or 'right'), does not affect single lines of text. Source code: [gameobjects/BitmapText.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js) ([Line 535](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js#L535)) ### alive : boolean A useful flag to control if the Game Object is alive or dead. This is set automatically by the Health components `damage` method should the object run out of health. Or you can toggle it via your game code. This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. Inherited From * [Phaser.Component.LifeSpan#alive](phaser.component.lifespan#alive) Default Value * true Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L50)) ### anchor : [Phaser.Point](phaser.point) The anchor value of this BitmapText. Source code: [gameobjects/BitmapText.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js) ([Line 92](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js#L92)) ### angle : number The angle property is the rotation of the Game Object in *degrees* from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90. If you wish to work in radians instead of degrees you can use the property `rotation` instead. Working in radians is slightly faster as it doesn't have to perform any calculations. Inherited From * [Phaser.Component.Angle#angle](phaser.component.angle#angle) Source code: [gameobjects/components/Angle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js#L29)) ### animations : [Phaser.AnimationManager](phaser.animationmanager) If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. Through it you can create, play, pause and stop animations. Inherited From * [Phaser.Component.Core#animations](phaser.component.core#animations) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 193](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L193)) See * [Phaser.AnimationManager](phaser.animationmanager) ### autoCull : boolean A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, or you have tested performance and find it acceptable. Inherited From * [Phaser.Component.AutoCull#autoCull](phaser.component.autocull#autoCull) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L28)) ### body : [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | null `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated properties and methods via it. By default Game Objects won't add themselves to any physics system and their `body` property will be `null`. To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`. You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group. Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5, so the physics body is centered on the Game Object. If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics. ##### Type * [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | null Inherited From * [Phaser.Component.PhysicsBody#body](phaser.component.physicsbody#body) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 91](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L91)) ### bottom : number The sum of the y and height properties. This is the same as `y + height - offsetY`. Inherited From * [Phaser.Component.Bounds#bottom](phaser.component.bounds#bottom) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 168](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L168)) ### cameraOffset : [Phaser.Point](phaser.point) The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. Inherited From * [Phaser.Component.FixedToCamera#cameraOffset](phaser.component.fixedtocamera#cameraOffset) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L86)) ### centerX : number The center x coordinate of the Game Object. This is the same as `(x - offsetX) + (width / 2)`. Inherited From * [Phaser.Component.Bounds#centerX](phaser.component.bounds#centerX) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L58)) ### centerY : number The center y coordinate of the Game Object. This is the same as `(y - offsetY) + (height / 2)`. Inherited From * [Phaser.Component.Bounds#centerY](phaser.component.bounds#centerY) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 80](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L80)) ### checkWorldBounds : boolean If this is set to `true` the Game Object checks if it is within the World bounds each frame. When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event. If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event. It also optionally kills the Game Object if `outOfBoundsKill` is `true`. When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame. This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, or you have tested performance and find it acceptable. Inherited From * [Phaser.Component.InWorld#checkWorldBounds](phaser.component.inworld#checkWorldBounds) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L98)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### <internal> components : Object The components this Game Object has installed. Inherited From * [Phaser.Component.Core#components](phaser.component.core#components) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 167](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L167)) ### data : Object An empty Object that belongs to this Game Object. This value isn't ever used internally by Phaser, but may be used by your own code, or by Phaser Plugins, to store data that needs to be associated with the Game Object, without polluting the Game Object directly. Inherited From * [Phaser.Component.Core#data](phaser.component.core#data) Default Value * {} Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 160](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L160)) ### debug : boolean A debug flag designed for use with `Game.enableStep`. Inherited From * [Phaser.Component.Core#debug](phaser.component.core#debug) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 218](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L218)) ### [readonly] destroyPhase : boolean As a Game Object runs through its destroy method this flag is set to true, and can be checked in any sub-systems or plugins it is being destroyed from. Inherited From * [Phaser.Component.Destroy#destroyPhase](phaser.component.destroy#destroyPhase) Source code: [gameobjects/components/Destroy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js#L22)) ### dirty : boolean The dirty state of this object. Source code: [gameobjects/BitmapText.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js#L153)) ### events : [Phaser.Events](phaser.events) All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this Game Object, or any of its components. Inherited From * [Phaser.Component.Core#events](phaser.component.core#events) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 185](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L185)) See * [Phaser.Events](phaser.events) ### exists : boolean Controls if this Game Object is processed by the core game loop. If this Game Object has a physics body it also controls if its physics body is updated or not. When `exists` is set to `false` it will remove its physics body from the physics world if it has one. It also toggles the `visible` property to false as well. Setting `exists` to true will add its physics body back in to the physics world, if it has one. It will also set the `visible` property to `true`. Inherited From * [Phaser.Component.Core#exists](phaser.component.core#exists) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 284](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L284)) ### fixedToCamera : boolean A Game Object that is "fixed" to the camera uses its x/y coordinates as offsets from the top left of the camera during rendering. The values are adjusted at the rendering stage, overriding the Game Objects actual world position. The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times regardless where in the world the camera is. The offsets are stored in the `cameraOffset` property. Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. Inherited From * [Phaser.Component.FixedToCamera#fixedToCamera](phaser.component.fixedtocamera#fixedToCamera) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 56](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L56)) ### font : string The font the text will be rendered in, i.e. 'Arial'. Must be loaded in the browser before use. Source code: [gameobjects/BitmapText.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js) ([Line 579](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js#L579)) ### fontSize : number The size of the font in pixels. Source code: [gameobjects/BitmapText.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js) ([Line 602](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js#L602)) ### [readonly] fresh : boolean A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. This property is mostly used internally by the physics systems, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#fresh](phaser.component.core#fresh) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 248](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L248)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Inherited From * [Phaser.Component.Core#game](phaser.component.core#game) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 142](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L142)) ### height : number The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#height](pixi.displayobjectcontainer#height) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 600](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L600)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### [readonly] inCamera : boolean Checks if the Game Objects bounds intersect with the Game Camera bounds. Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. Inherited From * [Phaser.Component.AutoCull#inCamera](phaser.component.autocull#inCamera) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L37)) ### input : [Phaser.InputHandler](phaser.inputhandler) | null The Input Handler for this Game Object. By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`. After you have done this, this property will be a reference to the Phaser InputHandler. ##### Type * [Phaser.InputHandler](phaser.inputhandler) | null Inherited From * [Phaser.Component.InputEnabled#input](phaser.component.inputenabled#input) Source code: [gameobjects/components/InputEnabled.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js#L24)) ### inputEnabled : boolean By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created for this Game Object and it will then start to process click / touch events and more. You can then access the Input Handler via `this.input`. Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`. If you set this property to false it will stop the Input Handler from processing any more input events. If you want to *temporarily* disable input for a Game Object, then it's better to set `input.enabled = false`, as it won't reset any of the Input Handlers internal properties. You can then toggle this back on as needed. Inherited From * [Phaser.Component.InputEnabled#inputEnabled](phaser.component.inputenabled#inputEnabled) Source code: [gameobjects/components/InputEnabled.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js#L42)) ### [readonly] inWorld : boolean Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds. Inherited From * [Phaser.Component.InWorld#inWorld](phaser.component.inworld#inWorld) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 129](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L129)) ### key : string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) The key of the image or texture used by this Game Object during rendering. If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. ##### Type * string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) Inherited From * [Phaser.Component.Core#key](phaser.component.core#key) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 203](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L203)) ### left : number The left coordinate of the Game Object. This is the same as `x - offsetX`. Inherited From * [Phaser.Component.Bounds#left](phaser.component.bounds#left) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 102](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L102)) ### lifespan : number The lifespan allows you to give a Game Object a lifespan in milliseconds. Once the Game Object is 'born' you can set this to a positive value. It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. When it reaches zero it will call the `kill` method. Very handy for particles, bullets, collectibles, or any other short-lived entity. Inherited From * [Phaser.Component.LifeSpan#lifespan](phaser.component.lifespan#lifespan) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 65](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L65)) ### maxWidth : number The maximum display width of this BitmapText in pixels. If BitmapText.text is longer than maxWidth then the lines will be automatically wrapped based on the last whitespace character found in the line. If no whitespace was found then no wrapping will take place and consequently the maxWidth value will not be honored. Disable maxWidth by setting the value to 0. The maximum width of this BitmapText in pixels. Source code: [gameobjects/BitmapText.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js) ([Line 648](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js#L648)) ### name : string A user defined name given to this Game Object. This value isn't ever used internally by Phaser, it is meant as a game level property. Inherited From * [Phaser.Component.Core#name](phaser.component.core#name) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 150](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L150)) ### [readonly] offsetX : number The amount the Game Object is visually offset from its x coordinate. This is the same as `width * anchor.x`. It will only be > 0 if anchor.x is not equal to zero. Inherited From * [Phaser.Component.Bounds#offsetX](phaser.component.bounds#offsetX) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L24)) ### [readonly] offsetY : number The amount the Game Object is visually offset from its y coordinate. This is the same as `height * anchor.y`. It will only be > 0 if anchor.y is not equal to zero. Inherited From * [Phaser.Component.Bounds#offsetY](phaser.component.bounds#offsetY) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L42)) ### outOfBoundsKill : boolean If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false. Inherited From * [Phaser.Component.InWorld#outOfBoundsKill](phaser.component.inworld#outOfBoundsKill) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 106](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L106)) ### outOfCameraBoundsKill : boolean If this and the `autoCull` property are both set to `true`, then the `kill` method is called as soon as the Game Object leaves the camera bounds. Inherited From * [Phaser.Component.InWorld#outOfCameraBoundsKill](phaser.component.inworld#outOfCameraBoundsKill) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 115](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L115)) ### pendingDestroy : boolean A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. You can set it directly to allow you to flag an object to be destroyed on its next update. This is extremely useful if you wish to destroy an object from within one of its own callbacks such as with Buttons or other Input events. Inherited From * [Phaser.Component.Core#pendingDestroy](phaser.component.core#pendingDestroy) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 259](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L259)) ### [readonly] physicsType : number The const physics body type of this object. Source code: [gameobjects/BitmapText.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js) ([Line 75](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js#L75)) ### [readonly] previousPosition : [Phaser.Point](phaser.point) The position the Game Object was located in the previous frame. Inherited From * [Phaser.Component.Core#previousPosition](phaser.component.core#previousPosition) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 225](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L225)) ### [readonly] previousRotation : number The rotation the Game Object was in set to in the previous frame. Value is in radians. Inherited From * [Phaser.Component.Core#previousRotation](phaser.component.core#previousRotation) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L232)) ### [readonly] renderOrderID : number The render order ID is used internally by the renderer and Input Manager and should not be modified. This property is mostly used internally by the renderers, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#renderOrderID](phaser.component.core#renderOrderID) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 240](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L240)) ### right : number The right coordinate of the Game Object. This is the same as `x + width - offsetX`. Inherited From * [Phaser.Component.Bounds#right](phaser.component.bounds#right) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L124)) ### smoothed : boolean Enable or disable texture smoothing for this BitmapText. The smoothing is applied to the BaseTexture of this font, which all letters of the text reference. Smoothing is enabled by default. Source code: [gameobjects/BitmapText.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js) ([Line 681](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js#L681)) ### text : string The text to be displayed by this BitmapText object. Source code: [gameobjects/BitmapText.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js) ([Line 626](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js#L626)) ### [readonly] textHeight : number The height in pixels of the overall text area, taking into consideration multi-line text. Source code: [gameobjects/BitmapText.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js#L87)) ### [readonly] textWidth : number The width in pixels of the overall text area, taking into consideration multi-line text. Source code: [gameobjects/BitmapText.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js) ([Line 81](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js#L81)) ### tint : number The tint applied to the BitmapText. This is a hex value. Set to white to disable (0xFFFFFF) Source code: [gameobjects/BitmapText.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js) ([Line 557](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js#L557)) ### top : number The y coordinate of the Game Object. This is the same as `y - offsetY`. Inherited From * [Phaser.Component.Bounds#top](phaser.component.bounds#top) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 146](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L146)) ### [readonly] type : number The const type of this object. Source code: [gameobjects/BitmapText.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js) ([Line 69](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js#L69)) ### width : number The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#width](pixi.displayobjectcontainer#width) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 571](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L571)) ### world : [Phaser.Point](phaser.point) The world coordinates of this Game Object in pixels. Depending on where in the display list this Game Object is placed this value can differ from `position`, which contains the x/y coordinates relative to the Game Objects parent. Inherited From * [Phaser.Component.Core#world](phaser.component.core#world) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 211](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L211)) ### x : number The position of the Game Object on the x axis relative to the local coordinates of the parent. Inherited From * [Phaser.Component.PhysicsBody#x](phaser.component.physicsbody#x) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L98)) ### y : number The position of the Game Object on the y axis relative to the local coordinates of the parent. Inherited From * [Phaser.Component.PhysicsBody#y](phaser.component.physicsbody#y) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L124)) ### [readonly] z : number The z depth of this Game Object within its parent Group. No two objects in a Group can have the same z value. This value is adjusted automatically whenever the Group hierarchy changes. If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. Inherited From * [Phaser.Component.Core#z](phaser.component.core#z) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 177](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L177)) Public Methods -------------- ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### alignIn(container, position, offsetX, offsetY) → {Object} Aligns this Game Object within another Game Object, or Rectangle, known as the 'container', to one of 9 possible positions. The container must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the container. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the container, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `container` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Inherited From * [Phaser.Component.Bounds#alignIn](phaser.component.bounds#alignIn) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 223](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L223)) ### alignTo(parent, position, offsetX, offsetY) → {Object} Aligns this Game Object to the side of another Game Object, or Rectangle, known as the 'parent', in one of 11 possible positions. The parent must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the parent. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the parent, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Inherited From * [Phaser.Component.Bounds#alignTo](phaser.component.bounds#alignTo) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 321](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L321)) ### cleanText(text, replace) → {string} Given a text string this will scan each character in the string to ensure it exists in the BitmapText font data. If it doesn't the character is removed, or replaced with the `replace` argument. If no font data has been loaded at all this returns an empty string, as nothing can be rendered. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `text` | string | | | The text to parse. | | `replace` | string | <optional> | '' | The replacement string for any missing characters. | ##### Returns string - The cleaned text string. Source code: [gameobjects/BitmapText.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js) ([Line 312](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js#L312)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### destroy(destroyChildren, destroyTexture) Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present and nulls its reference to `game`, freeing it up for garbage collection. If this Game Object has the Events component it will also dispatch the `onDestroy` event. You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've more than one Game Object sharing the same BaseTexture. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroyChildren` | boolean | <optional> | true | Should every child of this object have its destroy method called as well? | | `destroyTexture` | boolean | <optional> | false | Destroy the BaseTexture this Game Object is using? Note that if another Game Object is sharing the same BaseTexture it will invalidate it. | Inherited From * [Phaser.Component.Destroy#destroy](phaser.component.destroy#destroy) Source code: [gameobjects/components/Destroy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js#L37)) ### getBounds(targetCoordinateSpace) → {Rectangle} Retrieves the global bounds of the displayObjectContainer as a rectangle. The bounds calculation takes all visible children into consideration. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `targetCoordinateSpace` | PIXIDisplayObject | PIXIMatrix | <optional> | Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object. | ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.DisplayObjectContainer#getBounds](pixi.displayobjectcontainer#getBounds) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 280](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L280)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the displayObjectContainer as a rectangle without any transformations. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.DisplayObjectContainer#getLocalBounds](pixi.displayobjectcontainer#getLocalBounds) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 437](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L437)) ### kill() → {PIXI.DisplayObject} Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false. It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal. Note that killing a Game Object is a way for you to quickly recycle it in an object pool, it doesn't destroy the object or free it up from memory. If you don't need this Game Object any more you should call `destroy` instead. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.LifeSpan#kill](phaser.component.lifespan#kill) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 113](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L113)) ### postUpdate() Automatically called by World.preUpdate. Source code: [gameobjects/BitmapText.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js) ([Line 198](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js#L198)) ### preUpdate() → {boolean} Automatically called by World.preUpdate. ##### Returns boolean - True if the BitmapText was rendered, otherwise false. Source code: [gameobjects/BitmapText.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js) ([Line 187](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js#L187)) ### purgeGlyphs() → {integer} If a BitmapText changes from having a large number of characters to having very few characters it will cause lots of Sprites to be retained in the BitmapText.\_glyphs array. Although they are not attached to the display list they still take up memory while sat in the glyphs pool waiting to be re-used in the future. If you know that the BitmapText will not grow any larger then you can purge out the excess glyphs from the pool by calling this method. Calling this doesn't prevent you from increasing the length of the text again in the future. ##### Returns integer - The amount of glyphs removed from the pool. Source code: [gameobjects/BitmapText.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js) ([Line 477](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js#L477)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### reset(x, y, health) → {PIXI.DisplayObject} Resets the Game Object. This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`, `visible` and `renderable` to true. If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value. If this Game Object has a Physics Body it will reset the Body. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate (in world space) to position the Game Object at. | | `y` | number | | | The y coordinate (in world space) to position the Game Object at. | | `health` | number | <optional> | 1 | The health to give the Game Object if it has the Health component. | ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.Reset#reset](phaser.component.reset#reset) Source code: [gameobjects/components/Reset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Reset.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Reset.js#L30)) ### revive(health) → {PIXI.DisplayObject} Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `health` | number | <optional> | 100 | The health to give the Game Object. Only set if the GameObject has the Health component. | ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.LifeSpan#revive](phaser.component.lifespan#revive) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L78)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### setText(text) The text to be displayed by this BitmapText object. It's faster to use `BitmapText.text = string`, but this is kept for backwards compatibility. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `text` | string | The text to be displayed by this BitmapText object. | Source code: [gameobjects/BitmapText.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js) ([Line 217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapText.js#L217)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) ### update() Override this method in your own custom objects to handle any update requirements. It is called immediately after `preUpdate` and before `postUpdate`. Remember if this Game Object has any children you should call update on those too. Inherited From * [Phaser.Component.Core#update](phaser.component.core#update) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 328](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L328))
programming_docs
phaser Class: Phaser.Easing.Bounce Class: Phaser.Easing.Bounce =========================== Constructor ----------- ### new Bounce() Bounce easing. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 509](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L509)) Public Methods -------------- ### In(k) → {number} Bounce ease-in. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 511](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L511)) ### InOut(k) → {number} Bounce ease-in/out. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 553](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L553)) ### Out(k) → {number} Bounce ease-out. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 524](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L524)) phaser Class: Phaser.ArrayUtils Class: Phaser.ArrayUtils ======================== Constructor ----------- ### new ArrayUtils() Utility functions for dealing with Arrays. Source code: [utils/ArrayUtils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js) ([Line 13](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js#L13)) Public Methods -------------- ### <static> findClosest(value, arr) → {number} Snaps a value to the nearest value in an array. The result will always be in the range `[first_value, last_value]`. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `value` | number | The search value | | `arr` | Array.<number> | The input array which *must* be sorted. | ##### Returns number - The nearest value found. Source code: [utils/ArrayUtils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js) ([Line 172](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js#L172)) ### <static> getRandomItem(objects, startIndex, length) → {object} Fetch a random entry from the given array. Will return null if there are no array items that fall within the specified range or if there is no item for the randomly chosen index. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `objects` | Array.<any> | An array of objects. | | `startIndex` | integer | Optional offset off the front of the array. Default value is 0, or the beginning of the array. | | `length` | integer | Optional restriction on the number of values you want to randomly select from. | ##### Returns object - The random object that was selected. Source code: [utils/ArrayUtils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js) ([Line 27](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js#L27)) ### <static> removeRandomItem(objects, startIndex, length) → {object} Removes a random object from the given array and returns it. Will return null if there are no array items that fall within the specified range or if there is no item for the randomly chosen index. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `objects` | Array.<any> | An array of objects. | | `startIndex` | integer | Optional offset off the front of the array. Default value is 0, or the beginning of the array. | | `length` | integer | Optional restriction on the number of values you want to randomly select from. | ##### Returns object - The random object that was removed. Source code: [utils/ArrayUtils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js#L51)) ### <static> rotate(array) → {any} This method is *deprecated* and should not be used. It may be removed in the future. Moves the element from the start of the array to the end, shifting all items in the process. The "rotation" happens to the left. Before: `[ A, B, C, D, E, F ]` After: `[ B, C, D, E, F, A ]` See also Phaser.ArrayUtils.rotateRight ##### Parameters | Name | Type | Description | | --- | --- | --- | | `array` | Array.<any> | The array to rotate. The array is modified. | ##### Returns any - The rotated value. Deprecated: * Please use Phaser.ArrayUtils.rotate instead. Source code: [utils/ArrayUtils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js) ([Line 239](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js#L239)) ### <static> rotateLeft(array) → {any} Moves the element from the start of the array to the end, shifting all items in the process. The "rotation" happens to the left. Before: `[ A, B, C, D, E, F ]` After: `[ B, C, D, E, F, A ]` See also Phaser.ArrayUtils.rotateRight ##### Parameters | Name | Type | Description | | --- | --- | --- | | `array` | Array.<any> | The array to rotate. The array is modified. | ##### Returns any - The rotated value. Source code: [utils/ArrayUtils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js) ([Line 217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js#L217)) ### <static> rotateMatrix(matrix, direction) → {Array.<Array.<any>>} Rotates the given matrix (array of arrays). Based on the routine from <http://jsfiddle.net/MrPolywhirl/NH42z/>. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `matrix` | Array.<Array.<any>> | The array to rotate; this matrix *may* be altered. | | `direction` | number | string | The amount to rotate: the rotation in degrees (90, -90, 270, -270, 180) or a string command ('rotateLeft', 'rotateRight' or 'rotate180'). | ##### Returns Array.<Array.<any>> - The rotated matrix. The source matrix should be discarded for the returned matrix. Source code: [utils/ArrayUtils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js#L132)) ### <static> rotateRight(array) → {any} Moves the element from the end of the array to the start, shifting all items in the process. The "rotation" happens to the right. Before: `[ A, B, C, D, E, F ]` After: `[ F, A, B, C, D, E ]` See also Phaser.ArrayUtils.rotateLeft. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `array` | Array.<any> | The array to rotate. The array is modified. | ##### Returns any - The shifted value. Source code: [utils/ArrayUtils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js) ([Line 195](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js#L195)) ### <static> shuffle(array) → {Array.<any>} A standard Fisher-Yates Array shuffle implementation which modifies the array in place. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `array` | Array.<any> | The array to shuffle. | ##### Returns Array.<any> - The original array, now shuffled. Source code: [utils/ArrayUtils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js) ([Line 80](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js#L80)) ### <static> transposeMatrix(array) → {Array.<Array.<any>>} Transposes the elements of the given matrix (array of arrays). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `array` | Array.<Array.<any>> | The matrix to transpose. | ##### Returns Array.<Array.<any>> - A new transposed matrix Source code: [utils/ArrayUtils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js) ([Line 101](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js#L101)) ### numberArray(start, end) → {Array.<number>} Create an array representing the inclusive range of numbers (usually integers) in `[start, end]`. This is equivalent to `numberArrayStep(start, end, 1)`. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `start` | number | The minimum value the array starts with. | | `end` | number | The maximum value the array contains. | ##### Returns Array.<number> - The array of number values. Source code: [utils/ArrayUtils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js) ([Line 262](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js#L262)) ### numberArrayStep(start, end, step) → {Array} Create an array of numbers (positive and/or negative) progressing from `start` up to but not including `end` by advancing by `step`. If `start` is less than `end` a zero-length range is created unless a negative `step` is specified. Certain values for `start` and `end` (eg. NaN/undefined/null) are currently coerced to 0; for forward compatibility make sure to pass in actual numbers. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `start` | number | | | The start of the range. | | `end` | number | <optional> | | The end of the range. | | `step` | number | <optional> | 1 | The value to increment or decrement by. | ##### Returns Array - Returns the new array of numbers. Source code: [utils/ArrayUtils.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js) ([Line 284](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/ArrayUtils.js#L284)) ##### Example ``` Phaser.ArrayUtils.numberArrayStep(4); // => [0, 1, 2, 3] Phaser.ArrayUtils.numberArrayStep(1, 5); // => [1, 2, 3, 4] Phaser.ArrayUtils.numberArrayStep(0, 20, 5); // => [0, 5, 10, 15] Phaser.ArrayUtils.numberArrayStep(0, -4, -1); // => [0, -1, -2, -3] Phaser.ArrayUtils.numberArrayStep(1, 4, 0); // => [1, 1, 1] Phaser.ArrayUtils.numberArrayStep(0); // => [] ``` phaser Class: Phaser.Line Class: Phaser.Line ================== Constructor ----------- ### new Line(x1, y1, x2, y2) Creates a new Line object with a start and an end point. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x1` | number | <optional> | 0 | The x coordinate of the start of the line. | | `y1` | number | <optional> | 0 | The y coordinate of the start of the line. | | `x2` | number | <optional> | 0 | The x coordinate of the end of the line. | | `y2` | number | <optional> | 0 | The y coordinate of the end of the line. | Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L17)) Public Properties ----------------- ### [readonly] angle : number Gets the angle of the line in radians. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 372](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L372)) ### [readonly] bottom : number Gets the bottom-most point of this line. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 476](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L476)) ### end : [Phaser.Point](phaser.point) The end point of the line. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 32](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L32)) ### [readonly] height : number Gets the height of this bounds of this line. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 502](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L502)) ### [readonly] left : number Gets the left-most point of this line. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 437](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L437)) ### [readonly] length : number Gets the length of the line segment. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 359](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L359)) ### [readonly] normalAngle : number Gets the angle in radians of the normal of this line (line.angle - 90 degrees.) Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 541](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L541)) ### [readonly] normalX : number Gets the x component of the left-hand normal of this line. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 515](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L515)) ### [readonly] normalY : number Gets the y component of the left-hand normal of this line. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 528](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L528)) ### [readonly] perpSlope : number Gets the perpendicular slope of the line (x/y). Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 398](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L398)) ### [readonly] right : number Gets the right-most point of this line. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 450](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L450)) ### [readonly] slope : number Gets the slope of the line (y/x). Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 385](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L385)) ### start : [Phaser.Point](phaser.point) The start point of the line. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 27](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L27)) ### [readonly] top : number Gets the top-most point of this line. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 463](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L463)) ### [readonly] type : number The const type of this object. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L38)) ### [readonly] width : number Gets the width of this bounds of this line. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 489](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L489)) ### [readonly] x : number Gets the x coordinate of the top left of the bounds around this line. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 411](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L411)) ### [readonly] y : number Gets the y coordinate of the top left of the bounds around this line. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 424](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L424)) Public Methods -------------- ### <static> intersects(a, b, asSegment, result) → {[Phaser.Point](phaser.point)} Checks for intersection between two lines. If asSegment is true it will check for segment intersection. If asSegment is false it will check for line intersection. Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. Adapted from code by Keith Hair ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `a` | [Phaser.Line](phaser.line) | | | The first Line to be checked. | | `b` | [Phaser.Line](phaser.line) | | | The second Line to be checked. | | `asSegment` | boolean | <optional> | true | If true it will check for segment intersection, otherwise full line intersection. | | `result` | [Phaser.Point](phaser.point) | <optional> | | A Point object to store the result in, if not given a new one will be created. | ##### Returns [Phaser.Point](phaser.point) - The intersection segment of the two lines as a Point, or null if there is no intersection. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 610](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L610)) ### <static> intersectsPoints(a, b, e, f, asSegment, result) → {[Phaser.Point](phaser.point)} Checks for intersection between two lines as defined by the given start and end points. If asSegment is true it will check for line segment intersection. If asSegment is false it will check for line intersection. Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. Adapted from code by Keith Hair ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `a` | [Phaser.Point](phaser.point) | | | The start of the first Line to be checked. | | `b` | [Phaser.Point](phaser.point) | | | The end of the first line to be checked. | | `e` | [Phaser.Point](phaser.point) | | | The start of the second Line to be checked. | | `f` | [Phaser.Point](phaser.point) | | | The end of the second line to be checked. | | `asSegment` | boolean | <optional> | true | If true it will check for segment intersection, otherwise full line intersection. | | `result` | [Phaser.Point](phaser.point) | object | <optional> | | A Point object to store the result in, if not given a new one will be created. | ##### Returns [Phaser.Point](phaser.point) - The intersection segment of the two lines as a Point, or null if there is no intersection. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 554](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L554)) ### <static> intersectsRectangle(line, rect) → {boolean} Checks for intersection between the Line and a Rectangle shape, or a rectangle-like object, with public `x`, `y`, `right` and `bottom` properties, such as a Sprite or Body. An intersection is considered valid if: The line starts within, or ends within, the Rectangle. The line segment intersects one of the 4 rectangle edges. The for the purposes of this function rectangles are considered 'solid'. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `line` | [Phaser.Line](phaser.line) | The line to check for intersection with. | | `rect` | [Phaser.Rectangle](phaser.rectangle) | object | The rectangle, or rectangle-like object, to check for intersection with. | ##### Returns boolean - True if the line intersects with the rectangle edges, or starts or ends within the rectangle. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 630](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L630)) ### <static> reflect(a, b) → {number} Returns the reflected angle between two lines. This is the outgoing angle based on the angle of Line 1 and the normalAngle of Line 2. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | [Phaser.Line](phaser.line) | The base line. | | `b` | [Phaser.Line](phaser.line) | The line to be reflected from the base line. | ##### Returns number - The reflected angle in radians. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 722](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L722)) ### centerOn(x, y) → {[Phaser.Line](phaser.line)} Centers this Line on the given coordinates. The line is centered by positioning the start and end points so that the lines midpoint matches the coordinates given. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The x position to center the line on. | | `y` | number | The y position to center the line on. | ##### Returns [Phaser.Line](phaser.line) - This line object Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 200](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L200)) ### clone(output) → {[Phaser.Line](phaser.line)} Returns a new Line object with the same values for the start and end properties as this Line object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `output` | [Phaser.Line](phaser.line) | Optional Line object. If given the values will be set into the object, otherwise a brand new Line object will be created and returned. | ##### Returns [Phaser.Line](phaser.line) - The cloned Line object. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 336](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L336)) ### coordinatesOnLine(stepRate, results) → {array} Using Bresenham's line algorithm this will return an array of all coordinates on this line. The start and end points are rounded before this runs as the algorithm works on integers. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `stepRate` | number | <optional> | 1 | How many steps will we return? 1 = every coordinate on the line, 2 = every other coordinate, etc. | | `results` | array | <optional> | | The array to store the results in. If not provided a new one will be generated. | ##### Returns array - An array of coordinates. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 278](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L278)) ### fromAngle(x, y, angle, length) → {[Phaser.Line](phaser.line)} Sets this line to start at the given `x` and `y` coordinates and for the segment to extend at `angle` for the given `length`. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The x coordinate of the start of the line. | | `y` | number | The y coordinate of the start of the line. | | `angle` | number | The angle of the line in radians. | | `length` | number | The length of the line in pixels. | ##### Returns [Phaser.Line](phaser.line) - This line object Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L86)) ### fromSprite(startSprite, endSprite, useCenter) → {[Phaser.Line](phaser.line)} Sets the line to match the x/y coordinates of the two given sprites. Can optionally be calculated from their center coordinates. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `startSprite` | [Phaser.Sprite](phaser.sprite) | | | The coordinates of this Sprite will be set to the Line.start point. | | `endSprite` | [Phaser.Sprite](phaser.sprite) | | | The coordinates of this Sprite will be set to the Line.start point. | | `useCenter` | boolean | <optional> | false | If true it will use startSprite.center.x, if false startSprite.x. Note that Sprites don't have a center property by default, so only enable if you've over-ridden your Sprite with a custom class. | ##### Returns [Phaser.Line](phaser.line) - This line object Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 63](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L63)) ### intersects(line, asSegment, result) → {[Phaser.Point](phaser.point)} Checks for intersection between this line and another Line. If asSegment is true it will check for segment intersection. If asSegment is false it will check for line intersection. Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `line` | [Phaser.Line](phaser.line) | | | The line to check against this one. | | `asSegment` | boolean | <optional> | true | If true it will check for segment intersection, otherwise full line intersection. | | `result` | [Phaser.Point](phaser.point) | <optional> | | A Point object to store the result in, if not given a new one will be created. | ##### Returns [Phaser.Point](phaser.point) - The intersection segment of the two lines as a Point, or null if there is no intersection. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 151](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L151)) ### midPoint(out) → {[Phaser.Point](phaser.point)} Returns a Point object where the x and y values correspond to the center (or midpoint) of the Line segment. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `out` | [Phaser.Point](phaser.point) | <optional> | A Phaser.Point object into which the result will be populated. If not given a new Point object is created. | ##### Returns [Phaser.Point](phaser.point) - A Phaser.Point object with the x and y values set to the center of the line segment. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 182](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L182)) ### pointOnLine(x, y) → {boolean} Tests if the given coordinates fall on this line. See pointOnSegment to test against just the line segment. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The line to check against this one. | | `y` | number | The line to check against this one. | ##### Returns boolean - True if the point is on the line, false if not. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 224](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L224)) ### pointOnSegment(x, y) → {boolean} Tests if the given coordinates fall on this line and within the segment. See pointOnLine to test against just the line. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The line to check against this one. | | `y` | number | The line to check against this one. | ##### Returns boolean - True if the point is on the line and segment, false if not. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 238](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L238)) ### random(out) → {[Phaser.Point](phaser.point)} Picks a random point from anywhere on the Line segment and returns it. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `out` | [Phaser.Point](phaser.point) | object | <optional> | A Phaser.Point, or any object with public x/y properties, that the values will be set in. If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an object. | ##### Returns [Phaser.Point](phaser.point) - An object containing the random point in its `x` and `y` properties. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 257](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L257)) ### reflect(line) → {number} Returns the reflected angle between two lines. This is the outgoing angle based on the angle of this line and the normalAngle of the given line. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `line` | [Phaser.Line](phaser.line) | The line to reflect off this line. | ##### Returns number - The reflected angle in radians. Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 168](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L168)) ### rotate(angle, asDegrees) → {[Phaser.Line](phaser.line)} Rotates the line by the amount specified in `angle`. Rotation takes place from the center of the line. If you wish to rotate around a different point see Line.rotateAround. If you wish to rotate the ends of the Line then see Line.start.rotate or Line.end.rotate. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `angle` | number | | | The angle in radians (unless asDegrees is true) to rotate the line by. | | `asDegrees` | boolean | <optional> | false | Is the given angle in radians (false) or degrees (true)? | ##### Returns [Phaser.Line](phaser.line) - This line object Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 105](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L105)) ### rotateAround(x, y, angle, asDegrees) → {[Phaser.Line](phaser.line)} Rotates the line by the amount specified in `angle`. Rotation takes place around the coordinates given. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate to offset the rotation from. | | `y` | number | | | The y coordinate to offset the rotation from. | | `angle` | number | | | The angle in radians (unless asDegrees is true) to rotate the line by. | | `asDegrees` | boolean | <optional> | false | Is the given angle in radians (false) or degrees (true)? | ##### Returns [Phaser.Line](phaser.line) - This line object Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 130](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L130)) ### setTo(x1, y1, x2, y2) → {[Phaser.Line](phaser.line)} Sets the components of the Line to the specified values. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x1` | number | <optional> | 0 | The x coordinate of the start of the line. | | `y1` | number | <optional> | 0 | The y coordinate of the start of the line. | | `x2` | number | <optional> | 0 | The x coordinate of the end of the line. | | `y2` | number | <optional> | 0 | The y coordinate of the end of the line. | ##### Returns [Phaser.Line](phaser.line) - This line object Source code: [geom/Line.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js) ([Line 44](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Line.js#L44))
programming_docs
phaser Class: Phaser.Component.LifeSpan Class: Phaser.Component.LifeSpan ================================ Constructor ----------- ### new LifeSpan() LifeSpan Component Features. Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 12](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L12)) Public Properties ----------------- ### alive : boolean A useful flag to control if the Game Object is alive or dead. This is set automatically by the Health components `damage` method should the object run out of health. Or you can toggle it via your game code. This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. Default Value * true Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L50)) ### lifespan : number The lifespan allows you to give a Game Object a lifespan in milliseconds. Once the Game Object is 'born' you can set this to a positive value. It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. When it reaches zero it will call the `kill` method. Very handy for particles, bullets, collectibles, or any other short-lived entity. Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 65](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L65)) Public Methods -------------- ### <static> preUpdate() The LifeSpan component preUpdate handler. Called automatically by the Game Object. Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L20)) ### kill() → {PIXI.DisplayObject} Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false. It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal. Note that killing a Game Object is a way for you to quickly recycle it in an object pool, it doesn't destroy the object or free it up from memory. If you don't need this Game Object any more you should call `destroy` instead. ##### Returns PIXI.DisplayObject - This instance. Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 113](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L113)) ### revive(health) → {PIXI.DisplayObject} Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `health` | number | <optional> | 100 | The health to give the Game Object. Only set if the GameObject has the Health component. | ##### Returns PIXI.DisplayObject - This instance. Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L78)) phaser Class: Phaser.Mouse Class: Phaser.Mouse =================== Constructor ----------- ### new Mouse(game) The Mouse class is responsible for handling all aspects of mouse interaction with the browser. It captures and processes mouse events that happen on the game canvas object. It also adds a single `mouseup` listener to `window` which is used to capture the mouse being released when not over the game. You should not normally access this class directly, but instead use a Phaser.Pointer object which normalises all game input for you, including accurate button handling. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 21](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L21)) Public Properties ----------------- ### [static] BACK\_BUTTON : number Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 190](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L190)) ### [static] FORWARD\_BUTTON : number Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 196](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L196)) ### [static] LEFT\_BUTTON : number Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 172](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L172)) ### [static] MIDDLE\_BUTTON : number Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 178](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L178)) ### [static] NO\_BUTTON : number Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 166](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L166)) ### [static] RIGHT\_BUTTON : number Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 184](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L184)) ### [static] WHEEL\_DOWN : number Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 208](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L208)) ### [static] WHEEL\_UP : number Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 202](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L202)) ### button : number This property was removed in Phaser 2.4 and should no longer be used. Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on. Or Pointer.button holds the DOM event button value if you require that. Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 76](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L76)) ### callbackContext : Object The context under which callbacks are called. Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L37)) ### capture : boolean If true the DOM mouse events will have event.preventDefault applied to them, if false they will propagate fully. Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 67](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L67)) ### enabled : boolean Mouse input will only be processed if enabled. Default Value * true Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 89](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L89)) ### event :MouseEvent | null The browser mouse DOM event. Will be null if no mouse event has ever been received. Access this property only inside a Mouse event handler and do not keep references to it. ##### Type * MouseEvent | null Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 115](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L115)) ### game : [Phaser.Game](phaser.game) A reference to the currently running game. Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L26)) ### <internal> input : [Phaser.Input](phaser.input) A reference to the Phaser Input Manager. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 32](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L32)) ### locked : boolean If the mouse has been Pointer Locked successfully this will be set to true. Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 95](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L95)) ### mouseDownCallback : Function A callback that can be fired when the mouse is pressed down. Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L42)) ### mouseOutCallback : Function A callback that can be fired when the mouse is no longer over the game canvas. Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 52](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L52)) ### mouseOverCallback : Function A callback that can be fired when the mouse enters the game canvas (usually after a mouseout). Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 57](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L57)) ### mouseUpCallback : Function A callback that can be fired when the mouse is released from a pressed down state. Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 47](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L47)) ### mouseWheelCallback : Function A callback that can be fired when the mousewheel is used. Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 62](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L62)) ### pointerLock : [Phaser.Signal](phaser.signal) This event is dispatched when the browser enters or leaves pointer lock state. Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 107](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L107)) ### stopOnGameOut : boolean If true Pointer.stop will be called if the mouse leaves the game canvas. Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 101](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L101)) ### wheelDelta : number The direction of the *last* mousewheel usage 1 for up -1 for down. Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 82](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L82)) Public Methods -------------- ### onMouseDown(event) The internal method that handles the mouse down event from the browser. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | MouseEvent | The native event from the browser. This gets stored in Mouse.event. | Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 296](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L296)) ### onMouseMove(event) The internal method that handles the mouse move event from the browser. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | MouseEvent | The native event from the browser. This gets stored in Mouse.event. | Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 326](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L326)) ### onMouseOut(event) The internal method that handles the mouse out event from the browser. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | MouseEvent | The native event from the browser. This gets stored in Mouse.event. | Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 444](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L444)) ### onMouseOutGlobal(event) The internal method that handles the mouse out event from the window. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | MouseEvent | The native event from the browser. This gets stored in Mouse.event. | Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 408](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L408)) ### onMouseOver(event) The internal method that handles the mouse over event from the browser. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | MouseEvent | The native event from the browser. This gets stored in Mouse.event. | Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 480](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L480)) ### onMouseUp(event) The internal method that handles the mouse up event from the browser. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | MouseEvent | The native event from the browser. This gets stored in Mouse.event. | Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 356](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L356)) ### onMouseUpGlobal(event) The internal method that handles the mouse up event from the window. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | MouseEvent | The native event from the browser. This gets stored in Mouse.event. | Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 386](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L386)) ### onMouseWheel(event) The internal method that handles the mouse wheel event from the browser. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | MouseEvent | The native event from the browser. | Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 504](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L504)) ### pointerLockChange(event) Internal pointerLockChange handler. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | [Event](event) | The native event from the browser. This gets stored in Mouse.event. | Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 562](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L562)) ### releasePointerLock() Internal release pointer lock handler. Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 587](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L587)) ### requestPointerLock() If the browser supports it you can request that the pointer be locked to the browser window. This is classically known as 'FPS controls', where the pointer can't leave the browser until the user presses an exit key. If the browser successfully enters a locked state the event Phaser.Mouse.pointerLock will be dispatched and the first parameter will be 'true'. Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 533](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L533)) ### start() Starts the event listeners running. Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 212](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L212)) ### stop() Stop the event listeners. Source code: [input/Mouse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js) ([Line 603](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Mouse.js#L603)) phaser Class: Phaser.Circle Class: Phaser.Circle ==================== Constructor ----------- ### new Circle(x, y, diameter) Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter. If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | <optional> | 0 | The x coordinate of the center of the circle. | | `y` | number | <optional> | 0 | The y coordinate of the center of the circle. | | `diameter` | number | <optional> | 0 | The diameter of the circle. | Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L17)) Public Properties ----------------- ### [readonly] area : number The area of this Circle. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 412](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L412)) ### bottom : number The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. Gets or sets the bottom of the circle. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 385](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L385)) ### diameter : number The largest distance between any two points on the circle. The same as the radius \* 2. Gets or sets the diameter of the circle. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 258](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L258)) ### empty : boolean Determines whether or not this Circle object is empty. Will return a value of true if the Circle objects diameter is less than or equal to 0; otherwise false. If set to true it will reset all of the Circle objects properties to 0. A Circle object is empty if its diameter is less than or equal to 0. Gets or sets the empty state of the circle. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 435](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L435)) ### left The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 304](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L304)) ### radius : number The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. Gets or sets the radius of the circle. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 281](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L281)) ### right : number The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. Gets or sets the value of the rightmost point of the circle. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 331](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L331)) ### top : number The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. Gets or sets the top of the circle. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 358](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L358)) ### [readonly] type : number The const type of this object. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L54)) ### x : number The x coordinate of the center of the circle. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L26)) ### y : number The y coordinate of the center of the circle. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 31](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L31)) Public Methods -------------- ### <static> circumferencePoint(a, angle, asDegrees, out) → {[Phaser.Point](phaser.point)} Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `a` | [Phaser.Circle](phaser.circle) | | | The first Circle object. | | `angle` | number | | | The angle in radians (unless asDegrees is true) to return the point from. | | `asDegrees` | boolean | <optional> | false | Is the given angle in radians (false) or degrees (true)? | | `out` | [Phaser.Point](phaser.point) | <optional> | | An optional Point object to put the result in to. If none specified a new Point object will be created. | ##### Returns [Phaser.Point](phaser.point) - The Point object holding the result. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 510](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L510)) ### <static> contains(a, x, y) → {boolean} Return true if the given x/y coordinates are within the Circle object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | [Phaser.Circle](phaser.circle) | The Circle to be checked. | | `x` | number | The X value of the coordinate to test. | | `y` | number | The Y value of the coordinate to test. | ##### Returns boolean - True if the coordinates are within this circle, otherwise false. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 458](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L458)) ### <static> equals(a, b) → {boolean} Determines whether the two Circle objects match. This method compares the x, y and diameter properties. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | [Phaser.Circle](phaser.circle) | The first Circle object. | | `b` | [Phaser.Circle](phaser.circle) | The second Circle object. | ##### Returns boolean - A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 483](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L483)) ### <static> intersects(a, b) → {boolean} Determines whether the two Circle objects intersect. This method checks the radius distances between the two Circle objects to see if they intersect. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | [Phaser.Circle](phaser.circle) | The first Circle object. | | `b` | [Phaser.Circle](phaser.circle) | The second Circle object. | ##### Returns boolean - A value of true if the specified object intersects with this Circle object; otherwise false. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 496](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L496)) ### <static> intersectsRectangle(c, r) → {boolean} Checks if the given Circle and Rectangle objects intersect. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `c` | [Phaser.Circle](phaser.circle) | The Circle object to test. | | `r` | [Phaser.Rectangle](phaser.rectangle) | The Rectangle object to test. | ##### Returns boolean - True if the two objects intersect, otherwise false. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 536](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L536)) ### circumference() → {number} The circumference of the circle. ##### Returns number - The circumference of the circle. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 60](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L60)) ### circumferencePoint(angle, asDegrees, out) → {[Phaser.Point](phaser.point)} Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `angle` | number | | | The angle in radians (unless asDegrees is true) to return the point from. | | `asDegrees` | boolean | <optional> | false | Is the given angle in radians (false) or degrees (true)? | | `out` | [Phaser.Point](phaser.point) | <optional> | | An optional Point object to put the result in to. If none specified a new Point object will be created. | ##### Returns [Phaser.Point](phaser.point) - The Point object holding the result. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 205](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L205)) ### clone(output) → {[Phaser.Circle](phaser.circle)} Returns a new Circle object with the same values for the x, y, width, and height properties as this Circle object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `output` | [Phaser.Circle](phaser.circle) | Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned. | ##### Returns [Phaser.Circle](phaser.circle) - The cloned Circle object. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L171)) ### contains(x, y) → {boolean} Return true if the given x/y coordinates are within this Circle object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The X value of the coordinate to test. | | `y` | number | The Y value of the coordinate to test. | ##### Returns boolean - True if the coordinates are within this circle, otherwise false. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 192](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L192)) ### copyFrom(source) → {Circle} Copies the x, y and diameter properties from any given object to this Circle. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `source` | any | The object to copy from. | ##### Returns Circle - This Circle object. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 128](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L128)) ### copyTo(dest) → {object} Copies the x, y and diameter properties from this Circle to any given object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `dest` | any | The object to copy to. | ##### Returns object - This dest object. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 140](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L140)) ### distance(dest, round) → {number} Returns the distance from the center of the Circle object to the given object (can be Circle, Point or anything with x/y properties) ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `dest` | object | | | The target object. Must have visible x and y properties that represent the center of the object. | | `round` | boolean | <optional> | false | Round the distance to the nearest integer. | ##### Returns number - The distance between this Point object and the destination Point object. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 156](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L156)) ### getBounds() → {[Phaser.Rectangle](phaser.rectangle)} Returns the framing rectangle of the circle as a Phaser.Rectangle object. ##### Returns [Phaser.Rectangle](phaser.rectangle) - The bounds of the Circle. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 97](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L97)) ### offset(dx, dy) → {Circle} Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `dx` | number | Moves the x value of the Circle object by this amount. | | `dy` | number | Moves the y value of the Circle object by this amount. | ##### Returns Circle - This Circle object. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 219](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L219)) ### offsetPoint(point) → {Circle} Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `point` | Point | A Point object to use to offset this Circle object (or any valid object with exposed x and y properties). | ##### Returns Circle - This Circle object. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 235](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L235)) ### random(out) → {[Phaser.Point](phaser.point)} Returns a uniformly distributed random point from anywhere within this Circle. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `out` | [Phaser.Point](phaser.point) | object | <optional> | A Phaser.Point, or any object with public x/y properties, that the values will be set in. If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. | ##### Returns [Phaser.Point](phaser.point) - An object containing the random point in its `x` and `y` properties. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 72](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L72)) ### setTo(x, y, diameter) → {Circle} Sets the members of Circle to the specified values. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The x coordinate of the center of the circle. | | `y` | number | The y coordinate of the center of the circle. | | `diameter` | number | The diameter of the circle. | ##### Returns Circle - This circle object. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 109](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L109)) ### toString() → {string} Returns a string representation of this object. ##### Returns string - a string representation of the instance. Source code: [geom/Circle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js) ([Line 245](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Circle.js#L245))
programming_docs
phaser Class: Phaser.Plugin.PathManager Class: Phaser.Plugin.PathManager ================================ Constructor ----------- ### new PathManager(game, parent) PathManager controls a list of Paths and a list of PathFollowers. It is the central control for the majority of the Pathing API. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the current Phaser.Game instance. | | `parent` | [Phaser.PluginManager](phaser.pluginmanager) | The Phaser Plugin Manager which looks after this plugin. | Source code: [plugins/path/PathManagerPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/PathManagerPlugin.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/PathManagerPlugin.js#L17)) Public Methods -------------- ### createPathsFromJSON() create a new Path from JSON data JSON data format: required: "coordinateSystem":, "smoothness":, "loops":, "speed":, "pointList":[ {"x":, "y":}, ... ] optional: "branchFrom": { "path":, "point": }, "joinTo": { "path":, "point": } Source code: [plugins/path/PathManagerPlugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/PathManagerPlugin.js) ([Line 47](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/PathManagerPlugin.js#L47)) phaser Class: global Class: global ============= Constructor ----------- Public Properties ----------------- ### <constant> ANGLE\_DOWN : integer The Angle (in degrees) a Game Object needs to be set to in order to face down. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 339](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L339)) ### <constant> ANGLE\_LEFT : integer The Angle (in degrees) a Game Object needs to be set to in order to face left. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 346](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L346)) ### <constant> ANGLE\_NORTH\_EAST : integer The Angle (in degrees) a Game Object needs to be set to in order to face north east. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 360](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L360)) ### <constant> ANGLE\_NORTH\_WEST : integer The Angle (in degrees) a Game Object needs to be set to in order to face north west. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 367](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L367)) ### <constant> ANGLE\_RIGHT : integer The Angle (in degrees) a Game Object needs to be set to in order to face right. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 353](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L353)) ### <constant> ANGLE\_SOUTH\_EAST : integer The Angle (in degrees) a Game Object needs to be set to in order to face south east. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 374](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L374)) ### <constant> ANGLE\_SOUTH\_WEST : integer The Angle (in degrees) a Game Object needs to be set to in order to face south west. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 381](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L381)) ### <constant> ANGLE\_UP : integer The Angle (in degrees) a Game Object needs to be set to in order to face up. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 332](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L332)) ### <constant> AUTO : integer AUTO renderer - picks between WebGL or Canvas based on device. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 31](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L31)) ### <constant> BITMAPDATA : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 185](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L185)) ### <constant> BITMAPTEXT : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 136](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L136)) ### <constant> blendModes Various blend modes supported by Pixi. IMPORTANT: The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. ##### Properties: | Name | Type | Description | | --- | --- | --- | | `blendModes.NORMAL` | Number | | | `blendModes.ADD` | Number | | | `blendModes.MULTIPLY` | Number | | | `blendModes.SCREEN` | Number | | | `blendModes.OVERLAY` | Number | | | `blendModes.DARKEN` | Number | | | `blendModes.LIGHTEN` | Number | | | `blendModes.COLOR_DODGE` | Number | | | `blendModes.COLOR_BURN` | Number | | | `blendModes.HARD_LIGHT` | Number | | | `blendModes.SOFT_LIGHT` | Number | | | `blendModes.DIFFERENCE` | Number | | | `blendModes.EXCLUSION` | Number | | | `blendModes.HUE` | Number | | | `blendModes.SATURATION` | Number | | | `blendModes.COLOR` | Number | | | `blendModes.LUMINOSITY` | Number | | Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 499](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L499)) ### <constant> BOTTOM\_CENTER : integer A constant representing a bottom-center alignment or position. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 465](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L465)) ### <constant> BOTTOM\_LEFT : integer A constant representing a bottom-left alignment or position. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 458](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L458)) ### <constant> BOTTOM\_RIGHT : integer A constant representing a bottom-right alignment or position. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 472](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L472)) ### <constant> BUTTON : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 101](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L101)) ### <constant> CANVAS : integer Canvas Renderer. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L38)) ### <constant> CANVAS\_FILTER : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 192](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L192)) ### <constant> CENTER : integer A constant representing a center alignment or position. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 430](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L430)) ### <constant> CIRCLE : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 241](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L241)) ### <constant> CREATURE : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 283](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L283)) ### <constant> DOWN : integer Direction constant. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L87)) ### <constant> ELLIPSE : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 206](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L206)) ### <constant> EMITTER : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L171)) ### <constant> GAMES :array An array of Phaser game instances. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L24)) ### <constant> GRAPHICS : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 115](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L115)) ### <constant> GROUP : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 143](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L143)) ### <constant> HEADLESS : integer Headless renderer (not visual output) Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 52](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L52)) ### <constant> HORIZONTAL : integer A horizontal orientation Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 304](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L304)) ### <constant> IMAGE : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 108](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L108)) ### <constant> LANDSCAPE : integer A landscape orientation Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 318](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L318)) ### <constant> LEFT : integer Direction constant. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 66](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L66)) ### <constant> LEFT\_BOTTOM : integer A constant representing a left-bottom alignment or position. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 423](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L423)) ### <constant> LEFT\_CENTER : integer A constant representing a left-center alignment or position. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 416](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L416)) ### <constant> LEFT\_TOP : integer A constant representing a left-top alignment or position. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 409](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L409)) ### <constant> LINE : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 255](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L255)) ### <constant> MATRIX : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 262](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L262)) ### <constant> NONE : integer Direction constant. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 59](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L59)) ### <constant> PENDING\_ATLAS : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 297](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L297)) ### <constant> POINT : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 269](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L269)) ### <constant> POINTER : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 227](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L227)) ### <constant> POLYGON : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 178](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L178)) ### <constant> PORTRAIT : integer A portrait orientation Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 325](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L325)) ### <constant> RECTANGLE : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 248](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L248)) ### <constant> RENDERTEXTURE : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 150](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L150)) ### <constant> RETROFONT : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 220](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L220)) ### <constant> RIGHT : integer Direction constant. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 73](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L73)) ### <constant> RIGHT\_BOTTOM : integer A constant representing a right-bottom alignment or position. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 451](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L451)) ### <constant> RIGHT\_CENTER : integer A constant representing a right-center alignment or position. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 444](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L444)) ### <constant> RIGHT\_TOP : integer A constant representing a right-top alignment or position. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 437](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L437)) ### <constant> ROPE : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 234](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L234)) ### <constant> ROUNDEDRECTANGLE : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 276](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L276)) ### <constant> scaleModes The scale modes that are supported by Pixi. The DEFAULT scale mode affects the default scaling mode of future operations. It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. ##### Properties: | Name | Type | Default | Description | | --- | --- | --- | --- | | `Phaser.scaleModes` | Object | | | | `scaleModes.DEFAULT` | Number | LINEAR | | | `scaleModes.LINEAR` | Number | | Smooth scaling | | `scaleModes.NEAREST` | Number | | Pixelating scaling | Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 532](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L532)) ### <constant> SPRITE : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 94](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L94)) ### <constant> SPRITEBATCH : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L213)) ### <constant> TEXT : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 122](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L122)) ### <constant> TILEMAP : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 157](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L157)) ### <constant> TILEMAPLAYER : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 164](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L164)) ### <constant> TILESPRITE : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 129](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L129)) ### <constant> TOP\_CENTER : integer A constant representing a top-center alignment or position. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 395](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L395)) ### <constant> TOP\_LEFT : integer A constant representing a top-left alignment or position. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 388](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L388)) ### <constant> TOP\_RIGHT : integer A constant representing a top-right alignment or position. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 402](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L402)) ### <constant> UP : integer Direction constant. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 80](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L80)) ### <constant> VERSION : string The Phaser version number. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L17)) ### <constant> VERTICAL : integer A vertical orientation Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 311](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L311)) ### <constant> VIDEO : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 290](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L290)) ### <constant> WEBGL : integer WebGL Renderer. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L45)) ### <constant> WEBGL\_FILTER : integer Game Object type. Source code: [Phaser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js) ([Line 199](https://github.com/photonstorm/phaser/tree/v2.6.2/src/Phaser.js#L199)) Public Methods -------------- ### displayList(displayObject) Call this function from the Dev Tools console. It will scan the display list and output all of the Objects it finds, and their renderOrderIDs. **Note** Requires a browser that supports console.group and console.groupEnd (such as Chrome) ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `displayObject` | Object | <optional> | The displayObject level display object to start from. Defaults to the World. | Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 844](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L844)) ### emit(eventName) → {Boolean} Emit an event to all registered event listeners. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `eventName` | String | The name of the event. | ##### Returns Boolean - Indication if we've emitted an event. Source code: [plugins/path/EventTarget.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js#L54)) ### listeners(eventName) → {Array} Return a list of assigned event listeners. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `eventName` | String | The events that should be listed. | ##### Returns Array - An array of listener functions Source code: [plugins/path/EventTarget.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js) ([Line 41](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js#L41)) ### mixin(object) Mixes in the properties of the EventTarget prototype onto another object ##### Parameters | Name | Type | Description | | --- | --- | --- | | `object` | Object | The obj to mix into | Source code: [plugins/path/EventTarget.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js) ([Line 34](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js#L34)) ### off(eventName, callback) Remove event listeners. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `eventName` | String | The event we want to remove. | | `callback` | function | The listener that we need to find. | Source code: [plugins/path/EventTarget.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js) ([Line 143](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js#L143)) ### on(eventName, callback) Register a new EventListener for the given event. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `eventName` | String | Name of the event. | | `callback` | Functon | fn Callback function. | Source code: [plugins/path/EventTarget.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js) ([Line 107](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js#L107)) ### once(eventName, callback) Add an EventListener that's only called once. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `eventName` | String | Name of the event. | | `callback` | function | Callback function. | Source code: [plugins/path/EventTarget.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js#L124)) ### Phaser.Path#numPoints return {number} The total number of PathPoints in this Path.() The total number of PathPoints in this Path. Source code: [plugins/path/Path.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/Path.js) ([Line 536](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/Path.js#L536)) ### removeAllListeners(eventName) Remove all listeners or only the listeners for the specified event. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `eventName` | String | The event you want to remove all listeners for. | Source code: [plugins/path/EventTarget.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js) ([Line 173](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js#L173)) ### stopImmediatePropagation() Stops the propagation of events to sibling listeners (no longer calls any listeners). Source code: [plugins/path/EventTarget.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js) ([Line 277](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js#L277)) ### stopPropagation() Stops the propagation of events up the scene graph (prevents bubbling). Source code: [plugins/path/EventTarget.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js) ([Line 268](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js#L268)) Type Definitions ---------------- ### DisplayObject A display object is any object that can be rendered in the Phaser/pixi.js scene graph. This includes [Phaser.Group](phaser.group) (groups are display objects!), [Phaser.Sprite](phaser.sprite), [Phaser.Button](phaser.button), [Phaser.Text](phaser.text) as well as PIXI.DisplayObject and all derived types. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2958](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2958))
programming_docs
phaser Class: Phaser.Stage Class: Phaser.Stage =================== Constructor ----------- ### new Stage(game) The Stage controls root level display objects upon which everything is displayed. It also handles browser visibility handling and the pausing due to loss of focus. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | Game reference to the currently running game. | Source code: [core/Stage.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js) ([Line 16](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js#L16)) Extends ------- * [PIXI.DisplayObjectContainer](pixi.displayobjectcontainer) Public Properties ----------------- ### backgroundColor : number | string Gets and sets the background color of the stage. The color can be given as a number: 0xff0000 or a hex string: '#ff0000' ##### Type * number | string Source code: [core/Stage.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js) ([Line 366](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js#L366)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### currentRenderOrderID : number Reset each frame, keeps a count of the total number of objects updated. Source code: [core/Stage.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js) ([Line 65](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js#L65)) ### disableVisibilityChange : boolean By default if the browser tab loses focus the game will pause. You can stop that behavior by setting this property to true. Note that the browser can still elect to pause your game if it wishes to do so, for example swapping to another browser tab. This will cause the RAF callback to halt, effectively pausing your game, even though no in-game pause event is triggered if you enable this property. Source code: [core/Stage.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js) ([Line 40](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js#L40)) ### exists : boolean If exists is true the Stage and all children are updated, otherwise it is skipped. Default Value * true Source code: [core/Stage.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js#L46)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Source code: [core/Stage.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js) ([Line 21](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js#L21)) ### height : number The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#height](pixi.displayobjectcontainer#height) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 600](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L600)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### name : string The name of this object. Default Value * \_stage\_root Source code: [core/Stage.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js#L29)) ### smoothed : boolean Enable or disable texture smoothing for all objects on this Stage. Only works for bitmap/image textures. Smoothing is enabled by default. Set to true to smooth all sprites rendered on this Stage, or false to disable smoothing (great for pixel art) Source code: [core/Stage.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js) ([Line 386](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js#L386)) ### width : number The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#width](pixi.displayobjectcontainer#width) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 571](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L571)) Public Methods -------------- ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### checkVisibility() Starts a page visibility event listener running, or window.onpagehide/onpageshow if not supported by the browser. Also listens for window.onblur and window.onfocus. Source code: [core/Stage.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js) ([Line 221](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js#L221)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### destroy() Destroys the Stage and removes event listeners. Source code: [core/Stage.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js) ([Line 346](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js#L346)) ### getBounds(targetCoordinateSpace) → {Rectangle} Retrieves the global bounds of the displayObjectContainer as a rectangle. The bounds calculation takes all visible children into consideration. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `targetCoordinateSpace` | PIXIDisplayObject | PIXIMatrix | <optional> | Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object. | ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.DisplayObjectContainer#getBounds](pixi.displayobjectcontainer#getBounds) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 280](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L280)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the displayObjectContainer as a rectangle without any transformations. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.DisplayObjectContainer#getLocalBounds](pixi.displayobjectcontainer#getLocalBounds) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 437](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L437)) ### <internal> parseConfig(config) Parses a Game configuration object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `config` | object | The configuration object to parse. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Stage.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js) ([Line 101](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js#L101)) ### postUpdate() This is called automatically before the renderer runs and after the plugins have updated. In postUpdate this is where all the final physics calculations and object positioning happens. The objects are processed in the order of the display list. Source code: [core/Stage.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js) ([Line 173](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js#L173)) ### preUpdate() This is called automatically after the plugins preUpdate and before the State.update. Most objects have preUpdate methods and it's where initial movement and positioning is done. Source code: [core/Stage.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js) ([Line 138](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js#L138)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### setBackgroundColor(color) Sets the background color for the Stage. The color can be given as a hex string (`'#RRGGBB'`), a CSS color string (`'rgb(r,g,b)'`), or a numeric value (`0xRRGGBB`). An alpha channel is *not* supported and will be ignored. If you've set your game to be transparent then calls to setBackgroundColor are ignored. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `color` | number | string | The color of the background. | Source code: [core/Stage.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js) ([Line 319](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js#L319)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) ### update() This is called automatically after the State.update, but before particles or plugins update. Source code: [core/Stage.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js) ([Line 156](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js#L156)) ### updateTransform() Updates the transforms for all objects on the display list. This overrides the Pixi default as we don't need the interactionManager, but do need the game property check. Source code: [core/Stage.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js) ([Line 204](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js#L204)) ### visibilityChange(event) This method is called when the document visibility is changed. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | [Event](event) | Its type will be used to decide whether the game should be paused or not. | Source code: [core/Stage.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js) ([Line 281](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Stage.js#L281)) phaser Class: Phaser.Component.Angle Class: Phaser.Component.Angle ============================= Constructor ----------- ### new Angle() The Angle Component provides access to an `angle` property; the rotation of a Game Object in degrees. Source code: [gameobjects/components/Angle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js) ([Line 12](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js#L12)) Public Properties ----------------- ### angle : number The angle property is the rotation of the Game Object in *degrees* from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90. If you wish to work in radians instead of degrees you can use the property `rotation` instead. Working in radians is slightly faster as it doesn't have to perform any calculations. Source code: [gameobjects/components/Angle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js#L29)) phaser Class: Phaser.Physics.P2.FixtureList Class: Phaser.Physics.P2.FixtureList ==================================== Constructor ----------- ### new FixtureList(list) Allow to access a list of created fixture (coming from Body#addPhaserPolygon) which itself parse the input from PhysicsEditor with the custom phaser exporter. You can access fixtures of a Body by a group index or even by providing a fixture Key. You can set the fixture key and also the group index for a fixture in PhysicsEditor. This gives you the power to create a complex body built of many fixtures and modify them during runtime (to remove parts, set masks, categories & sensor properties) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `list` | Array | A list of fixtures (from Phaser.Physics.P2.Body#addPhaserPolygon) | Source code: [physics/p2/FixtureList.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/FixtureList.js) ([Line 23](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/FixtureList.js#L23)) Public Methods -------------- ### flatten(array) A helper to flatten arrays. This is very useful as the fixtures are nested from time to time due to the way P2 creates and splits polygons. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `array` | array | The array to flatten. Notice: This will happen recursive not shallow. | Source code: [physics/p2/FixtureList.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/FixtureList.js) ([Line 212](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/FixtureList.js#L212)) ### getFixtureByKey(key) Accessor to get either a single fixture by its key. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the fixture. | Source code: [physics/p2/FixtureList.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/FixtureList.js) ([Line 158](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/FixtureList.js#L158)) ### getFixtures(keys) Accessor to get either a list of specified fixtures by key or the whole fixture list ##### Parameters | Name | Type | Description | | --- | --- | --- | | `keys` | array | A list of fixture keys | Source code: [physics/p2/FixtureList.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/FixtureList.js) ([Line 123](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/FixtureList.js#L123)) ### getGroup(groupID) Accessor to get a group of fixtures by its group index. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `groupID` | number | The group index. | Source code: [physics/p2/FixtureList.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/FixtureList.js) ([Line 170](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/FixtureList.js#L170)) ### init() Source code: [physics/p2/FixtureList.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/FixtureList.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/FixtureList.js#L38)) ### parse() Parser for the output of Phaser.Physics.P2.Body#addPhaserPolygon Source code: [physics/p2/FixtureList.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/FixtureList.js) ([Line 182](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/FixtureList.js#L182)) ### setCategory(bit, fixtureKey) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `bit` | number | The bit to set as the collision group. | | `fixtureKey` | string | Only apply to the fixture with the given key. | Source code: [physics/p2/FixtureList.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/FixtureList.js) ([Line 63](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/FixtureList.js#L63)) ### setMask(bit, fixtureKey) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `bit` | number | The bit to set as the collision mask | | `fixtureKey` | string | Only apply to the fixture with the given key | Source code: [physics/p2/FixtureList.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/FixtureList.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/FixtureList.js#L78)) ### setMaterial(material, fixtureKey) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `material` | Object | The contact material for a fixture | | `fixtureKey` | string | Only apply to the fixture with the given key | Source code: [physics/p2/FixtureList.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/FixtureList.js) ([Line 108](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/FixtureList.js#L108)) ### setSensor(value, fixtureKey) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `value` | boolean | sensor true or false | | `fixtureKey` | string | Only apply to the fixture with the given key | Source code: [physics/p2/FixtureList.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/FixtureList.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/FixtureList.js#L93))
programming_docs
phaser Class: Phaser.Image Class: Phaser.Image =================== Constructor ----------- ### new Image(game, x, y, key, frame) An Image is a light-weight object you can use to display anything that doesn't need physics or animation. It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | | A reference to the currently running game. | | `x` | number | <optional> | 0 | The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in. | | `y` | number | <optional> | 0 | The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [PIXI.Texture](pixi.texture) | <optional> | | The texture used by the Image during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Image is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | Source code: [gameobjects/Image.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Image.js) ([Line 36](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Image.js#L36)) Extends ------- * [PIXI.Sprite](pixi.sprite) * [Phaser.Component.Core](phaser.component.core) * [Phaser.Component.Angle](phaser.component.angle) * [Phaser.Component.Animation](phaser.component.animation) * [Phaser.Component.AutoCull](phaser.component.autocull) * [Phaser.Component.Bounds](phaser.component.bounds) * [Phaser.Component.BringToTop](phaser.component.bringtotop) * [Phaser.Component.Crop](phaser.component.crop) * [Phaser.Component.Destroy](phaser.component.destroy) * [Phaser.Component.FixedToCamera](phaser.component.fixedtocamera) * [Phaser.Component.InputEnabled](phaser.component.inputenabled) * [Phaser.Component.LifeSpan](phaser.component.lifespan) * [Phaser.Component.LoadTexture](phaser.component.loadtexture) * [Phaser.Component.Overlap](phaser.component.overlap) * [Phaser.Component.Reset](phaser.component.reset) * [Phaser.Component.ScaleMinMax](phaser.component.scaleminmax) * [Phaser.Component.Smoothed](phaser.component.smoothed) Public Properties ----------------- ### alive : boolean A useful flag to control if the Game Object is alive or dead. This is set automatically by the Health components `damage` method should the object run out of health. Or you can toggle it via your game code. This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. Inherited From * [Phaser.Component.LifeSpan#alive](phaser.component.lifespan#alive) Default Value * true Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L50)) ### anchor :Point The anchor sets the origin point of the texture. The default is 0,0 this means the texture's origin is the top left Setting than anchor to 0.5,0.5 means the textures origin is centered Setting the anchor to 1,1 would mean the textures origin points will be the bottom right corner Inherited From * [PIXI.Sprite#anchor](pixi.sprite#anchor) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L17)) ### angle : number The angle property is the rotation of the Game Object in *degrees* from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90. If you wish to work in radians instead of degrees you can use the property `rotation` instead. Working in radians is slightly faster as it doesn't have to perform any calculations. Inherited From * [Phaser.Component.Angle#angle](phaser.component.angle#angle) Source code: [gameobjects/components/Angle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js#L29)) ### animations : [Phaser.AnimationManager](phaser.animationmanager) If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. Through it you can create, play, pause and stop animations. Inherited From * [Phaser.Component.Core#animations](phaser.component.core#animations) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 193](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L193)) See * [Phaser.AnimationManager](phaser.animationmanager) ### autoCull : boolean A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, or you have tested performance and find it acceptable. Inherited From * [Phaser.Component.AutoCull#autoCull](phaser.component.autocull#autoCull) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L28)) ### blendMode : number The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode. Warning: You cannot have a blend mode and a filter active on the same Sprite. Doing so will render the sprite invisible. Inherited From * [PIXI.Sprite#blendMode](pixi.sprite#blendMode) Default Value * PIXI.blendModes.NORMAL; Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 82](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L82)) ### bottom : number The sum of the y and height properties. This is the same as `y + height - offsetY`. Inherited From * [Phaser.Component.Bounds#bottom](phaser.component.bounds#bottom) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 168](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L168)) ### cameraOffset : [Phaser.Point](phaser.point) The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. Inherited From * [Phaser.Component.FixedToCamera#cameraOffset](phaser.component.fixedtocamera#cameraOffset) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L86)) ### centerX : number The center x coordinate of the Game Object. This is the same as `(x - offsetX) + (width / 2)`. Inherited From * [Phaser.Component.Bounds#centerX](phaser.component.bounds#centerX) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L58)) ### centerY : number The center y coordinate of the Game Object. This is the same as `(y - offsetY) + (height / 2)`. Inherited From * [Phaser.Component.Bounds#centerY](phaser.component.bounds#centerY) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 80](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L80)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### <internal> components : Object The components this Game Object has installed. Inherited From * [Phaser.Component.Core#components](phaser.component.core#components) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 167](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L167)) ### cropRect : [Phaser.Rectangle](phaser.rectangle) The Rectangle used to crop the texture this Game Object uses. Set this property via `crop`. If you modify this property directly you must call `updateCrop` in order to have the change take effect. Inherited From * [Phaser.Component.Crop#cropRect](phaser.component.crop#cropRect) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L24)) ### data : Object An empty Object that belongs to this Game Object. This value isn't ever used internally by Phaser, but may be used by your own code, or by Phaser Plugins, to store data that needs to be associated with the Game Object, without polluting the Game Object directly. Inherited From * [Phaser.Component.Core#data](phaser.component.core#data) Default Value * {} Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 160](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L160)) ### debug : boolean A debug flag designed for use with `Game.enableStep`. Inherited From * [Phaser.Component.Core#debug](phaser.component.core#debug) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 218](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L218)) ### [readonly] destroyPhase : boolean As a Game Object runs through its destroy method this flag is set to true, and can be checked in any sub-systems or plugins it is being destroyed from. Inherited From * [Phaser.Component.Destroy#destroyPhase](phaser.component.destroy#destroyPhase) Source code: [gameobjects/components/Destroy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js#L22)) ### events : [Phaser.Events](phaser.events) All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this Game Object, or any of its components. Inherited From * [Phaser.Component.Core#events](phaser.component.core#events) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 185](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L185)) See * [Phaser.Events](phaser.events) ### exists : boolean Controls if this Sprite is processed by the core Phaser game loops and Group loops. Inherited From * [PIXI.Sprite#exists](pixi.sprite#exists) Default Value * true Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 103](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L103)) ### fixedToCamera : boolean A Game Object that is "fixed" to the camera uses its x/y coordinates as offsets from the top left of the camera during rendering. The values are adjusted at the rendering stage, overriding the Game Objects actual world position. The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times regardless where in the world the camera is. The offsets are stored in the `cameraOffset` property. Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. Inherited From * [Phaser.Component.FixedToCamera#fixedToCamera](phaser.component.fixedtocamera#fixedToCamera) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 56](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L56)) ### frame : integer Gets or sets the current frame index of the texture being used to render this Game Object. To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use, for example: `player.frame = 4`. If the frame index given doesn't exist it will revert to the first frame found in the texture. If you are using a texture atlas then you should use the `frameName` property instead. If you wish to fully replace the texture being used see `loadTexture`. Inherited From * [Phaser.Component.LoadTexture#frame](phaser.component.loadtexture#frame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 254](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L254)) ### frameName : string Gets or sets the current frame name of the texture being used to render this Game Object. To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use, for example: `player.frameName = "idle"`. If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning. If you are using a sprite sheet then you should use the `frame` property instead. If you wish to fully replace the texture being used see `loadTexture`. Inherited From * [Phaser.Component.LoadTexture#frameName](phaser.component.loadtexture#frameName) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 279](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L279)) ### [readonly] fresh : boolean A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. This property is mostly used internally by the physics systems, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#fresh](phaser.component.core#fresh) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 248](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L248)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Inherited From * [Phaser.Component.Core#game](phaser.component.core#game) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 142](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L142)) ### height : number The height of the sprite, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.Sprite#height](pixi.sprite#height) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 144](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L144)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### [readonly] inCamera : boolean Checks if the Game Objects bounds intersect with the Game Camera bounds. Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. Inherited From * [Phaser.Component.AutoCull#inCamera](phaser.component.autocull#inCamera) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L37)) ### input : [Phaser.InputHandler](phaser.inputhandler) | null The Input Handler for this Game Object. By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`. After you have done this, this property will be a reference to the Phaser InputHandler. ##### Type * [Phaser.InputHandler](phaser.inputhandler) | null Inherited From * [Phaser.Component.InputEnabled#input](phaser.component.inputenabled#input) Source code: [gameobjects/components/InputEnabled.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js#L24)) ### inputEnabled : boolean By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created for this Game Object and it will then start to process click / touch events and more. You can then access the Input Handler via `this.input`. Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`. If you set this property to false it will stop the Input Handler from processing any more input events. If you want to *temporarily* disable input for a Game Object, then it's better to set `input.enabled = false`, as it won't reset any of the Input Handlers internal properties. You can then toggle this back on as needed. Inherited From * [Phaser.Component.InputEnabled#inputEnabled](phaser.component.inputenabled#inputEnabled) Source code: [gameobjects/components/InputEnabled.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js#L42)) ### key : string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) The key of the image or texture used by this Game Object during rendering. If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. ##### Type * string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) Inherited From * [Phaser.Component.Core#key](phaser.component.core#key) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 203](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L203)) ### left : number The left coordinate of the Game Object. This is the same as `x - offsetX`. Inherited From * [Phaser.Component.Bounds#left](phaser.component.bounds#left) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 102](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L102)) ### lifespan : number The lifespan allows you to give a Game Object a lifespan in milliseconds. Once the Game Object is 'born' you can set this to a positive value. It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. When it reaches zero it will call the `kill` method. Very handy for particles, bullets, collectibles, or any other short-lived entity. Inherited From * [Phaser.Component.LifeSpan#lifespan](phaser.component.lifespan#lifespan) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 65](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L65)) ### name : string A user defined name given to this Game Object. This value isn't ever used internally by Phaser, it is meant as a game level property. Inherited From * [Phaser.Component.Core#name](phaser.component.core#name) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 150](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L150)) ### [readonly] offsetX : number The amount the Game Object is visually offset from its x coordinate. This is the same as `width * anchor.x`. It will only be > 0 if anchor.x is not equal to zero. Inherited From * [Phaser.Component.Bounds#offsetX](phaser.component.bounds#offsetX) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L24)) ### [readonly] offsetY : number The amount the Game Object is visually offset from its y coordinate. This is the same as `height * anchor.y`. It will only be > 0 if anchor.y is not equal to zero. Inherited From * [Phaser.Component.Bounds#offsetY](phaser.component.bounds#offsetY) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L42)) ### pendingDestroy : boolean A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. You can set it directly to allow you to flag an object to be destroyed on its next update. This is extremely useful if you wish to destroy an object from within one of its own callbacks such as with Buttons or other Input events. Inherited From * [Phaser.Component.Core#pendingDestroy](phaser.component.core#pendingDestroy) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 259](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L259)) ### [readonly] previousPosition : [Phaser.Point](phaser.point) The position the Game Object was located in the previous frame. Inherited From * [Phaser.Component.Core#previousPosition](phaser.component.core#previousPosition) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 225](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L225)) ### [readonly] previousRotation : number The rotation the Game Object was in set to in the previous frame. Value is in radians. Inherited From * [Phaser.Component.Core#previousRotation](phaser.component.core#previousRotation) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L232)) ### [readonly] renderOrderID : number The render order ID is used internally by the renderer and Input Manager and should not be modified. This property is mostly used internally by the renderers, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#renderOrderID](phaser.component.core#renderOrderID) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 240](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L240)) ### right : number The right coordinate of the Game Object. This is the same as `x + width - offsetX`. Inherited From * [Phaser.Component.Bounds#right](phaser.component.bounds#right) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L124)) ### scaleMax : [Phaser.Point](phaser.point) The maximum scale this Game Object will scale up to. It allows you to prevent a parent from scaling this Game Object higher than the given value. Set it to `null` to remove the limit. Inherited From * [Phaser.Component.ScaleMinMax#scaleMax](phaser.component.scaleminmax#scaleMax) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L46)) ### scaleMin : [Phaser.Point](phaser.point) The minimum scale this Game Object will scale down to. It allows you to prevent a parent from scaling this Game Object lower than the given value. Set it to `null` to remove the limit. Inherited From * [Phaser.Component.ScaleMinMax#scaleMin](phaser.component.scaleminmax#scaleMin) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 36](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L36)) ### shader : [PIXI.AbstractFilter](pixi.abstractfilter) The shader that will be used to render this Sprite. Set to null to remove a current shader. Inherited From * [PIXI.Sprite#shader](pixi.sprite#shader) Default Value * null Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L93)) ### smoothed : boolean Enable or disable texture smoothing for this Game Object. It only takes effect if the Game Object is using an image based texture. Smoothing is enabled by default. Inherited From * [Phaser.Component.Smoothed#smoothed](phaser.component.smoothed#smoothed) Source code: [gameobjects/components/Smoothed.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Smoothed.js) ([Line 25](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Smoothed.js#L25)) ### texture : [PIXI.Texture](pixi.texture) The texture that the sprite is using Inherited From * [PIXI.Sprite#texture](pixi.sprite#texture) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L28)) ### tint : number The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. Inherited From * [PIXI.Sprite#tint](pixi.sprite#tint) Default Value * 0xFFFFFF Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L54)) ### tintedTexture :Canvas A canvas that contains the tinted version of the Sprite (in Canvas mode, WebGL doesn't populate this) Inherited From * [PIXI.Sprite#tintedTexture](pixi.sprite#tintedTexture) Default Value * null Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 73](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L73)) ### top : number The y coordinate of the Game Object. This is the same as `y - offsetY`. Inherited From * [Phaser.Component.Bounds#top](phaser.component.bounds#top) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 146](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L146)) ### transformCallback : Function The callback that will apply any scale limiting to the worldTransform. Inherited From * [Phaser.Component.ScaleMinMax#transformCallback](phaser.component.scaleminmax#transformCallback) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L20)) ### transformCallbackContext : Object The context under which `transformCallback` is called. Inherited From * [Phaser.Component.ScaleMinMax#transformCallbackContext](phaser.component.scaleminmax#transformCallbackContext) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L26)) ### [readonly] type : number The const type of this object. Source code: [gameobjects/Image.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Image.js) ([Line 47](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Image.js#L47)) ### width : number The width of the sprite, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.Sprite#width](pixi.sprite#width) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 125](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L125)) ### world : [Phaser.Point](phaser.point) The world coordinates of this Game Object in pixels. Depending on where in the display list this Game Object is placed this value can differ from `position`, which contains the x/y coordinates relative to the Game Objects parent. Inherited From * [Phaser.Component.Core#world](phaser.component.core#world) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 211](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L211)) ### [readonly] z : number The z depth of this Game Object within its parent Group. No two objects in a Group can have the same z value. This value is adjusted automatically whenever the Group hierarchy changes. If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. Inherited From * [Phaser.Component.Core#z](phaser.component.core#z) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 177](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L177)) Public Methods -------------- ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### alignIn(container, position, offsetX, offsetY) → {Object} Aligns this Game Object within another Game Object, or Rectangle, known as the 'container', to one of 9 possible positions. The container must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the container. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the container, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `container` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Inherited From * [Phaser.Component.Bounds#alignIn](phaser.component.bounds#alignIn) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 223](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L223)) ### alignTo(parent, position, offsetX, offsetY) → {Object} Aligns this Game Object to the side of another Game Object, or Rectangle, known as the 'parent', in one of 11 possible positions. The parent must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the parent. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the parent, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Inherited From * [Phaser.Component.Bounds#alignTo](phaser.component.bounds#alignTo) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 321](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L321)) ### bringToTop() → {PIXI.DisplayObject} Brings this Game Object to the top of its parents display list. Visually this means it will render over the top of any old child in the same Group. If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#bringToTop](phaser.component.bringtotop#bringToTop) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L24)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### crop(rect, copy) Crop allows you to crop the texture being used to display this Game Object. Setting a crop rectangle modifies the core texture frame. The Game Object width and height properties will be adjusted accordingly. Cropping takes place from the top-left and can be modified in real-time either by providing an updated rectangle object to this method, or by modifying `cropRect` property directly and then calling `updateCrop`. The rectangle object given to this method can be either a `Phaser.Rectangle` or any other object so long as it has public `x`, `y`, `width`, `height`, `right` and `bottom` properties. A reference to the rectangle is stored in `cropRect` unless the `copy` parameter is `true`, in which case the values are duplicated to a local object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `rect` | [Phaser.Rectangle](phaser.rectangle) | | | The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle. | | `copy` | boolean | <optional> | false | If false `cropRect` will be stored as a reference to the given rect. If true it will copy the rect values into a local Phaser Rectangle object stored in cropRect. | Inherited From * [Phaser.Component.Crop#crop](phaser.component.crop#crop) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L49)) ### destroy(destroyChildren, destroyTexture) Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present and nulls its reference to `game`, freeing it up for garbage collection. If this Game Object has the Events component it will also dispatch the `onDestroy` event. You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've more than one Game Object sharing the same BaseTexture. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroyChildren` | boolean | <optional> | true | Should every child of this object have its destroy method called as well? | | `destroyTexture` | boolean | <optional> | false | Destroy the BaseTexture this Game Object is using? Note that if another Game Object is sharing the same BaseTexture it will invalidate it. | Inherited From * [Phaser.Component.Destroy#destroy](phaser.component.destroy#destroy) Source code: [gameobjects/components/Destroy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js#L37)) ### getBounds(matrix) → {Rectangle} Returns the bounds of the Sprite as a rectangle. The bounds calculation takes the worldTransform into account. It is important to note that the transform is not updated when you call this method. So if this Sprite is the child of a Display Object which has had its transform updated since the last render pass, those changes will not yet have been applied to this Sprites worldTransform. If you need to ensure that all parent transforms are factored into this getBounds operation then you should call `updateTransform` on the root most object in this Sprites display list first. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `matrix` | Matrix | the transformation matrix of the sprite | ##### Returns Rectangle - the framing rectangle Inherited From * [PIXI.Sprite#getBounds](pixi.sprite#getBounds) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 199](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L199)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the Sprite as a rectangle. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.Sprite#getLocalBounds](pixi.sprite#getLocalBounds) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 315](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L315)) ### kill() → {PIXI.DisplayObject} Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false. It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal. Note that killing a Game Object is a way for you to quickly recycle it in an object pool, it doesn't destroy the object or free it up from memory. If you don't need this Game Object any more you should call `destroy` instead. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.LifeSpan#kill](phaser.component.lifespan#kill) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 113](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L113)) ### loadTexture(key, frame, stopAnimation) Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache. If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead. You should only use `loadTexture` if you want to replace the base texture entirely. Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU. You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite. Doing this then sets the key to be the `frame` argument (the frame is set to zero). This allows you to create sprites using `load.image` during development, and then change them to use a Texture Atlas later in development by simply searching your code for 'PENDING\_ATLAS' and swapping it to be the key of the atlas data. Note: You cannot use a RenderTexture as a texture for a TileSprite. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | | `stopAnimation` | boolean | <optional> | true | If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing. | Inherited From * [Phaser.Component.LoadTexture#loadTexture](phaser.component.loadtexture#loadTexture) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L51)) ### moveDown() → {PIXI.DisplayObject} Moves this Game Object down one place in its parents display list. This call has no effect if the Game Object is already at the bottom of the display list. If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#moveDown](phaser.component.bringtotop#moveDown) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L87)) ### moveUp() → {PIXI.DisplayObject} Moves this Game Object up one place in its parents display list. This call has no effect if the Game Object is already at the top of the display list. If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#moveUp](phaser.component.bringtotop#moveUp) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 66](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L66)) ### overlap(displayObject) → {boolean} Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object, which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result. This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result. Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency. It should be fine for low-volume testing where physics isn't required. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `displayObject` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.TileSprite](phaser.tilesprite) | [Phaser.Button](phaser.button) | PIXI.DisplayObject | The display object to check against. | ##### Returns boolean - True if the bounds of this Game Object intersects at any point with the bounds of the given display object. Inherited From * [Phaser.Component.Overlap#overlap](phaser.component.overlap#overlap) Source code: [gameobjects/components/Overlap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Overlap.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Overlap.js#L29)) ### play(name, frameRate, loop, killOnComplete) → {[Phaser.Animation](phaser.animation)} Plays an Animation. The animation should have previously been created via `animations.add`. If the animation is already playing calling this again won't do anything. If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `name` | string | | | The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'. | | `frameRate` | number | <optional> | null | The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. | | `loop` | boolean | <optional> | false | Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. | | `killOnComplete` | boolean | <optional> | false | If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. | ##### Returns [Phaser.Animation](phaser.animation) - A reference to playing Animation. Inherited From * [Phaser.Component.Animation#play](phaser.component.animation#play) Source code: [gameobjects/components/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Animation.js) ([Line 31](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Animation.js#L31)) ### <internal> postUpdate() Internal method called by the World postUpdate cycle. Inherited From * [Phaser.Component.Core#postUpdate](phaser.component.core#postUpdate) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 338](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L338)) ### preUpdate() Automatically called by World.preUpdate. Source code: [gameobjects/Image.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Image.js) ([Line 79](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Image.js#L79)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### reset(x, y, health) → {PIXI.DisplayObject} Resets the Game Object. This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`, `visible` and `renderable` to true. If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value. If this Game Object has a Physics Body it will reset the Body. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate (in world space) to position the Game Object at. | | `y` | number | | | The y coordinate (in world space) to position the Game Object at. | | `health` | number | <optional> | 1 | The health to give the Game Object if it has the Health component. | ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.Reset#reset](phaser.component.reset#reset) Source code: [gameobjects/components/Reset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Reset.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Reset.js#L30)) ### resetFrame() Resets the texture frame dimensions that the Game Object uses for rendering. Inherited From * [Phaser.Component.LoadTexture#resetFrame](phaser.component.loadtexture#resetFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L232)) ### resizeFrame(parent, width, height) Resizes the Frame dimensions that the Game Object uses for rendering. You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData it can be useful to adjust the dimensions directly in this way. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `parent` | object | The parent texture object that caused the resize, i.e. a Phaser.Video object. | | `width` | integer | The new width of the texture. | | `height` | integer | The new height of the texture. | Inherited From * [Phaser.Component.LoadTexture#resizeFrame](phaser.component.loadtexture#resizeFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 220](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L220)) ### revive(health) → {PIXI.DisplayObject} Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `health` | number | <optional> | 100 | The health to give the Game Object. Only set if the GameObject has the Health component. | ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.LifeSpan#revive](phaser.component.lifespan#revive) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L78)) ### sendToBack() → {PIXI.DisplayObject} Sends this Game Object to the bottom of its parents display list. Visually this means it will render below all other children in the same Group. If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#sendToBack](phaser.component.bringtotop#sendToBack) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L45)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### setFrame(frame) Sets the texture frame the Game Object uses for rendering. This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `frame` | [Phaser.Frame](phaser.frame) | The Frame to be used by the texture. | Inherited From * [Phaser.Component.LoadTexture#setFrame](phaser.component.loadtexture#setFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 155](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L155)) ### setScaleMinMax(minX, minY, maxX, maxY) Sets the scaleMin and scaleMax values. These values are used to limit how far this Game Object will scale based on its parent. For example if this Game Object has a `minScale` value of 1 and its parent has a `scale` value of 0.5, the 0.5 will be ignored and the scale value of 1 will be used, as the parents scale is lower than the minimum scale this Game Object should adhere to. By setting these values you can carefully control how Game Objects deal with responsive scaling. If only one parameter is given then that value will be used for both scaleMin and scaleMax: `setScaleMinMax(1)` = scaleMin.x, scaleMin.y, scaleMax.x and scaleMax.y all = 1 If only two parameters are given the first is set as scaleMin.x and y and the second as scaleMax.x and y: `setScaleMinMax(0.5, 2)` = scaleMin.x and y = 0.5 and scaleMax.x and y = 2 If you wish to set `scaleMin` with different values for x and y then either modify Game Object.scaleMin directly, or pass `null` for the `maxX` and `maxY` parameters. Call `setScaleMinMax(null)` to clear all previously set values. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `minX` | number | null | The minimum horizontal scale value this Game Object can scale down to. | | `minY` | number | null | The minimum vertical scale value this Game Object can scale down to. | | `maxX` | number | null | The maximum horizontal scale value this Game Object can scale up to. | | `maxY` | number | null | The maximum vertical scale value this Game Object can scale up to. | Inherited From * [Phaser.Component.ScaleMinMax#setScaleMinMax](phaser.component.scaleminmax#setScaleMinMax) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 110](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L110)) ### setTexture(texture, destroy) Sets the texture of the sprite. Be warned that this doesn't remove or destroy the previous texture this Sprite was using. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `texture` | [PIXI.Texture](pixi.texture) | | | The PIXI texture that is displayed by the sprite | | `destroy` | Boolean | <optional> | false | Call Texture.destroy on the current texture before replacing it with the new one? | Inherited From * [PIXI.Sprite#setTexture](pixi.sprite#setTexture) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 163](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L163)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) ### update() Override this method in your own custom objects to handle any update requirements. It is called immediately after `preUpdate` and before `postUpdate`. Remember if this Game Object has any children you should call update on those too. Inherited From * [Phaser.Component.Core#update](phaser.component.core#update) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 328](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L328)) ### updateCrop() If you have set a crop rectangle on this Game Object via `crop` and since modified the `cropRect` property, or the rectangle it references, then you need to update the crop frame by calling this method. Inherited From * [Phaser.Component.Crop#updateCrop](phaser.component.crop#updateCrop) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L86))
programming_docs
phaser Class: Phaser.RetroFont Class: Phaser.RetroFont ======================= Constructor ----------- ### new RetroFont(game, key, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) A Retro Font is similar to a BitmapFont, in that it uses a texture to render the text. However unlike a BitmapFont every character in a RetroFont is the same size. This makes it similar to a sprite sheet. You typically find font sheets like this from old 8/16-bit games and demos. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | | Current game instance. | | `key` | string | | | The font set graphic set as stored in the Game.Cache. | | `characterWidth` | number | | | The width of each character in the font set. | | `characterHeight` | number | | | The height of each character in the font set. | | `chars` | string | | | The characters used in the font set, in display order. You can use the TEXT\_SET consts for common font set arrangements. | | `charsPerRow` | number | <optional> | | The number of characters per row in the font set. If not given charsPerRow will be the image width / characterWidth. | | `xSpacing` | number | <optional> | 0 | If the characters in the font set have horizontal spacing between them set the required amount here. | | `ySpacing` | number | <optional> | 0 | If the characters in the font set have vertical spacing between them set the required amount here. | | `xOffset` | number | <optional> | 0 | If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. | | `yOffset` | number | <optional> | 0 | If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. | Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 25](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L25)) Extends ------- * [Phaser.RenderTexture](phaser.rendertexture) Public Properties ----------------- ### [static] ALIGN\_CENTER : string Align each line of multi-line text in the center. Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 196](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L196)) ### [static] ALIGN\_LEFT : string Align each line of multi-line text to the left. Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 182](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L182)) ### [static] ALIGN\_RIGHT : string Align each line of multi-line text to the right. Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 189](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L189)) ### [static] TEXT\_SET1 : string Text Set 1 = !"#$%&'()\*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^\_`abcdefghijklmnopqrstuvwxyz{ | }~ Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 203](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L203)) ### [static] TEXT\_SET2 : string Text Set 2 = !"#$%&'()\*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 210](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L210)) ### [static] TEXT\_SET3 : string Text Set 3 = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L217)) ### [static] TEXT\_SET4 : string Text Set 4 = ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 224](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L224)) ### [static] TEXT\_SET5 : string Text Set 5 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-\*:0123456789 Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 231](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L231)) ### [static] TEXT\_SET6 : string Text Set 6 = ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789"(),-.' Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 238](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L238)) ### [static] TEXT\_SET7 : string Text Set 7 = AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW")28FLRX-'39 Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 245](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L245)) ### [static] TEXT\_SET8 : string Text Set 8 = 0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 252](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L252)) ### [static] TEXT\_SET9 : string Text Set 9 = ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'"?! Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 259](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L259)) ### [static] TEXT\_SET10 : string Text Set 10 = ABCDEFGHIJKLMNOPQRSTUVWXYZ Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 266](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L266)) ### [static] TEXT\_SET11 : string Text Set 11 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,"-+!?()':;0123456789 Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 273](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L273)) ### align : string Alignment of the text when multiLine = true or a fixedWidth is set. Set to RetroFont.ALIGN\_LEFT (default), RetroFont.ALIGN\_RIGHT or RetroFont.ALIGN\_CENTER. Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 77](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L77)) ### autoUpperCase : boolean Automatically convert any text to upper case. Lots of old bitmap fonts only contain upper-case characters, so the default is true. Default Value * true Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 89](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L89)) ### baseTexture : [PIXI.BaseTexture](pixi.basetexture) The base texture object that this texture uses Inherited From * [PIXI.RenderTexture#baseTexture](pixi.rendertexture#baseTexture) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L78)) ### characterHeight : number The height of each character in the font set. Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L45)) ### characterPerRow : number The number of characters per row in the font set. Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 60](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L60)) ### characterSpacingX : number If the characters in the font set have horizontal spacing between them set the required amount here. Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L50)) ### characterSpacingY : number If the characters in the font set have vertical spacing between them set the required amount here. Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L55)) ### characterWidth : number The width of each character in the font set. Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 40](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L40)) ### crop :Rectangle This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) Inherited From * [PIXI.RenderTexture#crop](pixi.rendertexture#crop) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 69](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L69)) ### customSpacingX : number Adds horizontal spacing between each character of the font, in pixels. Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 95](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L95)) ### customSpacingY : number Adds vertical spacing between each line of multi-line text, set in pixels. Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 101](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L101)) ### fixedWidth : number If you need this RetroFont image to have a fixed width you can set the width in this value. If text is wider than the width specified it will be cropped off. Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 108](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L108)) ### fontSet :Image A reference to the image stored in the Game.Cache that contains the font. Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 113](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L113)) ### frame :Rectangle The framing rectangle of the render texture Inherited From * [PIXI.RenderTexture#frame](pixi.rendertexture#frame) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 61](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L61)) ### frameData : [Phaser.FrameData](phaser.framedata) The FrameData representing this Retro Font. Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 130](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L130)) ### game : [Phaser.Game](phaser.game) A reference to the currently running game. Inherited From * [Phaser.RenderTexture#game](phaser.rendertexture#game) Source code: [gameobjects/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js#L30)) ### height : number The height of the render texture Inherited From * [PIXI.RenderTexture#height](pixi.rendertexture#height) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L45)) ### isTiling : boolean Is this a tiling texture? As used by the likes of a TilingSprite. Inherited From * [PIXI.Texture#isTiling](pixi.texture#isTiling) Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 79](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L79)) ### key : string The key of the RenderTexture in the Cache, if stored there. Inherited From * [Phaser.RenderTexture#key](phaser.rendertexture#key) Source code: [gameobjects/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js) ([Line 35](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js#L35)) ### multiLine : boolean If set to true all carriage-returns in text will form new lines (see align). If false the font will only contain one single line of text (the default) Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 83](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L83)) ### noFrame : boolean Does this Texture have any frame data assigned to it? Inherited From * [PIXI.Texture#noFrame](pixi.texture#noFrame) Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L28)) ### [readonly] offsetX : number If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 66](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L66)) ### [readonly] offsetY : number If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 72](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L72)) ### renderer : [PIXI.CanvasRenderer](pixi.canvasrenderer) | [PIXI.WebGLRenderer](pixi.webglrenderer) The renderer this RenderTexture uses. A RenderTexture can only belong to one renderer at the moment if its webGL. ##### Type * [PIXI.CanvasRenderer](pixi.canvasrenderer) | [PIXI.WebGLRenderer](pixi.webglrenderer) Inherited From * [PIXI.RenderTexture#renderer](pixi.rendertexture#renderer) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 99](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L99)) ### requiresReTint : boolean This will let a renderer know that a tinted parent has updated its texture. Inherited From * [PIXI.Texture#requiresReTint](pixi.texture#requiresReTint) Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 95](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L95)) ### requiresUpdate : boolean This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) Inherited From * [PIXI.Texture#requiresUpdate](pixi.texture#requiresUpdate) Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L87)) ### resolution : number The Resolution of the texture. Inherited From * [PIXI.RenderTexture#resolution](pixi.rendertexture#resolution) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 53](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L53)) ### smoothed : boolean Sets if the stamp is smoothed or not. Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 585](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L585)) ### [readonly] stamp : [Phaser.Image](phaser.image) The image that is stamped to the RenderTexture for each character in the font. Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 163](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L163)) ### text : string Set this value to update the text in this sprite. Carriage returns are automatically stripped out if multiLine is false. Text is converted to upper case if autoUpperCase is true. Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 547](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L547)) ### trim :Rectangle The texture trim data. Inherited From * [PIXI.Texture#trim](pixi.texture#trim) Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 63](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L63)) ### type : number Base Phaser object type. Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 170](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L170)) ### valid : boolean Inherited From * [PIXI.RenderTexture#valid](pixi.rendertexture#valid) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 125](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L125)) ### width : number The with of the render texture Inherited From * [PIXI.RenderTexture#width](pixi.rendertexture#width) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L37)) Public Methods -------------- ### buildRetroFontText() Updates the texture with the new text. Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 328](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L328)) ### clear() Clears the RenderTexture. Inherited From * [PIXI.RenderTexture#clear](pixi.rendertexture#clear) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 175](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L175)) ### destroy(destroyBase) Destroys this texture ##### Parameters | Name | Type | Description | | --- | --- | --- | | `destroyBase` | Boolean | Whether to destroy the base texture as well | Inherited From * [PIXI.Texture#destroy](pixi.texture#destroy) Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 165](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L165)) ### getBase64() → {String} Will return a base64 encoded string of this texture. It works by calling RenderTexture.getCanvas and then running toDataURL on that. ##### Returns String - A base64 encoded string of the texture. Inherited From * [PIXI.RenderTexture#getBase64](pixi.rendertexture#getBase64) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 309](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L309)) ### getCanvas() → {HTMLCanvasElement} Creates a Canvas element, renders this RenderTexture to it and then returns it. ##### Returns HTMLCanvasElement - A Canvas element with the texture rendered on. Inherited From * [PIXI.RenderTexture#getCanvas](pixi.rendertexture#getCanvas) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 320](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L320)) ### getImage() → {Image} Will return a HTML Image of the texture ##### Returns Image - Inherited From * [PIXI.RenderTexture#getImage](pixi.rendertexture#getImage) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 296](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L296)) ### getLongestLine() → {number} Works out the longest line of text in \_text and returns its length ##### Returns number - The length of the longest line of text. Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 459](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L459)) ### pasteLine(line, x, y, customSpacingX) Internal function that takes a single line of text (2nd parameter) and pastes it into the BitmapData at the given coordinates. Used by getLine and getMultiLine ##### Parameters | Name | Type | Description | | --- | --- | --- | | `line` | string | The single line of text to paste. | | `x` | number | The x coordinate. | | `y` | number | The y coordinate. | | `customSpacingX` | number | Custom X spacing. | Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 420](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L420)) ### <internal> removeUnsupportedCharacters(stripCR) → {string} Internal helper function that removes all unsupported characters from the \_text String, leaving only characters contained in the font set. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `stripCR` | boolean | <optional> | true | Should it strip carriage returns as well? | ##### Returns string - A clean version of the string. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 486](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L486)) ### render(displayObject, matrix, clear) This function will draw the display object to the RenderTexture. In versions of Phaser prior to 2.4.0 the second parameter was a Phaser.Point object. This is now a Matrix allowing you much more control over how the Display Object is rendered. If you need to replicate the earlier behavior please use Phaser.RenderTexture.renderXY instead. If you wish for the displayObject to be rendered taking its current scale, rotation and translation into account then either pass `null`, leave it undefined or pass `displayObject.worldTransform` as the matrix value. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `displayObject` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Group](phaser.group) | | | The display object to render to this texture. | | `matrix` | [Phaser.Matrix](phaser.matrix) | <optional> | | Optional matrix to apply to the display object before rendering. If null or undefined it will use the worldTransform matrix of the given display object. | | `clear` | boolean | <optional> | false | If true the texture will be cleared before the display object is drawn. | Inherited From * [Phaser.RenderTexture#render](phaser.rendertexture#render) Source code: [gameobjects/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js) ([Line 117](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js#L117)) ### renderRawXY(displayObject, x, y, clear) This function will draw the display object to the RenderTexture at the given coordinates. When the display object is drawn it doesn't take into account scale, rotation or translation. If you need those then use RenderTexture.renderXY instead. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `displayObject` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Group](phaser.group) | | | The display object to render to this texture. | | `x` | number | | | The x position to render the object at. | | `y` | number | | | The y position to render the object at. | | `clear` | boolean | <optional> | false | If true the texture will be cleared before the display object is drawn. | Inherited From * [Phaser.RenderTexture#renderRawXY](phaser.rendertexture#renderRawXY) Source code: [gameobjects/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js) ([Line 89](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js#L89)) ### renderXY(displayObject, x, y, clear) This function will draw the display object to the RenderTexture at the given coordinates. When the display object is drawn it takes into account scale and rotation. If you don't want those then use RenderTexture.renderRawXY instead. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `displayObject` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Group](phaser.group) | | | The display object to render to this texture. | | `x` | number | | | The x position to render the object at. | | `y` | number | | | The y position to render the object at. | | `clear` | boolean | <optional> | false | If true the texture will be cleared before the display object is drawn. | Inherited From * [Phaser.RenderTexture#renderXY](phaser.rendertexture#renderXY) Source code: [gameobjects/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js) ([Line 57](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js#L57)) ### resize(width, height, updateBase) Resizes the RenderTexture. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `width` | Number | The width to resize to. | | `height` | Number | The height to resize to. | | `updateBase` | Boolean | Should the baseTexture.width and height values be resized as well? | Inherited From * [PIXI.RenderTexture#resize](pixi.rendertexture#resize) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 139](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L139)) ### setFixedWidth(width, lineAlignment) If you need this RetroFont to have a fixed width and custom alignment you can set the width here. If text is wider than the width specified it will be cropped off. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `width` | number | | | Width in pixels of this RetroFont. Set to zero to disable and re-enable automatic resizing. | | `lineAlignment` | string | <optional> | 'left' | Align the text within this width. Set to RetroFont.ALIGN\_LEFT (default), RetroFont.ALIGN\_RIGHT or RetroFont.ALIGN\_CENTER. | Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 275](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L275)) ### setFrame(frame) Specifies the region of the baseTexture that this texture will use. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `frame` | Rectangle | The frame of the texture to set it to | Inherited From * [PIXI.Texture#setFrame](pixi.texture#setFrame) Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 178](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L178)) ### setText(content, multiLine, characterSpacing, lineSpacing, lineAlignment, allowLowerCase) A helper function that quickly sets lots of variables at once, and then updates the text. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `content` | string | | | The text of this sprite. | | `multiLine` | boolean | <optional> | false | Set to true if you want to support carriage-returns in the text and create a multi-line sprite instead of a single line. | | `characterSpacing` | number | <optional> | 0 | To add horizontal spacing between each character specify the amount in pixels. | | `lineSpacing` | number | <optional> | 0 | To add vertical spacing between each line of text, set the amount in pixels. | | `lineAlignment` | string | <optional> | 'left' | Align each line of multi-line text. Set to RetroFont.ALIGN\_LEFT, RetroFont.ALIGN\_RIGHT or RetroFont.ALIGN\_CENTER. | | `allowLowerCase` | boolean | <optional> | false | Lots of bitmap font sets only include upper-case characters, if yours needs to support lower case then set this to true. | Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 293](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L293)) ### updateOffset(xOffset, yOffset) Updates the x and/or y offset that the font is rendered from. This updates all of the texture frames, so be careful how often it is called. Note that the values given for the x and y properties are either ADDED to or SUBTRACTED from (if negative) the existing offsetX/Y values of the characters. So if the current offsetY is 8 and you want it to start rendering from y16 you would call updateOffset(0, 8) to add 8 to the current y offset. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `xOffset` | number | <optional> | 0 | If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. | | `yOffset` | number | <optional> | 0 | If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. | Source code: [gameobjects/RetroFont.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js) ([Line 514](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RetroFont.js#L514))
programming_docs
phaser Class: Phaser.Physics.P2 Class: Phaser.Physics.P2 ======================== Constructor ----------- ### new P2(game, config) This is your main access to the P2 Physics World. From here you can create materials, listen for events and add bodies into the physics simulation. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | Reference to the current game instance. | | `config` | object | <optional> | Physics configuration object passed in from the game constructor. | Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L20)) Classes ------- [Body](phaser.physics.p2.body) [BodyDebug](phaser.physics.p2.bodydebug) [CollisionGroup](phaser.physics.p2.collisiongroup) [ContactMaterial](phaser.physics.p2.contactmaterial) [DistanceConstraint](phaser.physics.p2.distanceconstraint) [FixtureList](phaser.physics.p2.fixturelist) [GearConstraint](phaser.physics.p2.gearconstraint) [InversePointProxy](phaser.physics.p2.inversepointproxy) [LockConstraint](phaser.physics.p2.lockconstraint) [Material](phaser.physics.p2.material) [PointProxy](phaser.physics.p2.pointproxy) [PrismaticConstraint](phaser.physics.p2.prismaticconstraint) [RevoluteConstraint](phaser.physics.p2.revoluteconstraint) [RotationalSpring](phaser.physics.p2.rotationalspring) [Spring](phaser.physics.p2.spring) Public Properties ----------------- ### applyDamping : boolean Enable to automatically apply body damping each step. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1919](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1919)) ### applyGravity : boolean Enable to automatically apply gravity each step. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1939](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1939)) ### applySpringForces : boolean Enable to automatically apply spring forces each step. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1899](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1899)) ### boundsCollidesWith :array An array of the bodies the world bounds collides with. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L232)) ### boundsCollisionGroup : [Phaser.Physics.P2.CollisionGroup](phaser.physics.p2.collisiongroup) A default collision group. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 222](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L222)) ### callbackContext : Object The context under which the callbacks are fired. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 170](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L170)) ### collisionGroups :array An array containing the collision groups that have been defined in the World. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 212](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L212)) ### <internal> config : Object The p2 World configuration object. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 48](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L48)) ### contactMaterial :p2.ContactMaterial The default Contact Material being used by the World. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1879](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1879)) ### emitImpactEvent : boolean Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1994](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1994)) ### everythingCollisionGroup : [Phaser.Physics.P2.CollisionGroup](phaser.physics.p2.collisiongroup) A default collision group. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 227](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L227)) ### frameRate : number The frame rate the world will be stepped at. Defaults to 1 / 60, but you can change here. Also see useElapsedTime property. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 60](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L60)) ### friction : number Friction between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1839](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1839)) ### game : [Phaser.Game](phaser.game) Local reference to game. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 25](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L25)) ### gravity : [Phaser.Physics.P2.InversePointProxy](phaser.physics.p2.inversepointproxy) The gravity applied to all bodies each step. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 83](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L83)) ### <internal> materials :array.<[Phaser.Physics.P2.Material](phaser.physics.p2.material)> A local array of all created Materials. ##### Type * array.<[Phaser.Physics.P2.Material](phaser.physics.p2.material)> Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L78)) ### nothingCollisionGroup : [Phaser.Physics.P2.CollisionGroup](phaser.physics.p2.collisiongroup) A default collision group. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L217)) ### onBeginContact : [Phaser.Signal](phaser.signal) This Signal is dispatched when a first contact is created between two bodies. This happens *before* the step has been done. It sends 5 arguments: `bodyA`, `bodyB`, `shapeA`, `shapeB` and `contactEquations`. It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this in your own code to avoid processing potentially null physics bodies. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 182](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L182)) ### onBodyAdded : [Phaser.Signal](phaser.signal) This signal is dispatched when a new Body is added to the World. It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was added to the world. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 97](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L97)) ### onBodyRemoved : [Phaser.Signal](phaser.signal) This signal is dispatched when a Body is removed to the World. It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was removed from the world. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 106](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L106)) ### onConstraintAdded : [Phaser.Signal](phaser.signal) This signal is dispatched when a Constraint is added to the World. It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was added to the world. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 133](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L133)) ### onConstraintRemoved : [Phaser.Signal](phaser.signal) This signal is dispatched when a Constraint is removed from the World. It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was removed from the world. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 142](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L142)) ### onContactMaterialAdded : [Phaser.Signal](phaser.signal) This signal is dispatched when a Contact Material is added to the World. It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was added to the world. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 151](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L151)) ### onContactMaterialRemoved : [Phaser.Signal](phaser.signal) This signal is dispatched when a Contact Material is removed from the World. It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was removed from the world. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 160](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L160)) ### onEndContact : [Phaser.Signal](phaser.signal) This Signal is dispatched when final contact occurs between two bodies. This happens *before* the step has been done. It sends 4 arguments: `bodyA`, `bodyB`, `shapeA` and `shapeB`. It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this in your own code to avoid processing potentially null physics bodies. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 194](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L194)) ### onSpringAdded : [Phaser.Signal](phaser.signal) This signal is dispatched when a Spring is added to the World. It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was added to the world. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 115](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L115)) ### onSpringRemoved : [Phaser.Signal](phaser.signal) This signal is dispatched when a Spring is removed from the World. It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was removed from the world. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L124)) ### paused : boolean The paused state of the P2 World. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 72](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L72)) ### postBroadphaseCallback : Function A postBroadphase callback. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 165](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L165)) ### restitution : number Default coefficient of restitution between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1859](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1859)) ### sleepMode : number How to deactivate bodies during simulation. Possible modes are: World.NO\_SLEEPING, World.BODY\_SLEEPING and World.ISLAND\_SLEEPING. If sleeping is enabled, you might need to wake up the bodies if they fall asleep when they shouldn't. If you want to enable sleeping in the world, but want to disable it for a particular body, see Body.allowSleep. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 2014](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L2014)) ### solveConstraints : boolean Enable/disable constraint solving in each step. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1959](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1959)) ### [readonly] time : boolean The World time. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1979](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1979)) ### [readonly] total : number The total number of bodies in the world. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 2036](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L2036)) ### useElapsedTime : boolean If true the frameRate value will be ignored and instead p2 will step with the value of Game.Time.physicsElapsed, which is a delta time value. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 66](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L66)) ### walls : Object An object containing the 4 wall bodies that bound the physics world. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 88](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L88)) ### <internal> world :p2.World The p2 World in which the simulation is run. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L54)) Public Methods -------------- ### addBody(body) → {boolean} Add a body to the world. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `body` | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | The Body to add to the World. | ##### Returns boolean - True if the Body was added successfully, otherwise false. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 887](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L887)) ### addConstraint(constraint) → {Phaser.Physics.P2.Constraint} Adds a Constraint to the world. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `constraint` | Phaser.Physics.P2.Constraint | The Constraint to add to the World. | ##### Returns Phaser.Physics.P2.Constraint - The Constraint that was added. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1119](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1119)) ### addContactMaterial(material) → {[Phaser.Physics.P2.ContactMaterial](phaser.physics.p2.contactmaterial)} Adds a Contact Material to the world. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `material` | [Phaser.Physics.P2.ContactMaterial](phaser.physics.p2.contactmaterial) | The Contact Material to be added to the World. | ##### Returns [Phaser.Physics.P2.ContactMaterial](phaser.physics.p2.contactmaterial) - The Contact Material that was added. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1153)) ### addSpring(spring) → {[Phaser.Physics.P2.Spring](phaser.physics.p2.spring)} Adds a Spring to the world. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `spring` | [Phaser.Physics.P2.Spring](phaser.physics.p2.spring) | p2.LinearSpring | p2.RotationalSpring | The Spring to add to the World. | ##### Returns [Phaser.Physics.P2.Spring](phaser.physics.p2.spring) - The Spring that was added. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 931](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L931)) ### beginContactHandler(event) Handles a p2 begin contact event. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | object | The event data. | Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 502](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L502)) ### clear() Clears all bodies from the simulation, resets callbacks and resets the collision bitmask. The P2 world is also cleared: * Removes all solver equations * Removes all constraints * Removes all bodies * Removes all springs * Removes all contact materials This is called automatically when you switch state. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 800](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L800)) ### clearTilemapLayerBodies(map, layer) Clears all physics bodies from the given TilemapLayer that were created with `World.convertTilemap`. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `map` | [Phaser.Tilemap](phaser.tilemap) | | The Tilemap to get the map data from. | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | The layer to operate on. If not given will default to map.currentLayer. | Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1666](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1666)) ### convertCollisionObjects(map, layer, addToWorld) → {array} Converts all of the polylines objects inside a Tiled ObjectGroup into physics bodies that are added to the world. Note that the polylines must be created in such a way that they can withstand polygon decomposition. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `map` | [Phaser.Tilemap](phaser.tilemap) | | | The Tilemap to get the map data from. | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | | The layer to operate on. If not given will default to map.currentLayer. | | `addToWorld` | boolean | <optional> | true | If true it will automatically add each body to the world. | ##### Returns array - An array of the Phaser.Physics.Body objects that have been created. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1625](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1625)) ### convertTilemap(map, layer, addToWorld, optimize) → {array} Goes through all tiles in the given Tilemap and TilemapLayer and converts those set to collide into physics bodies. Only call this *after* you have specified all of the tiles you wish to collide with calls like Tilemap.setCollisionBetween, etc. Every time you call this method it will destroy any previously created bodies and remove them from the world. Therefore understand it's a very expensive operation and not to be done in a core game update loop. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `map` | [Phaser.Tilemap](phaser.tilemap) | | | The Tilemap to get the map data from. | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | | The layer to operate on. If not given will default to map.currentLayer. | | `addToWorld` | boolean | <optional> | true | If true it will automatically add each body to the world, otherwise it's up to you to do so. | | `optimize` | boolean | <optional> | true | If true adjacent colliding tiles will be combined into a single body to save processing. However it means you cannot perform specific Tile to Body collision responses. | ##### Returns array - An array of the Phaser.Physics.P2.Body objects that were created. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1688](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1688)) ### createBody(x, y, mass, addToWorld, options, points) → {[Phaser.Physics.P2.Body](phaser.physics.p2.body)} Creates a new Body and adds it to the World. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate of Body. | | `y` | number | | | The y coordinate of Body. | | `mass` | number | | | The mass of the Body. A mass of 0 means a 'static' Body is created. | | `addToWorld` | boolean | <optional> | false | Automatically add this Body to the world? (usually false as it won't have any shapes on construction). | | `options` | object | | | An object containing the build options: Properties | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `optimalDecomp` | boolean | <optional> | false | Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. | | `skipSimpleCheck` | boolean | <optional> | false | Set to true if you already know that the path is not intersecting itself. | | `removeCollinearPoints` | boolean | number | <optional> | false | Set to a number (angle threshold value) to remove collinear points, or false to keep all points. | | | `points` | Array.<number> | number | | | An array of 2d vectors that form the convex or concave polygon. Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. | ##### Returns [Phaser.Physics.P2.Body](phaser.physics.p2.body) - The body Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1542](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1542)) ### createCollisionGroup(object) Creates a new Collision Group and optionally applies it to the given object. Collision Groups are handled using bitmasks, therefore you have a fixed limit you can create before you need to re-use older groups. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `object` | [Phaser.Group](phaser.group) | [Phaser.Sprite](phaser.sprite) | <optional> | An optional Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. | Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1411](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1411)) ### createContactMaterial(materialA, materialB, options) → {[Phaser.Physics.P2.ContactMaterial](phaser.physics.p2.contactmaterial)} Creates a Contact Material from the two given Materials. You can then edit the properties of the Contact Material directly. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `materialA` | [Phaser.Physics.P2.Material](phaser.physics.p2.material) | <optional> | The first Material to create the ContactMaterial from. If undefined it will create a new Material object first. | | `materialB` | [Phaser.Physics.P2.Material](phaser.physics.p2.material) | <optional> | The second Material to create the ContactMaterial from. If undefined it will create a new Material object first. | | `options` | object | <optional> | Material options object. | ##### Returns [Phaser.Physics.P2.ContactMaterial](phaser.physics.p2.contactmaterial) - The Contact Material that was created. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1246](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1246)) ### createDistanceConstraint(bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce) → {[Phaser.Physics.P2.DistanceConstraint](phaser.physics.p2.distanceconstraint)} Creates a constraint that tries to keep the distance between two bodies constant. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `bodyA` | [Phaser.Sprite](phaser.sprite) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | First connected body. | | `bodyB` | [Phaser.Sprite](phaser.sprite) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | Second connected body. | | `distance` | number | | The distance to keep between the bodies. | | `localAnchorA` | Array | <optional> | The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0]. | | `localAnchorB` | Array | <optional> | The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0]. | | `maxForce` | number | <optional> | The maximum force that should be applied to constrain the bodies. | ##### Returns [Phaser.Physics.P2.DistanceConstraint](phaser.physics.p2.distanceconstraint) - The constraint Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 979](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L979)) ### createGearConstraint(bodyA, bodyB, angle, ratio) → {[Phaser.Physics.P2.GearConstraint](phaser.physics.p2.gearconstraint)} Creates a constraint that tries to keep the distance between two bodies constant. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `bodyA` | [Phaser.Sprite](phaser.sprite) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | First connected body. | | `bodyB` | [Phaser.Sprite](phaser.sprite) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | Second connected body. | | `angle` | number | <optional> | 0 | The relative angle | | `ratio` | number | <optional> | 1 | The gear ratio. | ##### Returns [Phaser.Physics.P2.GearConstraint](phaser.physics.p2.gearconstraint) - The constraint Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1007](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1007)) ### createLockConstraint(bodyA, bodyB, offset, angle, maxForce) → {[Phaser.Physics.P2.LockConstraint](phaser.physics.p2.lockconstraint)} Locks the relative position between two bodies. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `bodyA` | [Phaser.Sprite](phaser.sprite) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | First connected body. | | `bodyB` | [Phaser.Sprite](phaser.sprite) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | Second connected body. | | `offset` | Array | <optional> | | The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. | | `angle` | number | <optional> | 0 | The angle of bodyB in bodyA's frame. | | `maxForce` | number | <optional> | | The maximum force that should be applied to constrain the bodies. | ##### Returns [Phaser.Physics.P2.LockConstraint](phaser.physics.p2.lockconstraint) - The constraint Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1062](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1062)) ### createMaterial(name, body) → {[Phaser.Physics.P2.Material](phaser.physics.p2.material)} Creates a Material. Materials are applied to Shapes owned by a Body and can be set with Body.setMaterial(). Materials are a way to control what happens when Shapes collide. Combine unique Materials together to create Contact Materials. Contact Materials have properties such as friction and restitution that allow for fine-grained collision control between different Materials. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `name` | string | <optional> | Optional name of the Material. Each Material has a unique ID but string names are handy for debugging. | | `body` | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | <optional> | Optional Body. If given it will assign the newly created Material to the Body shapes. | ##### Returns [Phaser.Physics.P2.Material](phaser.physics.p2.material) - The Material that was created. This is also stored in Phaser.Physics.P2.materials. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1219](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1219)) ### createParticle(x, y, mass, addToWorld, options, points) Creates a new Particle and adds it to the World. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate of Body. | | `y` | number | | | The y coordinate of Body. | | `mass` | number | | | The mass of the Body. A mass of 0 means a 'static' Body is created. | | `addToWorld` | boolean | <optional> | false | Automatically add this Body to the world? (usually false as it won't have any shapes on construction). | | `options` | object | | | An object containing the build options: Properties | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `optimalDecomp` | boolean | <optional> | false | Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. | | `skipSimpleCheck` | boolean | <optional> | false | Set to true if you already know that the path is not intersecting itself. | | `removeCollinearPoints` | boolean | number | <optional> | false | Set to a number (angle threshold value) to remove collinear points, or false to keep all points. | | | `points` | Array.<number> | number | | | An array of 2d vectors that form the convex or concave polygon. Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. | Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1584](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1584)) ### createPrismaticConstraint(bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) → {[Phaser.Physics.P2.PrismaticConstraint](phaser.physics.p2.prismaticconstraint)} Constraint that only allows bodies to move along a line, relative to each other. See http://www.iforce2d.net/b2dtut/joints-prismatic ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `bodyA` | [Phaser.Sprite](phaser.sprite) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | First connected body. | | `bodyB` | [Phaser.Sprite](phaser.sprite) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | Second connected body. | | `lockRotation` | boolean | <optional> | true | If set to false, bodyB will be free to rotate around its anchor point. | | `anchorA` | Array | <optional> | | Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. | | `anchorB` | Array | <optional> | | Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. | | `axis` | Array | <optional> | | An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. | | `maxForce` | number | <optional> | | The maximum force that should be applied to constrain the bodies. | ##### Returns [Phaser.Physics.P2.PrismaticConstraint](phaser.physics.p2.prismaticconstraint) - The constraint Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1089](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1089)) ### createRevoluteConstraint(bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) → {[Phaser.Physics.P2.RevoluteConstraint](phaser.physics.p2.revoluteconstraint)} Connects two bodies at given offset points, letting them rotate relative to each other around this point. The pivot points are given in world (pixel) coordinates. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `bodyA` | [Phaser.Sprite](phaser.sprite) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | First connected body. | | `pivotA` | Array | | | The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. | | `bodyB` | [Phaser.Sprite](phaser.sprite) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | Second connected body. | | `pivotB` | Array | | | The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. | | `maxForce` | number | <optional> | 0 | The maximum force that should be applied to constrain the bodies. | | `worldPivot` | Float32Array | <optional> | null | A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. | ##### Returns [Phaser.Physics.P2.RevoluteConstraint](phaser.physics.p2.revoluteconstraint) - The constraint Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1033](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1033)) ### createRotationalSpring(bodyA, bodyB, restAngle, stiffness, damping) → {[Phaser.Physics.P2.RotationalSpring](phaser.physics.p2.rotationalspring)} Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `bodyA` | [Phaser.Sprite](phaser.sprite) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | First connected body. | | `bodyB` | [Phaser.Sprite](phaser.sprite) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | Second connected body. | | `restAngle` | number | <optional> | | The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. | | `stiffness` | number | <optional> | 100 | Stiffness of the spring. A number >= 0. | | `damping` | number | <optional> | 1 | Damping of the spring. A number >= 0. | ##### Returns [Phaser.Physics.P2.RotationalSpring](phaser.physics.p2.rotationalspring) - The spring Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1515](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1515)) ### createSpring(bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) → {[Phaser.Physics.P2.Spring](phaser.physics.p2.spring)} Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `bodyA` | [Phaser.Sprite](phaser.sprite) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | First connected body. | | `bodyB` | [Phaser.Sprite](phaser.sprite) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | Second connected body. | | `restLength` | number | <optional> | 1 | Rest length of the spring. A number > 0. | | `stiffness` | number | <optional> | 100 | Stiffness of the spring. A number >= 0. | | `damping` | number | <optional> | 1 | Damping of the spring. A number >= 0. | | `worldA` | Array | <optional> | | Where to hook the spring to body A in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. | | `worldB` | Array | <optional> | | Where to hook the spring to body B in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. | | `localA` | Array | <optional> | | Where to hook the spring to body A in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. | | `localB` | Array | <optional> | | Where to hook the spring to body B in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. | ##### Returns [Phaser.Physics.P2.Spring](phaser.physics.p2.spring) - The spring Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1484](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1484)) ### destroy() Clears all bodies from the simulation and unlinks World from Game. Should only be called on game shutdown. Call `clear` on a State change. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 874](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L874)) ### enable(object, debug, children) This will create a P2 Physics body on the given game object or array of game objects. A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. Note: When the game object is enabled for P2 physics it has its anchor x/y set to 0.5 so it becomes centered. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `object` | object | array | [Phaser.Group](phaser.group) | | | The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. | | `debug` | boolean | <optional> | false | Create a debug object to go with this body? | | `children` | boolean | <optional> | true | Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. | Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 313](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L313)) ### enableBody(object, debug) Creates a P2 Physics body on the given game object. A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `object` | object | The game object to create the physics body on. A body will only be created if this object has a null `body` property. | | `debug` | boolean | Create a debug object to go with this body? | Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 372](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L372)) ### endContactHandler(event) Handles a p2 end contact event. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | object | The event data. | Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 527](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L527)) ### getBodies() → {array.<[Phaser.Physics.P2.Body](phaser.physics.p2.body)>} Populates and returns an array with references to of all current Bodies in the world. ##### Returns array.<[Phaser.Physics.P2.Body](phaser.physics.p2.body)> - An array containing all current Bodies in the world. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1266](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1266)) ### getBody(object) → {[p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html)} Checks the given object to see if it has a p2.Body and if so returns it. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `object` | object | The object to check for a p2.Body on. | ##### Returns [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) - The p2.Body, or null if not found. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1286](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1286)) ### getConstraints() → {array.<Phaser.Physics.P2.Constraint>} Populates and returns an array of all current Constraints in the world. You will get an array of p2 constraints back. This can be of mixed types, for example the array may contain PrismaticConstraints, RevoluteConstraints or any other valid p2 constraint type. ##### Returns array.<Phaser.Physics.P2.Constraint> - An array containing all current Constraints in the world. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1335](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1335)) ### getContactMaterial(materialA, materialB) → {[Phaser.Physics.P2.ContactMaterial](phaser.physics.p2.contactmaterial) | boolean} Gets a Contact Material based on the two given Materials. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `materialA` | [Phaser.Physics.P2.Material](phaser.physics.p2.material) | The first Material to search for. | | `materialB` | [Phaser.Physics.P2.Material](phaser.physics.p2.material) | The second Material to search for. | ##### Returns [Phaser.Physics.P2.ContactMaterial](phaser.physics.p2.contactmaterial) | boolean - The Contact Material or false if none was found matching the Materials given. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1187](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1187)) ### getSprings() → {array.<[Phaser.Physics.P2.Spring](phaser.physics.p2.spring)>} Populates and returns an array of all current Springs in the world. ##### Returns array.<[Phaser.Physics.P2.Spring](phaser.physics.p2.spring)> - An array containing all current Springs in the world. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1315](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1315)) ### hitTest(worldPoint, bodies, precision, filterStatic) → {Array} Test if a world point overlaps bodies. You will get an array of actual P2 bodies back. You can find out which Sprite a Body belongs to (if any) by checking the Body.parent.sprite property. Body.parent is a Phaser.Physics.P2.Body property. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `worldPoint` | [Phaser.Point](phaser.point) | | | Point to use for intersection tests. The points values must be in world (pixel) coordinates. | | `bodies` | Array.<([Phaser.Physics.P2.Body](phaser.physics.p2.body) | [Phaser.Sprite](phaser.sprite) | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html))> | <optional> | | A list of objects to check for intersection. If not given it will check Phaser.Physics.P2.world.bodies (i.e. all world bodies) | | `precision` | number | <optional> | 5 | Used for matching against particles and lines. Adds some margin to these infinitesimal objects. | | `filterStatic` | boolean | <optional> | false | If true all Static objects will be removed from the results array. | ##### Returns Array - Array of bodies that overlap the point. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1357](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1357)) ### mpx(v) → {number} Convert p2 physics value (meters) to pixel scale. By default Phaser uses a scale of 20px per meter. If you need to modify this you can over-ride these functions via the Physics Configuration object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `v` | number | The value to convert. | ##### Returns number - The scaled value. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1777](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1777)) ### mpxi(v) → {number} Convert p2 physics value (meters) to pixel scale and inverses it. By default Phaser uses a scale of 20px per meter. If you need to modify this you can over-ride these functions via the Physics Configuration object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `v` | number | The value to convert. | ##### Returns number - The scaled value. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1807](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1807)) ### pause() Pauses the P2 World independent of the game pause state. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 733](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L733)) ### preUpdate() Called at the start of the core update loop. Purges flagged bodies from the world. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 295](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L295)) ### pxm(v) → {number} Convert pixel value to p2 physics scale (meters). By default Phaser uses a scale of 20px per meter. If you need to modify this you can over-ride these functions via the Physics Configuration object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `v` | number | The value to convert. | ##### Returns number - The scaled value. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1792](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1792)) ### pxmi(v) → {number} Convert pixel value to p2 physics scale (meters) and inverses it. By default Phaser uses a scale of 20px per meter. If you need to modify this you can over-ride these functions via the Physics Configuration object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `v` | number | The value to convert. | ##### Returns number - The scaled value. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1822](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1822)) ### removeBody(body) → {[Phaser.Physics.P2.Body](phaser.physics.p2.body)} Removes a body from the world. This will silently fail if the body wasn't part of the world to begin with. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `body` | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | The Body to remove from the World. | ##### Returns [Phaser.Physics.P2.Body](phaser.physics.p2.body) - The Body that was removed. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 911](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L911)) ### removeBodyNextStep(body) This will add a P2 Physics body into the removal list for the next step. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `body` | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | The body to remove at the start of the next step. | Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 283](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L283)) ### removeConstraint(constraint) → {Phaser.Physics.P2.Constraint} Removes a Constraint from the world. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `constraint` | Phaser.Physics.P2.Constraint | The Constraint to be removed from the World. | ##### Returns Phaser.Physics.P2.Constraint - The Constraint that was removed. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1136](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1136)) ### removeContactMaterial(material) → {[Phaser.Physics.P2.ContactMaterial](phaser.physics.p2.contactmaterial)} Removes a Contact Material from the world. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `material` | [Phaser.Physics.P2.ContactMaterial](phaser.physics.p2.contactmaterial) | The Contact Material to be removed from the World. | ##### Returns [Phaser.Physics.P2.ContactMaterial](phaser.physics.p2.contactmaterial) - The Contact Material that was removed. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1170](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1170)) ### removeSpring(spring) → {[Phaser.Physics.P2.Spring](phaser.physics.p2.spring)} Removes a Spring from the world. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `spring` | [Phaser.Physics.P2.Spring](phaser.physics.p2.spring) | The Spring to remove from the World. | ##### Returns [Phaser.Physics.P2.Spring](phaser.physics.p2.spring) - The Spring that was removed. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 955](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L955)) ### reset() Called by Phaser.Physics when a State swap occurs. Starts the begin and end Contact listeners again. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 779](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L779)) ### resume() Resumes a paused P2 World. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 744](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L744)) ### setBounds(x, y, width, height, left, right, top, bottom, setCollisionGroup) Sets the bounds of the Physics world to match the given world pixel dimensions. You can optionally set which 'walls' to create: left, right, top or bottom. If none of the walls are given it will default to use the walls settings it had previously. I.e. if you previously told it to not have the left or right walls, and you then adjust the world size the newly created bounds will also not have the left and right walls. Explicitly state them in the parameters to override this. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate of the top-left corner of the bounds. | | `y` | number | | | The y coordinate of the top-left corner of the bounds. | | `width` | number | | | The width of the bounds. | | `height` | number | | | The height of the bounds. | | `left` | boolean | <optional> | true | If true will create the left bounds wall. | | `right` | boolean | <optional> | true | If true will create the right bounds wall. | | `top` | boolean | <optional> | true | If true will create the top bounds wall. | | `bottom` | boolean | <optional> | true | If true will create the bottom bounds wall. | | `setCollisionGroup` | boolean | <optional> | true | If true the Bounds will be set to use its own Collision Group. | Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 646](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L646)) ### setImpactEvents(state) Impact event handling is disabled by default. Enable it before any impact events will be dispatched. In a busy world hundreds of impact events can be generated every step, so only enable this if you cannot do what you need via beginContact or collision masks. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `state` | boolean | Set to true to enable impact events, or false to disable. | Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 393](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L393)) ### setMaterial(material, bodies) Sets the given Material against all Shapes owned by all the Bodies in the given array. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `material` | [Phaser.Physics.P2.Material](phaser.physics.p2.material) | The Material to be applied to the given Bodies. | | `bodies` | array.<[Phaser.Physics.P2.Body](phaser.physics.p2.body)> | An Array of Body objects that the given Material will be set on. | Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1201](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1201)) ### setPostBroadphaseCallback(callback, context) Sets a callback to be fired after the Broadphase has collected collision pairs in the world. Just because a pair exists it doesn't mean they *will* collide, just that they potentially could do. If your calback returns `false` the pair will be removed from the narrowphase. This will stop them testing for collision this step. Returning `true` from the callback will ensure they are checked in the narrowphase. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `callback` | function | The callback that will receive the postBroadphase event data. It must return a boolean. Set to null to disable an existing callback. | | `context` | object | The context under which the callback will be fired. | Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 413](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L413)) ### toJSON() → {object} Converts the current world into a JSON object. ##### Returns object - A JSON representation of the world. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 1399](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L1399)) ### update() Internal P2 update loop. Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 755](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L755)) ### updateBoundsCollisionGroup(setCollisionGroup) By default the World will be set to collide everything with everything. The bounds of the world is a Body with 4 shapes, one for each face. If you start to use your own collision groups then your objects will no longer collide with the bounds. To fix this you need to adjust the bounds to use its own collision group first BEFORE changing your Sprites collision group. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `setCollisionGroup` | boolean | <optional> | true | If true the Bounds will be set to use its own Collision Group. | Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 608](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L608))
programming_docs
phaser Class: Phaser.Easing.Circular Class: Phaser.Easing.Circular ============================= Constructor ----------- ### new Circular() Circular easing. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 344](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L344)) Public Methods -------------- ### In(k) → {number} Circular ease-in. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 346](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L346)) ### InOut(k) → {number} Circular ease-in/out. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 372](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L372)) ### Out(k) → {number} Circular ease-out. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 359](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L359)) phaser Class: PIXI.WebGLBlendModeManager Class: PIXI.WebGLBlendModeManager ================================= Constructor ----------- ### new WebGLBlendModeManager(gl) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `gl` | WebGLContext | the current WebGL drawing context | Source code: [pixi/renderers/webgl/utils/WebGLBlendModeManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLBlendModeManager.js) ([Line 5](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLBlendModeManager.js#L5)) Public Properties ----------------- ### currentBlendMode : number Source code: [pixi/renderers/webgl/utils/WebGLBlendModeManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLBlendModeManager.js) ([Line 12](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLBlendModeManager.js#L12)) Public Methods -------------- ### destroy() Destroys this object. Source code: [pixi/renderers/webgl/utils/WebGLBlendModeManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLBlendModeManager.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLBlendModeManager.js#L54)) ### setBlendMode(blendMode) Sets-up the given blendMode from WebGL's point of view. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `blendMode` | Number | the blendMode, should be a Pixi const, such as PIXI.BlendModes.ADD | Source code: [pixi/renderers/webgl/utils/WebGLBlendModeManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLBlendModeManager.js) ([Line 32](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLBlendModeManager.js#L32)) ### setContext(gl) Sets the WebGL Context. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `gl` | WebGLContext | the current WebGL drawing context | Source code: [pixi/renderers/webgl/utils/WebGLBlendModeManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLBlendModeManager.js) ([Line 21](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLBlendModeManager.js#L21)) phaser Class: Phaser.Easing.Quintic Class: Phaser.Easing.Quintic ============================ Constructor ----------- ### new Quintic() Quintic easing. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 190](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L190)) Public Methods -------------- ### In(k) → {number} Quintic ease-in. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 192](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L192)) ### InOut(k) → {number} Quintic ease-in/out. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 218](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L218)) ### Out(k) → {number} Quintic ease-out. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 205](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L205)) phaser Class: Phaser.Plugin Class: Phaser.Plugin ==================== Constructor ----------- ### new Plugin(game, parent) This is a base Plugin template to use for any Phaser plugin development. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | | `parent` | any | The object that owns this plugin, usually Phaser.PluginManager. | Source code: [core/Plugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js) ([Line 15](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js#L15)) Classes ------- [PathManager](phaser.plugin.pathmanager) Public Properties ----------------- ### active : boolean A Plugin with active=true has its preUpdate and update methods called by the parent, otherwise they are skipped. Source code: [core/Plugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js) ([Line 33](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js#L33)) ### game : [Phaser.Game](phaser.game) A reference to the currently running game. Source code: [core/Plugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js#L22)) ### hasPostRender : boolean A flag to indicate if this plugin has a postRender method. Source code: [core/Plugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js) ([Line 69](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js#L69)) ### hasPostUpdate : boolean A flag to indicate if this plugin has a postUpdate method. Source code: [core/Plugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js) ([Line 57](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js#L57)) ### hasPreUpdate : boolean A flag to indicate if this plugin has a preUpdate method. Source code: [core/Plugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js#L45)) ### hasRender : boolean A flag to indicate if this plugin has a render method. Source code: [core/Plugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js) ([Line 63](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js#L63)) ### hasUpdate : boolean A flag to indicate if this plugin has an update method. Source code: [core/Plugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js#L51)) ### parent :any The parent of this plugin. If added to the PluginManager the parent will be set to that, otherwise it will be null. Source code: [core/Plugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js) ([Line 27](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js#L27)) ### visible : boolean A Plugin with visible=true has its render and postRender methods called by the parent, otherwise they are skipped. Source code: [core/Plugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js) ([Line 39](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js#L39)) Public Methods -------------- ### destroy() Clear down this Plugin and null out references Source code: [core/Plugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js) ([Line 107](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js#L107)) ### postRender() Post-render is called after the Game Renderer and State.render have run. It is only called if visible is set to true. Source code: [core/Plugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js) ([Line 99](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js#L99)) ### preUpdate() Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). It is only called if active is set to true. Source code: [core/Plugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js) ([Line 75](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js#L75)) ### render() Render is called right after the Game Renderer completes, but before the State.render. It is only called if visible is set to true. Source code: [core/Plugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js) ([Line 91](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js#L91)) ### update() Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. It is only called if active is set to true. Source code: [core/Plugin.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js) ([Line 83](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Plugin.js#L83)) phaser Class: Phaser.Bullet Class: Phaser.Bullet ==================== Constructor ----------- ### new Bullet(game, x, y, key, frame) Create a new `Bullet` object. Bullets are used by the `Phaser.Weapon` class, and are normal Sprites, with a few extra properties in the data object to handle Weapon specific features. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | | `x` | number | The x coordinate (in world space) to position the Particle at. | | `y` | number | The y coordinate (in world space) to position the Particle at. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [PIXI.Texture](pixi.texture) | This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. | | `frame` | string | number | If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | Source code: [plugins/weapon/Bullet.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/Bullet.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/Bullet.js#L20)) Extends ------- * [Phaser.Sprite](phaser.sprite) Public Properties ----------------- ### alive : boolean A useful flag to control if the Game Object is alive or dead. This is set automatically by the Health components `damage` method should the object run out of health. Or you can toggle it via your game code. This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. Inherited From * [Phaser.Component.LifeSpan#alive](phaser.component.lifespan#alive) Default Value * true Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L50)) ### anchor :Point The anchor sets the origin point of the texture. The default is 0,0 this means the texture's origin is the top left Setting than anchor to 0.5,0.5 means the textures origin is centered Setting the anchor to 1,1 would mean the textures origin points will be the bottom right corner Inherited From * [PIXI.Sprite#anchor](pixi.sprite#anchor) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L17)) ### angle : number The angle property is the rotation of the Game Object in *degrees* from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90. If you wish to work in radians instead of degrees you can use the property `rotation` instead. Working in radians is slightly faster as it doesn't have to perform any calculations. Inherited From * [Phaser.Component.Angle#angle](phaser.component.angle#angle) Source code: [gameobjects/components/Angle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js#L29)) ### animations : [Phaser.AnimationManager](phaser.animationmanager) If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. Through it you can create, play, pause and stop animations. Inherited From * [Phaser.Component.Core#animations](phaser.component.core#animations) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 193](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L193)) See * [Phaser.AnimationManager](phaser.animationmanager) ### autoCull : boolean A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, or you have tested performance and find it acceptable. Inherited From * [Phaser.Component.AutoCull#autoCull](phaser.component.autocull#autoCull) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L28)) ### blendMode : number The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode. Warning: You cannot have a blend mode and a filter active on the same Sprite. Doing so will render the sprite invisible. Inherited From * [PIXI.Sprite#blendMode](pixi.sprite#blendMode) Default Value * PIXI.blendModes.NORMAL; Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 82](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L82)) ### body : [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | null `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated properties and methods via it. By default Game Objects won't add themselves to any physics system and their `body` property will be `null`. To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`. You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group. Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5, so the physics body is centered on the Game Object. If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics. ##### Type * [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | null Inherited From * [Phaser.Component.PhysicsBody#body](phaser.component.physicsbody#body) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 91](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L91)) ### bottom : number The sum of the y and height properties. This is the same as `y + height - offsetY`. Inherited From * [Phaser.Component.Bounds#bottom](phaser.component.bounds#bottom) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 168](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L168)) ### cameraOffset : [Phaser.Point](phaser.point) The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. Inherited From * [Phaser.Component.FixedToCamera#cameraOffset](phaser.component.fixedtocamera#cameraOffset) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L86)) ### centerX : number The center x coordinate of the Game Object. This is the same as `(x - offsetX) + (width / 2)`. Inherited From * [Phaser.Component.Bounds#centerX](phaser.component.bounds#centerX) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L58)) ### centerY : number The center y coordinate of the Game Object. This is the same as `(y - offsetY) + (height / 2)`. Inherited From * [Phaser.Component.Bounds#centerY](phaser.component.bounds#centerY) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 80](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L80)) ### checkWorldBounds : boolean If this is set to `true` the Game Object checks if it is within the World bounds each frame. When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event. If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event. It also optionally kills the Game Object if `outOfBoundsKill` is `true`. When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame. This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, or you have tested performance and find it acceptable. Inherited From * [Phaser.Component.InWorld#checkWorldBounds](phaser.component.inworld#checkWorldBounds) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L98)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### <internal> components : Object The components this Game Object has installed. Inherited From * [Phaser.Component.Core#components](phaser.component.core#components) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 167](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L167)) ### cropRect : [Phaser.Rectangle](phaser.rectangle) The Rectangle used to crop the texture this Game Object uses. Set this property via `crop`. If you modify this property directly you must call `updateCrop` in order to have the change take effect. Inherited From * [Phaser.Component.Crop#cropRect](phaser.component.crop#cropRect) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L24)) ### damage Damages the Game Object. This removes the given amount of health from the `health` property. If health is taken below or is equal to zero then the `kill` method is called. Inherited From * [Phaser.Component.Health#damage](phaser.component.health#damage) Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L46)) ### data : Object An empty Object that belongs to this Game Object. This value isn't ever used internally by Phaser, but may be used by your own code, or by Phaser Plugins, to store data that needs to be associated with the Game Object, without polluting the Game Object directly. Inherited From * [Phaser.Component.Core#data](phaser.component.core#data) Default Value * {} Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 160](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L160)) ### debug : boolean A debug flag designed for use with `Game.enableStep`. Inherited From * [Phaser.Component.Core#debug](phaser.component.core#debug) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 218](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L218)) ### [readonly] deltaX : number Returns the delta x value. The difference between world.x now and in the previous frame. The value will be positive if the Game Object has moved to the right or negative if to the left. Inherited From * [Phaser.Component.Delta#deltaX](phaser.component.delta#deltaX) Source code: [gameobjects/components/Delta.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js#L24)) ### [readonly] deltaY : number Returns the delta y value. The difference between world.y now and in the previous frame. The value will be positive if the Game Object has moved down or negative if up. Inherited From * [Phaser.Component.Delta#deltaY](phaser.component.delta#deltaY) Source code: [gameobjects/components/Delta.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js#L42)) ### [readonly] deltaZ : number Returns the delta z value. The difference between rotation now and in the previous frame. The delta value. Inherited From * [Phaser.Component.Delta#deltaZ](phaser.component.delta#deltaZ) Source code: [gameobjects/components/Delta.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js#L58)) ### [readonly] destroyPhase : boolean As a Game Object runs through its destroy method this flag is set to true, and can be checked in any sub-systems or plugins it is being destroyed from. Inherited From * [Phaser.Component.Destroy#destroyPhase](phaser.component.destroy#destroyPhase) Source code: [gameobjects/components/Destroy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js#L22)) ### events : [Phaser.Events](phaser.events) All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this Game Object, or any of its components. Inherited From * [Phaser.Component.Core#events](phaser.component.core#events) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 185](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L185)) See * [Phaser.Events](phaser.events) ### exists : boolean Controls if this Sprite is processed by the core Phaser game loops and Group loops. Inherited From * [PIXI.Sprite#exists](pixi.sprite#exists) Default Value * true Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 103](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L103)) ### fixedToCamera : boolean A Game Object that is "fixed" to the camera uses its x/y coordinates as offsets from the top left of the camera during rendering. The values are adjusted at the rendering stage, overriding the Game Objects actual world position. The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times regardless where in the world the camera is. The offsets are stored in the `cameraOffset` property. Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. Inherited From * [Phaser.Component.FixedToCamera#fixedToCamera](phaser.component.fixedtocamera#fixedToCamera) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 56](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L56)) ### frame : integer Gets or sets the current frame index of the texture being used to render this Game Object. To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use, for example: `player.frame = 4`. If the frame index given doesn't exist it will revert to the first frame found in the texture. If you are using a texture atlas then you should use the `frameName` property instead. If you wish to fully replace the texture being used see `loadTexture`. Inherited From * [Phaser.Component.LoadTexture#frame](phaser.component.loadtexture#frame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 254](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L254)) ### frameName : string Gets or sets the current frame name of the texture being used to render this Game Object. To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use, for example: `player.frameName = "idle"`. If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning. If you are using a sprite sheet then you should use the `frame` property instead. If you wish to fully replace the texture being used see `loadTexture`. Inherited From * [Phaser.Component.LoadTexture#frameName](phaser.component.loadtexture#frameName) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 279](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L279)) ### [readonly] fresh : boolean A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. This property is mostly used internally by the physics systems, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#fresh](phaser.component.core#fresh) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 248](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L248)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Inherited From * [Phaser.Component.Core#game](phaser.component.core#game) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 142](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L142)) ### heal Heal the Game Object. This adds the given amount of health to the `health` property. Inherited From * [Phaser.Component.Health#heal](phaser.component.health#heal) Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 90](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L90)) ### health : number The Game Objects health value. This is a handy property for setting and manipulating health on a Game Object. It can be used in combination with the `damage` method or modified directly. Inherited From * [Phaser.Component.Health#health](phaser.component.health#health) Default Value * 1 Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L26)) ### height : number The height of the sprite, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.Sprite#height](pixi.sprite#height) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 144](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L144)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### [readonly] inCamera : boolean Checks if the Game Objects bounds intersect with the Game Camera bounds. Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. Inherited From * [Phaser.Component.AutoCull#inCamera](phaser.component.autocull#inCamera) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L37)) ### input : [Phaser.InputHandler](phaser.inputhandler) | null The Input Handler for this Game Object. By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`. After you have done this, this property will be a reference to the Phaser InputHandler. ##### Type * [Phaser.InputHandler](phaser.inputhandler) | null Inherited From * [Phaser.Component.InputEnabled#input](phaser.component.inputenabled#input) Source code: [gameobjects/components/InputEnabled.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js#L24)) ### inputEnabled : boolean By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created for this Game Object and it will then start to process click / touch events and more. You can then access the Input Handler via `this.input`. Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`. If you set this property to false it will stop the Input Handler from processing any more input events. If you want to *temporarily* disable input for a Game Object, then it's better to set `input.enabled = false`, as it won't reset any of the Input Handlers internal properties. You can then toggle this back on as needed. Inherited From * [Phaser.Component.InputEnabled#inputEnabled](phaser.component.inputenabled#inputEnabled) Source code: [gameobjects/components/InputEnabled.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js#L42)) ### [readonly] inWorld : boolean Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds. Inherited From * [Phaser.Component.InWorld#inWorld](phaser.component.inworld#inWorld) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 129](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L129)) ### key : string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) The key of the image or texture used by this Game Object during rendering. If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. ##### Type * string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) Inherited From * [Phaser.Component.Core#key](phaser.component.core#key) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 203](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L203)) ### left : number The left coordinate of the Game Object. This is the same as `x - offsetX`. Inherited From * [Phaser.Component.Bounds#left](phaser.component.bounds#left) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 102](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L102)) ### lifespan : number The lifespan allows you to give a Game Object a lifespan in milliseconds. Once the Game Object is 'born' you can set this to a positive value. It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. When it reaches zero it will call the `kill` method. Very handy for particles, bullets, collectibles, or any other short-lived entity. Inherited From * [Phaser.Component.LifeSpan#lifespan](phaser.component.lifespan#lifespan) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 65](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L65)) ### maxHealth : number The Game Objects maximum health value. This works in combination with the `heal` method to ensure the health value never exceeds the maximum. Inherited From * [Phaser.Component.Health#maxHealth](phaser.component.health#maxHealth) Default Value * 100 Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 35](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L35)) ### name : string A user defined name given to this Game Object. This value isn't ever used internally by Phaser, it is meant as a game level property. Inherited From * [Phaser.Component.Core#name](phaser.component.core#name) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 150](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L150)) ### [readonly] offsetX : number The amount the Game Object is visually offset from its x coordinate. This is the same as `width * anchor.x`. It will only be > 0 if anchor.x is not equal to zero. Inherited From * [Phaser.Component.Bounds#offsetX](phaser.component.bounds#offsetX) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L24)) ### [readonly] offsetY : number The amount the Game Object is visually offset from its y coordinate. This is the same as `height * anchor.y`. It will only be > 0 if anchor.y is not equal to zero. Inherited From * [Phaser.Component.Bounds#offsetY](phaser.component.bounds#offsetY) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L42)) ### outOfBoundsKill : boolean If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false. Inherited From * [Phaser.Component.InWorld#outOfBoundsKill](phaser.component.inworld#outOfBoundsKill) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 106](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L106)) ### outOfCameraBoundsKill : boolean If this and the `autoCull` property are both set to `true`, then the `kill` method is called as soon as the Game Object leaves the camera bounds. Inherited From * [Phaser.Component.InWorld#outOfCameraBoundsKill](phaser.component.inworld#outOfCameraBoundsKill) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 115](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L115)) ### pendingDestroy : boolean A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. You can set it directly to allow you to flag an object to be destroyed on its next update. This is extremely useful if you wish to destroy an object from within one of its own callbacks such as with Buttons or other Input events. Inherited From * [Phaser.Component.Core#pendingDestroy](phaser.component.core#pendingDestroy) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 259](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L259)) ### [readonly] physicsType : number The const physics body type of this object. Inherited From * [Phaser.Sprite#physicsType](phaser.sprite#physicsType) Source code: [gameobjects/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Sprite.js) ([Line 61](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Sprite.js#L61)) ### [readonly] previousPosition : [Phaser.Point](phaser.point) The position the Game Object was located in the previous frame. Inherited From * [Phaser.Component.Core#previousPosition](phaser.component.core#previousPosition) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 225](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L225)) ### [readonly] previousRotation : number The rotation the Game Object was in set to in the previous frame. Value is in radians. Inherited From * [Phaser.Component.Core#previousRotation](phaser.component.core#previousRotation) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L232)) ### [readonly] renderOrderID : number The render order ID is used internally by the renderer and Input Manager and should not be modified. This property is mostly used internally by the renderers, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#renderOrderID](phaser.component.core#renderOrderID) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 240](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L240)) ### right : number The right coordinate of the Game Object. This is the same as `x + width - offsetX`. Inherited From * [Phaser.Component.Bounds#right](phaser.component.bounds#right) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L124)) ### scaleMax : [Phaser.Point](phaser.point) The maximum scale this Game Object will scale up to. It allows you to prevent a parent from scaling this Game Object higher than the given value. Set it to `null` to remove the limit. Inherited From * [Phaser.Component.ScaleMinMax#scaleMax](phaser.component.scaleminmax#scaleMax) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L46)) ### scaleMin : [Phaser.Point](phaser.point) The minimum scale this Game Object will scale down to. It allows you to prevent a parent from scaling this Game Object lower than the given value. Set it to `null` to remove the limit. Inherited From * [Phaser.Component.ScaleMinMax#scaleMin](phaser.component.scaleminmax#scaleMin) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 36](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L36)) ### setHealth Sets the health property of the Game Object to the given amount. Will never exceed the `maxHealth` value. Inherited From * [Phaser.Component.Health#setHealth](phaser.component.health#setHealth) Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 70](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L70)) ### shader : [PIXI.AbstractFilter](pixi.abstractfilter) The shader that will be used to render this Sprite. Set to null to remove a current shader. Inherited From * [PIXI.Sprite#shader](pixi.sprite#shader) Default Value * null Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L93)) ### smoothed : boolean Enable or disable texture smoothing for this Game Object. It only takes effect if the Game Object is using an image based texture. Smoothing is enabled by default. Inherited From * [Phaser.Component.Smoothed#smoothed](phaser.component.smoothed#smoothed) Source code: [gameobjects/components/Smoothed.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Smoothed.js) ([Line 25](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Smoothed.js#L25)) ### texture : [PIXI.Texture](pixi.texture) The texture that the sprite is using Inherited From * [PIXI.Sprite#texture](pixi.sprite#texture) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L28)) ### tint : number The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. Inherited From * [PIXI.Sprite#tint](pixi.sprite#tint) Default Value * 0xFFFFFF Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L54)) ### tintedTexture :Canvas A canvas that contains the tinted version of the Sprite (in Canvas mode, WebGL doesn't populate this) Inherited From * [PIXI.Sprite#tintedTexture](pixi.sprite#tintedTexture) Default Value * null Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 73](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L73)) ### top : number The y coordinate of the Game Object. This is the same as `y - offsetY`. Inherited From * [Phaser.Component.Bounds#top](phaser.component.bounds#top) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 146](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L146)) ### transformCallback : Function The callback that will apply any scale limiting to the worldTransform. Inherited From * [Phaser.Component.ScaleMinMax#transformCallback](phaser.component.scaleminmax#transformCallback) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L20)) ### transformCallbackContext : Object The context under which `transformCallback` is called. Inherited From * [Phaser.Component.ScaleMinMax#transformCallbackContext](phaser.component.scaleminmax#transformCallbackContext) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L26)) ### [readonly] type : number The const type of this object. Inherited From * [Phaser.Sprite#type](phaser.sprite#type) Source code: [gameobjects/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Sprite.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Sprite.js#L55)) ### width : number The width of the sprite, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.Sprite#width](pixi.sprite#width) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 125](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L125)) ### world : [Phaser.Point](phaser.point) The world coordinates of this Game Object in pixels. Depending on where in the display list this Game Object is placed this value can differ from `position`, which contains the x/y coordinates relative to the Game Objects parent. Inherited From * [Phaser.Component.Core#world](phaser.component.core#world) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 211](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L211)) ### x : number The position of the Game Object on the x axis relative to the local coordinates of the parent. Inherited From * [Phaser.Component.PhysicsBody#x](phaser.component.physicsbody#x) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L98)) ### y : number The position of the Game Object on the y axis relative to the local coordinates of the parent. Inherited From * [Phaser.Component.PhysicsBody#y](phaser.component.physicsbody#y) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L124)) ### [readonly] z : number The z depth of this Game Object within its parent Group. No two objects in a Group can have the same z value. This value is adjusted automatically whenever the Group hierarchy changes. If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. Inherited From * [Phaser.Component.Core#z](phaser.component.core#z) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 177](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L177)) Public Methods -------------- ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### alignIn(container, position, offsetX, offsetY) → {Object} Aligns this Game Object within another Game Object, or Rectangle, known as the 'container', to one of 9 possible positions. The container must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the container. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the container, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `container` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Inherited From * [Phaser.Component.Bounds#alignIn](phaser.component.bounds#alignIn) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 223](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L223)) ### alignTo(parent, position, offsetX, offsetY) → {Object} Aligns this Game Object to the side of another Game Object, or Rectangle, known as the 'parent', in one of 11 possible positions. The parent must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the parent. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the parent, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Inherited From * [Phaser.Component.Bounds#alignTo](phaser.component.bounds#alignTo) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 321](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L321)) ### bringToTop() → {PIXI.DisplayObject} Brings this Game Object to the top of its parents display list. Visually this means it will render over the top of any old child in the same Group. If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#bringToTop](phaser.component.bringtotop#bringToTop) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L24)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### crop(rect, copy) Crop allows you to crop the texture being used to display this Game Object. Setting a crop rectangle modifies the core texture frame. The Game Object width and height properties will be adjusted accordingly. Cropping takes place from the top-left and can be modified in real-time either by providing an updated rectangle object to this method, or by modifying `cropRect` property directly and then calling `updateCrop`. The rectangle object given to this method can be either a `Phaser.Rectangle` or any other object so long as it has public `x`, `y`, `width`, `height`, `right` and `bottom` properties. A reference to the rectangle is stored in `cropRect` unless the `copy` parameter is `true`, in which case the values are duplicated to a local object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `rect` | [Phaser.Rectangle](phaser.rectangle) | | | The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle. | | `copy` | boolean | <optional> | false | If false `cropRect` will be stored as a reference to the given rect. If true it will copy the rect values into a local Phaser Rectangle object stored in cropRect. | Inherited From * [Phaser.Component.Crop#crop](phaser.component.crop#crop) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L49)) ### destroy(destroyChildren, destroyTexture) Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present and nulls its reference to `game`, freeing it up for garbage collection. If this Game Object has the Events component it will also dispatch the `onDestroy` event. You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've more than one Game Object sharing the same BaseTexture. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroyChildren` | boolean | <optional> | true | Should every child of this object have its destroy method called as well? | | `destroyTexture` | boolean | <optional> | false | Destroy the BaseTexture this Game Object is using? Note that if another Game Object is sharing the same BaseTexture it will invalidate it. | Inherited From * [Phaser.Component.Destroy#destroy](phaser.component.destroy#destroy) Source code: [gameobjects/components/Destroy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js#L37)) ### getBounds(matrix) → {Rectangle} Returns the bounds of the Sprite as a rectangle. The bounds calculation takes the worldTransform into account. It is important to note that the transform is not updated when you call this method. So if this Sprite is the child of a Display Object which has had its transform updated since the last render pass, those changes will not yet have been applied to this Sprites worldTransform. If you need to ensure that all parent transforms are factored into this getBounds operation then you should call `updateTransform` on the root most object in this Sprites display list first. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `matrix` | Matrix | the transformation matrix of the sprite | ##### Returns Rectangle - the framing rectangle Inherited From * [PIXI.Sprite#getBounds](pixi.sprite#getBounds) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 199](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L199)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the Sprite as a rectangle. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.Sprite#getLocalBounds](pixi.sprite#getLocalBounds) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 315](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L315)) ### kill() Kills the Bullet, freeing it up for re-use by the Weapon bullet pool. Also dispatches the `Weapon.onKill` signal. Source code: [plugins/weapon/Bullet.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/Bullet.js) ([Line 41](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/Bullet.js#L41)) ### kill() Updates the Bullet, killing as required. Source code: [plugins/weapon/Bullet.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/Bullet.js) ([Line 60](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/weapon/Bullet.js#L60)) ### loadTexture(key, frame, stopAnimation) Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache. If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead. You should only use `loadTexture` if you want to replace the base texture entirely. Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU. You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite. Doing this then sets the key to be the `frame` argument (the frame is set to zero). This allows you to create sprites using `load.image` during development, and then change them to use a Texture Atlas later in development by simply searching your code for 'PENDING\_ATLAS' and swapping it to be the key of the atlas data. Note: You cannot use a RenderTexture as a texture for a TileSprite. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | | `stopAnimation` | boolean | <optional> | true | If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing. | Inherited From * [Phaser.Component.LoadTexture#loadTexture](phaser.component.loadtexture#loadTexture) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L51)) ### moveDown() → {PIXI.DisplayObject} Moves this Game Object down one place in its parents display list. This call has no effect if the Game Object is already at the bottom of the display list. If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#moveDown](phaser.component.bringtotop#moveDown) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L87)) ### moveUp() → {PIXI.DisplayObject} Moves this Game Object up one place in its parents display list. This call has no effect if the Game Object is already at the top of the display list. If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#moveUp](phaser.component.bringtotop#moveUp) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 66](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L66)) ### overlap(displayObject) → {boolean} Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object, which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result. This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result. Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency. It should be fine for low-volume testing where physics isn't required. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `displayObject` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.TileSprite](phaser.tilesprite) | [Phaser.Button](phaser.button) | PIXI.DisplayObject | The display object to check against. | ##### Returns boolean - True if the bounds of this Game Object intersects at any point with the bounds of the given display object. Inherited From * [Phaser.Component.Overlap#overlap](phaser.component.overlap#overlap) Source code: [gameobjects/components/Overlap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Overlap.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Overlap.js#L29)) ### play(name, frameRate, loop, killOnComplete) → {[Phaser.Animation](phaser.animation)} Plays an Animation. The animation should have previously been created via `animations.add`. If the animation is already playing calling this again won't do anything. If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `name` | string | | | The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'. | | `frameRate` | number | <optional> | null | The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. | | `loop` | boolean | <optional> | false | Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. | | `killOnComplete` | boolean | <optional> | false | If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. | ##### Returns [Phaser.Animation](phaser.animation) - A reference to playing Animation. Inherited From * [Phaser.Component.Animation#play](phaser.component.animation#play) Source code: [gameobjects/components/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Animation.js) ([Line 31](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Animation.js#L31)) ### <internal> postUpdate() Internal method called by the World postUpdate cycle. Inherited From * [Phaser.Component.Core#postUpdate](phaser.component.core#postUpdate) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 338](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L338)) ### preUpdate() → {boolean} Automatically called by World.preUpdate. ##### Returns boolean - True if the Sprite was rendered, otherwise false. Inherited From * [Phaser.Sprite#preUpdate](phaser.sprite#preUpdate) Source code: [gameobjects/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Sprite.js) ([Line 107](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Sprite.js#L107)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### reset(x, y, health) → {PIXI.DisplayObject} Resets the Game Object. This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`, `visible` and `renderable` to true. If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value. If this Game Object has a Physics Body it will reset the Body. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate (in world space) to position the Game Object at. | | `y` | number | | | The y coordinate (in world space) to position the Game Object at. | | `health` | number | <optional> | 1 | The health to give the Game Object if it has the Health component. | ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.Reset#reset](phaser.component.reset#reset) Source code: [gameobjects/components/Reset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Reset.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Reset.js#L30)) ### resetFrame() Resets the texture frame dimensions that the Game Object uses for rendering. Inherited From * [Phaser.Component.LoadTexture#resetFrame](phaser.component.loadtexture#resetFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L232)) ### resizeFrame(parent, width, height) Resizes the Frame dimensions that the Game Object uses for rendering. You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData it can be useful to adjust the dimensions directly in this way. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `parent` | object | The parent texture object that caused the resize, i.e. a Phaser.Video object. | | `width` | integer | The new width of the texture. | | `height` | integer | The new height of the texture. | Inherited From * [Phaser.Component.LoadTexture#resizeFrame](phaser.component.loadtexture#resizeFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 220](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L220)) ### revive(health) → {PIXI.DisplayObject} Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `health` | number | <optional> | 100 | The health to give the Game Object. Only set if the GameObject has the Health component. | ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.LifeSpan#revive](phaser.component.lifespan#revive) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L78)) ### sendToBack() → {PIXI.DisplayObject} Sends this Game Object to the bottom of its parents display list. Visually this means it will render below all other children in the same Group. If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#sendToBack](phaser.component.bringtotop#sendToBack) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L45)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### setFrame(frame) Sets the texture frame the Game Object uses for rendering. This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `frame` | [Phaser.Frame](phaser.frame) | The Frame to be used by the texture. | Inherited From * [Phaser.Component.LoadTexture#setFrame](phaser.component.loadtexture#setFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 155](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L155)) ### setScaleMinMax(minX, minY, maxX, maxY) Sets the scaleMin and scaleMax values. These values are used to limit how far this Game Object will scale based on its parent. For example if this Game Object has a `minScale` value of 1 and its parent has a `scale` value of 0.5, the 0.5 will be ignored and the scale value of 1 will be used, as the parents scale is lower than the minimum scale this Game Object should adhere to. By setting these values you can carefully control how Game Objects deal with responsive scaling. If only one parameter is given then that value will be used for both scaleMin and scaleMax: `setScaleMinMax(1)` = scaleMin.x, scaleMin.y, scaleMax.x and scaleMax.y all = 1 If only two parameters are given the first is set as scaleMin.x and y and the second as scaleMax.x and y: `setScaleMinMax(0.5, 2)` = scaleMin.x and y = 0.5 and scaleMax.x and y = 2 If you wish to set `scaleMin` with different values for x and y then either modify Game Object.scaleMin directly, or pass `null` for the `maxX` and `maxY` parameters. Call `setScaleMinMax(null)` to clear all previously set values. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `minX` | number | null | The minimum horizontal scale value this Game Object can scale down to. | | `minY` | number | null | The minimum vertical scale value this Game Object can scale down to. | | `maxX` | number | null | The maximum horizontal scale value this Game Object can scale up to. | | `maxY` | number | null | The maximum vertical scale value this Game Object can scale up to. | Inherited From * [Phaser.Component.ScaleMinMax#setScaleMinMax](phaser.component.scaleminmax#setScaleMinMax) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 110](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L110)) ### setTexture(texture, destroy) Sets the texture of the sprite. Be warned that this doesn't remove or destroy the previous texture this Sprite was using. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `texture` | [PIXI.Texture](pixi.texture) | | | The PIXI texture that is displayed by the sprite | | `destroy` | Boolean | <optional> | false | Call Texture.destroy on the current texture before replacing it with the new one? | Inherited From * [PIXI.Sprite#setTexture](pixi.sprite#setTexture) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 163](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L163)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) ### update() Override this method in your own custom objects to handle any update requirements. It is called immediately after `preUpdate` and before `postUpdate`. Remember if this Game Object has any children you should call update on those too. Inherited From * [Phaser.Component.Core#update](phaser.component.core#update) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 328](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L328)) ### updateCrop() If you have set a crop rectangle on this Game Object via `crop` and since modified the `cropRect` property, or the rectangle it references, then you need to update the crop frame by calling this method. Inherited From * [Phaser.Component.Crop#updateCrop](phaser.component.crop#updateCrop) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L86))
programming_docs
phaser Class: Phaser.Physics.Ninja Class: Phaser.Physics.Ninja =========================== Constructor ----------- ### new Ninja(game) Ninja Physics. The Ninja Physics system was created in Flash by Metanet Software and ported to JavaScript by Richard Davey. It allows for AABB and Circle to Tile collision. Tiles can be any of 34 different types, including slopes, convex and concave shapes. It does what it does very well, but is ripe for expansion and optimisation. Here are some features that I'd love to see the community add: * AABB to AABB collision * AABB to Circle collision * AABB and Circle 'immovable' property support * n-way collision, so an AABB/Circle could pass through a tile from below and land upon it. * QuadTree or spatial grid for faster Body vs. Tile Group look-ups. * Optimise the internal vector math and reduce the quantity of temporary vars created. * Expand Gravity and Bounce to allow for separate x/y axis values. * Support Bodies linked to Sprites that don't have anchor set to 0.5 Feel free to attempt any of the above and submit a Pull Request with your code! Be sure to include test cases proving they work. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | reference to the current game instance. | Source code: [physics/ninja/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js#L29)) Classes ------- [AABB](phaser.physics.ninja.aabb) [Body](phaser.physics.ninja.body) [Circle](phaser.physics.ninja.circle) [Tile](phaser.physics.ninja.tile) Public Properties ----------------- ### bounds : [Phaser.Rectangle](phaser.rectangle) The bounds inside of which the physics world exists. Defaults to match the world bounds. Source code: [physics/ninja/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js#L49)) ### game : [Phaser.Game](phaser.game) Local reference to game. Source code: [physics/ninja/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js) ([Line 34](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js#L34)) ### gravity : number The World gravity setting. Source code: [physics/ninja/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js) ([Line 44](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js#L44)) ### maxLevels : number Used by the QuadTree to set the maximum number of iteration levels. Source code: [physics/ninja/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js) ([Line 59](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js#L59)) ### maxObjects : number Used by the QuadTree to set the maximum number of objects per quad. Source code: [physics/ninja/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js#L54)) ### quadTree : [Phaser.QuadTree](phaser.quadtree) The world QuadTree. Source code: [physics/ninja/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js) ([Line 64](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js#L64)) ### time : [Phaser.Time](phaser.time) Local reference to game.time. Source code: [physics/ninja/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js) ([Line 39](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js#L39)) Public Methods -------------- ### clearTilemapLayerBodies(map, layer) Clears all physics bodies from the given TilemapLayer that were created with `World.convertTilemap`. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `map` | [Phaser.Tilemap](phaser.tilemap) | | The Tilemap to get the map data from. | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | The layer to operate on. If not given will default to map.currentLayer. | Source code: [physics/ninja/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js) ([Line 224](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js#L224)) ### collide(object1, object2, collideCallback, processCallback, callbackContext) → {boolean} Checks for collision between two game objects. You can perform Sprite vs. Sprite, Sprite vs. Group, Group vs. Group, Sprite vs. Tilemap Layer or Group vs. Tilemap Layer collisions. The second parameter can be an array of objects, of differing types. The objects are also automatically separated. If you don't require separation then use ArcadePhysics.overlap instead. An optional processCallback can be provided. If given this function will be called when two sprites are found to be colliding. It is called before any separation takes place, giving you the chance to perform additional checks. If the function returns true then the collision and separation is carried out. If it returns false it is skipped. The collideCallback is an optional function that is only called if two sprites collide. If a processCallback has been set then it needs to return true for collideCallback to be called. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `object1` | [Phaser.Sprite](phaser.sprite) | [Phaser.Group](phaser.group) | Phaser.Particles.Emitter | [Phaser.TilemapLayer](phaser.tilemaplayer) | | | The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer. | | `object2` | [Phaser.Sprite](phaser.sprite) | [Phaser.Group](phaser.group) | Phaser.Particles.Emitter | [Phaser.TilemapLayer](phaser.tilemaplayer) | array | | | The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. | | `collideCallback` | function | <optional> | null | An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. | | `processCallback` | function | <optional> | null | A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. | | `callbackContext` | object | <optional> | | The context in which to run the callbacks. | ##### Returns boolean - True if a collision occured otherwise false. Source code: [physics/ninja/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js) ([Line 330](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js#L330)) ### convertTilemap(map, layer, slopeMap) → {array} Goes through all tiles in the given Tilemap and TilemapLayer and converts those set to collide into physics tiles. Only call this *after* you have specified all of the tiles you wish to collide with calls like Tilemap.setCollisionBetween, etc. Every time you call this method it will destroy any previously created bodies and remove them from the world. Therefore understand it's a very expensive operation and not to be done in a core game update loop. In Ninja the Tiles have an ID from 0 to 33, where 0 is 'empty', 1 is a full tile, 2 is a 45-degree slope, etc. You can find the ID list either at the very bottom of `Tile.js`, or in a handy visual reference in the `resources/Ninja Physics Debug Tiles` folder in the repository. The slopeMap parameter is an array that controls how the indexes of the tiles in your tilemap data will map to the Ninja Tile IDs. For example if you had 6 tiles in your tileset: Imagine the first 4 should be converted into fully solid Tiles and the other 2 are 45-degree slopes. Your slopeMap array would look like this: `[ 1, 1, 1, 1, 2, 3 ]`. Where each element of the array is a tile in your tilemap and the resulting Ninja Tile it should create. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `map` | [Phaser.Tilemap](phaser.tilemap) | The Tilemap to get the map data from. | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | The layer to operate on. If not given will default to map.currentLayer. | | `slopeMap` | object | The tilemap index to Tile ID map. | ##### Returns array - An array of the Phaser.Physics.Ninja.Tile objects that were created. Source code: [physics/ninja/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js) ([Line 246](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js#L246)) ### enable(object, type, id, radius, children) This will create a Ninja Physics body on the given game object or array of game objects. A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `object` | object | array | [Phaser.Group](phaser.group) | | | The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. | | `type` | number | <optional> | 1 | The type of Ninja shape to create. 1 = AABB, 2 = Circle or 3 = Tile. | | `id` | number | <optional> | 1 | If this body is using a Tile shape, you can set the Tile id here, i.e. Phaser.Physics.Ninja.Tile.SLOPE\_45DEGpn, Phaser.Physics.Ninja.Tile.CONVEXpp, etc. | | `radius` | number | <optional> | 0 | If this body is using a Circle shape this controls the radius. | | `children` | boolean | <optional> | true | Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. | Source code: [physics/ninja/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js) ([Line 121](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js#L121)) ### enableAABB(object, children) This will create a Ninja Physics AABB body on the given game object. Its dimensions will match the width and height of the object at the point it is created. A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `object` | object | array | [Phaser.Group](phaser.group) | | | The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. | | `children` | boolean | <optional> | true | Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. | Source code: [physics/ninja/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js) ([Line 75](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js#L75)) ### enableBody(object) Creates a Ninja Physics body on the given game object. A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `object` | object | The game object to create the physics body on. A body will only be created if this object has a null `body` property. | Source code: [physics/ninja/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js) ([Line 181](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js#L181)) ### enableCircle(object, radius, children) This will create a Ninja Physics Circle body on the given game object. A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `object` | object | array | [Phaser.Group](phaser.group) | | | The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. | | `radius` | number | | | The radius of the Circle. | | `children` | boolean | <optional> | true | Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. | Source code: [physics/ninja/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js) ([Line 89](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js#L89)) ### enableTile(object, id, children) This will create a Ninja Physics Tile body on the given game object. There are 34 different types of tile you can create, including 45 degree slopes, convex and concave circles and more. The id parameter controls which Tile type is created, but you can also change it at run-time. Note that for all degree based tile types they need to have an equal width and height. If the given object doesn't have equal width and height it will use the width. A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `object` | object | array | [Phaser.Group](phaser.group) | | | The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. | | `id` | number | <optional> | 1 | The type of Tile this will use, i.e. Phaser.Physics.Ninja.Tile.SLOPE\_45DEGpn, Phaser.Physics.Ninja.Tile.CONVEXpp, etc. | | `children` | boolean | <optional> | true | Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. | Source code: [physics/ninja/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js) ([Line 104](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js#L104)) ### overlap(object1, object2, overlapCallback, processCallback, callbackContext) → {boolean} Checks for overlaps between two game objects. The objects can be Sprites, Groups or Emitters. You can perform Sprite vs. Sprite, Sprite vs. Group and Group vs. Group overlap checks. Unlike collide the objects are NOT automatically separated or have any physics applied, they merely test for overlap results. The second parameter can be an array of objects, of differing types. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `object1` | [Phaser.Sprite](phaser.sprite) | [Phaser.Group](phaser.group) | Phaser.Particles.Emitter | | | The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. | | `object2` | [Phaser.Sprite](phaser.sprite) | [Phaser.Group](phaser.group) | Phaser.Particles.Emitter | array | | | The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. | | `overlapCallback` | function | <optional> | null | An optional callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you specified them. | | `processCallback` | function | <optional> | null | A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then overlapCallback will only be called if processCallback returns true. | | `callbackContext` | object | <optional> | | The context in which to run the callbacks. | ##### Returns boolean - True if an overlap occured otherwise false. Source code: [physics/ninja/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js) ([Line 291](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js#L291)) ### separate(body1, body2) → {boolean} The core separation function to separate two physics bodies. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `body1` | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | The Body object to separate. | | `body2` | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | The Body object to separate. | ##### Returns boolean - Returns true if the bodies collided, otherwise false. Source code: [physics/ninja/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js) ([Line 567](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js#L567)) ### setBounds(x, y, width, height) Updates the size of this physics world. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Top left most corner of the world. | | `y` | number | Top left most corner of the world. | | `width` | number | New width of the world. Can never be smaller than the Game.width. | | `height` | number | New height of the world. Can never be smaller than the Game.height. | Source code: [physics/ninja/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js) ([Line 198](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js#L198)) ### setBoundsToWorld() Updates the size of this physics world to match the size of the game world. Source code: [physics/ninja/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/World.js#L213)) phaser Class: Phaser.BitmapData Class: Phaser.BitmapData ======================== Constructor ----------- ### new BitmapData(game, key, width, height, skipPool) A BitmapData object contains a Canvas element to which you can draw anything you like via normal Canvas context operations. A single BitmapData can be used as the texture for one or many Images / Sprites. So if you need to dynamically create a Sprite texture then they are a good choice. Important note: Every BitmapData creates its own Canvas element. Because BitmapData's are now Game Objects themselves, and don't live on the display list, they are NOT automatically cleared when you change State. Therefore you *must* call BitmapData.destroy in your State's shutdown method if you wish to free-up the resources the BitmapData used, it will not happen for you. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | | A reference to the currently running game. | | `key` | string | | | Internal Phaser reference key for the BitmapData. | | `width` | number | <optional> | 256 | The width of the BitmapData in pixels. If undefined or zero it's set to a default value. | | `height` | number | <optional> | 256 | The height of the BitmapData in pixels. If undefined or zero it's set to a default value. | | `skipPool` | boolean | <optional> | false | When this BitmapData generates its internal canvas to use for rendering, it will get the canvas from the CanvasPool if false, or create its own if true. | Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L24)) Public Properties ----------------- ### baseTexture : [PIXI.BaseTexture](pixi.basetexture) The PIXI.BaseTexture. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L124)) ### canvas :HTMLCanvasElement The canvas to which this BitmapData draws. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L54)) ### context :CanvasRenderingContext2D The 2d context of the canvas. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 60](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L60)) ### ctx :CanvasRenderingContext2D A reference to BitmapData.context. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 65](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L65)) ### data :Uint8ClampedArray A Uint8ClampedArray view into BitmapData.buffer. Note that this is unavailable in some browsers (such as Epic Browser due to its security restrictions) Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 84](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L84)) ### dirty : boolean If dirty this BitmapData will be re-rendered. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 159](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L159)) ### disableTextureUpload : boolean If disableTextureUpload is true this BitmapData will never send its image data to the GPU when its dirty flag is true. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 154](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L154)) ### frameData : [Phaser.FrameData](phaser.framedata) The FrameData container this BitmapData uses for rendering. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 135](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L135)) ### game : [Phaser.Game](phaser.game) A reference to the currently running game. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 33](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L33)) ### height : number The height of the BitmapData in pixels. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 48](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L48)) ### imageData :ImageData The context image data. Please note that a call to BitmapData.draw() or BitmapData.copy() does not update immediately this property for performance reason. Use BitmapData.update() to do so. This property is updated automatically after the first game loop, according to the dirty flag property. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 77](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L77)) ### key : string The key of the BitmapData in the Cache, if stored there. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L38)) ### pixels :Uint32Array An Uint32Array view into BitmapData.buffer. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 94](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L94)) ### smoothProperty : string The context property needed for smoothing this Canvas. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 70](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L70)) ### texture : [PIXI.Texture](pixi.texture) The PIXI.Texture. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 130](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L130)) ### textureFrame : [Phaser.Frame](phaser.frame) The Frame this BitmapData uses for rendering. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 141](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L141)) ### type : number The const type of this object. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 149](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L149)) ### width : number The width of the BitmapData in pixels. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 43](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L43)) Public Methods -------------- ### <static> getTransform(translateX, translateY, scaleX, scaleY, skewX, skewY) → {object} Gets a JavaScript object that has 6 properties set that are used by BitmapData in a transform. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `translateX` | number | The x translate value. | | `translateY` | number | The y translate value. | | `scaleX` | number | The scale x value. | | `scaleY` | number | The scale y value. | | `skewX` | number | The skew x value. | | `skewY` | number | The skew y value. | ##### Returns object - A JavaScript object containing all of the properties BitmapData needs for transforms. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2419](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2419)) ### add(object) → {[Phaser.BitmapData](phaser.bitmapdata)} Updates the given objects so that they use this BitmapData as their texture. This will replace any texture they will currently have set. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `object` | [Phaser.Sprite](phaser.sprite) | Array.<[Phaser.Sprite](phaser.sprite)> | [Phaser.Image](phaser.image) | Array.<[Phaser.Image](phaser.image)> | Either a single Sprite/Image or an Array of Sprites/Images. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 393](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L393)) ### addToWorld(x, y, anchorX, anchorY, scaleX, scaleY) → {[Phaser.Image](phaser.image)} Creates a new Phaser.Image object, assigns this BitmapData to be its texture, adds it to the world then returns it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | <optional> | 0 | The x coordinate to place the Image at. | | `y` | number | <optional> | 0 | The y coordinate to place the Image at. | | `anchorX` | number | <optional> | 0 | Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. | | `anchorY` | number | <optional> | 0 | Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. | | `scaleX` | number | <optional> | 1 | The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. | | `scaleY` | number | <optional> | 1 | The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. | ##### Returns [Phaser.Image](phaser.image) - The newly added Image object. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 1179](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L1179)) ### alphaMask(source, mask, sourceRect, maskRect) → {[Phaser.BitmapData](phaser.bitmapdata)} Draws the image onto this BitmapData using an image as an alpha mask. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `source` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapData](phaser.bitmapdata) | Image | HTMLCanvasElement | string | | The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. | | `mask` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapData](phaser.bitmapdata) | Image | HTMLCanvasElement | string | <optional> | The object to be used as the mask. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. If you don't provide a mask it will use this BitmapData as the mask. | | `sourceRect` | [Phaser.Rectangle](phaser.rectangle) | <optional> | A Rectangle where x/y define the coordinates to draw the Source image to and width/height define the size. | | `maskRect` | [Phaser.Rectangle](phaser.rectangle) | <optional> | A Rectangle where x/y define the coordinates to draw the Mask image to and width/height define the size. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 1738](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L1738)) ### blendAdd() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'lighter' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2169](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2169)) ### blendColor() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'color' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2351](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2351)) ### blendColorBurn() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'color-burn' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2260](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2260)) ### blendColorDodge() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'color-dodge' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2247](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2247)) ### blendDarken() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'darken' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2221](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2221)) ### blendDestinationAtop() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'destination-atop' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2143](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2143)) ### blendDestinationIn() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'destination-in' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2117](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2117)) ### blendDestinationOut() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'destination-out' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2130](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2130)) ### blendDestinationOver() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'destination-over' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2104](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2104)) ### blendDifference() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'difference' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2299](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2299)) ### blendExclusion() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'exclusion' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2312](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2312)) ### blendHardLight() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'hard-light' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2273](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2273)) ### blendHue() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'hue' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2325](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2325)) ### blendLighten() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'lighten' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2234](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2234)) ### blendLuminosity() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'luminosity' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2364](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2364)) ### blendMultiply() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'multiply' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2182](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2182)) ### blendOverlay() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'overlay' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2208](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2208)) ### blendReset() → {[Phaser.BitmapData](phaser.bitmapdata)} Resets the blend mode (effectively sets it to 'source-over') ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2039](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2039)) ### blendSaturation() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'saturation' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2338](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2338)) ### blendScreen() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'screen' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2195](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2195)) ### blendSoftLight() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'soft-light' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2286](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2286)) ### blendSourceAtop() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'source-atop' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2091](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2091)) ### blendSourceIn() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'source-in' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2065](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2065)) ### blendSourceOut() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'source-out' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2078](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2078)) ### blendSourceOver() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'source-over' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2052](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2052)) ### blendXor() → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the blend mode to 'xor' ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2156](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2156)) ### circle(x, y, radius, fillStyle) → {[Phaser.BitmapData](phaser.bitmapdata)} Draws a filled Circle to the BitmapData at the given x, y coordinates and radius in size. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `x` | number | | The x coordinate to draw the Circle at. This is the center of the circle. | | `y` | number | | The y coordinate to draw the Circle at. This is the center of the circle. | | `radius` | number | | The radius of the Circle in pixels. The radius is half the diameter. | | `fillStyle` | string | <optional> | If set the context fillStyle will be set to this value before the circle is drawn. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 1891](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L1891)) ### clear(x, y, width, height) → {[Phaser.BitmapData](phaser.bitmapdata)} Clears the BitmapData context using a clearRect. You can optionally define the area to clear. If the arguments are left empty it will clear the entire canvas. You may need to call BitmapData.update after this in order to clear out the pixel data, but Phaser will not do this automatically for you. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | <optional> | 0 | The x coordinate of the top-left of the area to clear. | | `y` | number | <optional> | 0 | The y coordinate of the top-left of the area to clear. | | `width` | number | <optional> | | The width of the area to clear. If undefined it will use BitmapData.width. | | `height` | number | <optional> | | The height of the area to clear. If undefined it will use BitmapData.height. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 463](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L463)) ### cls() Clears the BitmapData context using a clearRect. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 457](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L457)) ### copy(source, x, y, width, height, tx, ty, newWidth, newHeight, rotate, anchorX, anchorY, scaleX, scaleY, alpha, blendMode, roundPx) → {[Phaser.BitmapData](phaser.bitmapdata)} Copies a rectangular area from the source object to this BitmapData. If you give `null` as the source it will copy from itself. You can optionally resize, translate, rotate, scale, alpha or blend as it's drawn. All rotation, scaling and drawing takes place around the regions center point by default, but can be changed with the anchor parameters. Note that the source image can also be this BitmapData, which can create some interesting effects. This method has a lot of parameters for maximum control. You can use the more friendly methods like `copyRect` and `draw` to avoid having to remember them all. You may prefer to use `copyTransform` if you're simply trying to draw a Sprite to this BitmapData, and don't wish to translate, scale or rotate it from its original values. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `source` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.RenderTexture](phaser.rendertexture) | Image | HTMLCanvasElement | string | <optional> | | The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. | | `x` | number | <optional> | 0 | The x coordinate representing the top-left of the region to copy from the source image. | | `y` | number | <optional> | 0 | The y coordinate representing the top-left of the region to copy from the source image. | | `width` | number | <optional> | | The width of the region to copy from the source image. If not specified it will use the full source image width. | | `height` | number | <optional> | | The height of the region to copy from the source image. If not specified it will use the full source image height. | | `tx` | number | <optional> | | The x coordinate to translate to before drawing. If not specified it will default to the `x` parameter. If `null` and `source` is a Display Object, it will default to `source.x`. | | `ty` | number | <optional> | | The y coordinate to translate to before drawing. If not specified it will default to the `y` parameter. If `null` and `source` is a Display Object, it will default to `source.y`. | | `newWidth` | number | <optional> | | The new width of the block being copied. If not specified it will default to the `width` parameter. | | `newHeight` | number | <optional> | | The new height of the block being copied. If not specified it will default to the `height` parameter. | | `rotate` | number | <optional> | 0 | The angle in radians to rotate the block to before drawing. Rotation takes place around the center by default, but can be changed with the `anchor` parameters. | | `anchorX` | number | <optional> | 0 | The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. | | `anchorY` | number | <optional> | 0 | The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. | | `scaleX` | number | <optional> | 1 | The horizontal scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on. | | `scaleY` | number | <optional> | 1 | The vertical scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on. | | `alpha` | number | <optional> | 1 | The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque. | | `blendMode` | string | <optional> | null | The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. | | `roundPx` | boolean | <optional> | false | Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 1205](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L1205)) ### copyRect(source, area, x, y, alpha, blendMode, roundPx) → {[Phaser.BitmapData](phaser.bitmapdata)} Copies the area defined by the Rectangle parameter from the source image to this BitmapData at the given location. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `source` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.RenderTexture](phaser.rendertexture) | Image | string | | | The Image to copy from. If you give a string it will try and find the Image in the Game.Cache. | | `area` | [Phaser.Rectangle](phaser.rectangle) | | | The Rectangle region to copy from the source image. | | `x` | number | | | The destination x coordinate to copy the image to. | | `y` | number | | | The destination y coordinate to copy the image to. | | `alpha` | number | <optional> | 1 | The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque. | | `blendMode` | string | <optional> | null | The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. | | `roundPx` | boolean | <optional> | false | Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 1534](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L1534)) ### copyTransform(source, blendMode, roundPx) → {[Phaser.BitmapData](phaser.bitmapdata)} Draws the given `source` Game Object to this BitmapData, using its `worldTransform` property to set the position, scale and rotation of where it is drawn. This function is used internally by `drawGroup`. It takes the objects tint and scale mode into consideration before drawing. You can optionally specify Blend Mode and Round Pixels arguments. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `source` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.BitmapText](phaser.bitmaptext) | <optional> | | The Game Object to draw. | | `blendMode` | string | <optional> | null | The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. | | `roundPx` | boolean | <optional> | false | Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 1426](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L1426)) ### destroy() Destroys this BitmapData and puts the canvas it was using back into the canvas pool for re-use. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2024](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2024)) ### draw(source, x, y, width, height, blendMode, roundPx) → {[Phaser.BitmapData](phaser.bitmapdata)} Draws the given Phaser.Sprite, Phaser.Image or Phaser.Text to this BitmapData at the coordinates specified. You can use the optional width and height values to 'stretch' the sprite as it is drawn. This uses drawImage stretching, not scaling. The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible. When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values. Note: You should ensure that at least 1 full update has taken place before calling this, otherwise the objects are likely to render incorrectly, if at all. You can trigger an update yourself by calling `stage.updateTransform()` before calling `draw`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `source` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.RenderTexture](phaser.rendertexture) | | | The Sprite, Image or Text object to draw onto this BitmapData. | | `x` | number | <optional> | 0 | The x coordinate to translate to before drawing. If not specified it will default to `source.x`. | | `y` | number | <optional> | 0 | The y coordinate to translate to before drawing. If not specified it will default to `source.y`. | | `width` | number | <optional> | | The new width of the Sprite being copied. If not specified it will default to `source.width`. | | `height` | number | <optional> | | The new height of the Sprite being copied. If not specified it will default to `source.height`. | | `blendMode` | string | <optional> | null | The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. | | `roundPx` | boolean | <optional> | false | Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 1553](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L1553)) ### drawFull(parent, blendMode, roundPx) → {[Phaser.BitmapData](phaser.bitmapdata)} Draws the Game Object or Group to this BitmapData and then recursively iterates through all of its children. If a child has an `exists` property then it (and its children) will be only be drawn if exists is `true`. The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be drawn. Depending on your requirements you may need to resize the BitmapData in advance to match the bounds of the top-level Game Object. When drawing it will take into account the child's world rotation, scale and alpha values. It's perfectly valid to pass in `game.world` as the parent object, and it will iterate through the entire display list. Note: If you are trying to grab your entire game at the start of a State then you should ensure that at least 1 full update has taken place before doing so, otherwise all of the objects will render with incorrect positions and scales. You can trigger an update yourself by calling `stage.updateTransform()` before calling `drawFull`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | [Phaser.World](phaser.world) | [Phaser.Group](phaser.group) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | | | The Game Object to draw onto this BitmapData and then recursively draw all of its children. | | `blendMode` | string | <optional> | null | The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. | | `roundPx` | boolean | <optional> | false | Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 1648](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L1648)) ### drawGroup(group, blendMode, roundPx) → {[Phaser.BitmapData](phaser.bitmapdata)} Draws the immediate children of a Phaser.Group to this BitmapData. It's perfectly valid to pass in `game.world` as the Group, and it will iterate through the entire display list. Children are drawn *only* if they have their `exists` property set to `true`, and have image, or RenderTexture, based Textures. The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible. When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values. Note: You should ensure that at least 1 full update has taken place before calling this, otherwise the objects are likely to render incorrectly, if at all. You can trigger an update yourself by calling `stage.updateTransform()` before calling `drawGroup`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `group` | [Phaser.Group](phaser.group) | | | The Group to draw onto this BitmapData. Can also be Phaser.World. | | `blendMode` | string | <optional> | null | The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. | | `roundPx` | boolean | <optional> | false | Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 1581](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L1581)) ### extract(destination, r, g, b, a, resize, r2, g2, b2) → {[Phaser.BitmapData](phaser.bitmapdata)} Scans this BitmapData for all pixels matching the given r,g,b values and then draws them into the given destination BitmapData. The original BitmapData remains unchanged. The destination BitmapData must be large enough to receive all of the pixels that are scanned unless the 'resize' parameter is true. Although the destination BitmapData is returned from this method, it's actually modified directly in place, meaning this call is perfectly valid: `picture.extract(mask, r, g, b)` You can specify optional r2, g2, b2 color values. If given the pixel written to the destination bitmap will be of the r2, g2, b2 color. If not given it will be written as the same color it was extracted. You can provide one or more alternative colors, allowing you to tint the color during extraction. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destination` | [Phaser.BitmapData](phaser.bitmapdata) | | | The BitmapData that the extracted pixels will be drawn to. | | `r` | number | | | The red color component, in the range 0 - 255. | | `g` | number | | | The green color component, in the range 0 - 255. | | `b` | number | | | The blue color component, in the range 0 - 255. | | `a` | number | <optional> | 255 | The alpha color component, in the range 0 - 255 that the new pixel will be drawn at. | | `resize` | boolean | <optional> | false | Should the destination BitmapData be resized to match this one before the pixels are copied? | | `r2` | number | <optional> | | An alternative red color component to be written to the destination, in the range 0 - 255. | | `g2` | number | <optional> | | An alternative green color component to be written to the destination, in the range 0 - 255. | | `b2` | number | <optional> | | An alternative blue color component to be written to the destination, in the range 0 - 255. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - The BitmapData that the extract pixels were drawn on. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 1772](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L1772)) ### fill(r, g, b, a) → {[Phaser.BitmapData](phaser.bitmapdata)} Fills the BitmapData with the given color. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `r` | number | | | The red color value, between 0 and 0xFF (255). | | `g` | number | | | The green color value, between 0 and 0xFF (255). | | `b` | number | | | The blue color value, between 0 and 0xFF (255). | | `a` | number | <optional> | 1 | The alpha color value, between 0 and 1. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 494](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L494)) ### generateTexture(key) → {[PIXI.Texture](pixi.texture)} Creates a new Image element by converting this BitmapDatas canvas into a dataURL. The image is then stored in the image Cache using the key given. Finally a PIXI.Texture is created based on the image and returned. You can apply the texture to a sprite or any other supporting object by using either the key or the texture. First call generateTexture: `var texture = bitmapdata.generateTexture('ball');` Then you can either apply the texture to a sprite: `game.add.sprite(0, 0, texture);` or by using the string based key: `game.add.sprite(0, 0, 'ball');` ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key which will be used to store the image in the Cache. | ##### Returns [PIXI.Texture](pixi.texture) - The newly generated texture. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 516](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L516)) ### getBounds(rect) → {[Phaser.Rectangle](phaser.rectangle)} Scans the BitmapData and calculates the bounds. This is a rectangle that defines the extent of all non-transparent pixels. The rectangle returned will extend from the top-left of the image to the bottom-right, excluding transparent pixels. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `rect` | [Phaser.Rectangle](phaser.rectangle) | <optional> | If provided this Rectangle object will be populated with the bounds, otherwise a new object will be created. | ##### Returns [Phaser.Rectangle](phaser.rectangle) - A Rectangle whose dimensions encompass the full extent of non-transparent pixels in this BitmapData. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 1151](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L1151)) ### getFirstPixel(direction) → {object} Scans the BitmapData, pixel by pixel, until it encounters a pixel that isn't transparent (i.e. has an alpha value > 0). It then stops scanning and returns an object containing the color of the pixel in r, g and b properties and the location in the x and y properties. The direction parameter controls from which direction it should start the scan: 0 = top to bottom 1 = bottom to top 2 = left to right 3 = right to left ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `direction` | number | <optional> | 0 | The direction in which to scan for the first pixel. 0 = top to bottom, 1 = bottom to top, 2 = left to right and 3 = right to left. | ##### Returns object - Returns an object containing the color of the pixel in the `r`, `g` and `b` properties and the location in the `x` and `y` properties. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 1068](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L1068)) ### getPixel(x, y, out) → {object} Get the color of a specific pixel in the context into a color object. If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `x` | number | | The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData. | | `y` | number | | The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData. | | `out` | object | <optional> | An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. | ##### Returns object - An object with the red, green, blue and alpha values set in the r, g, b and a properties. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 985](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L985)) ### getPixel32(x, y) → {number} Get the color of a specific pixel including its alpha value. If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. Note that on little-endian systems the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData. | | `y` | number | The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData. | ##### Returns number - A native color value integer (format: 0xAARRGGBB) Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 1016](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L1016)) ### getPixelRGB(x, y, out, hsl, hsv) → {object} Get the color of a specific pixel including its alpha value as a color object containing r,g,b,a and rgba properties. If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData. | | `y` | number | | | The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData. | | `out` | object | <optional> | | An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. | | `hsl` | boolean | <optional> | false | Also convert the rgb values into hsl? | | `hsv` | boolean | <optional> | false | Also convert the rgb values into hsv? | ##### Returns object - An object with the red, green and blue values set in the r, g and b properties. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 1036](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L1036)) ### getPixels(rect) → {ImageData} Gets all the pixels from the region specified by the given Rectangle object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `rect` | [Phaser.Rectangle](phaser.rectangle) | The Rectangle region to get. | ##### Returns ImageData - Returns a ImageData object containing a Uint8ClampedArray data property. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 1055](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L1055)) ### line(x1, y1, x2, y2, color, width) → {[Phaser.BitmapData](phaser.bitmapdata)} Draws a line between the coordinates given in the color and thickness specified. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x1` | number | | | The x coordinate to start the line from. | | `y1` | number | | | The y coordinate to start the line from. | | `x2` | number | | | The x coordinate to draw the line to. | | `y2` | number | | | The y coordinate to draw the line to. | | `color` | string | <optional> | '#fff' | The stroke color that the line will be drawn in. | | `width` | number | <optional> | 1 | The line thickness. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 1920](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L1920)) ### load(source) → {[Phaser.BitmapData](phaser.bitmapdata)} Takes the given Game Object, resizes this BitmapData to match it and then draws it into this BitmapDatas canvas, ready for further processing. The source game object is not modified by this operation. If the source object uses a texture as part of a Texture Atlas or Sprite Sheet, only the current frame will be used for sizing. If a string is given it will assume it's a cache key and look in Phaser.Cache for an image key matching the string. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `source` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapData](phaser.bitmapdata) | Image | HTMLCanvasElement | string | The object that will be used to populate this BitmapData. If you give a string it will try and find the Image in the Game.Cache first. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 422](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L422)) ### move(x, y, wrap) → {[Phaser.BitmapData](phaser.bitmapdata)} Shifts the contents of this BitmapData by the distances given. The image will wrap-around the edges on all sides if the wrap argument is true (the default). ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | integer | | | The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right. | | `y` | integer | | | The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down. | | `wrap` | boolean | <optional> | true | Wrap the content of the BitmapData. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 240](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L240)) ### moveH(distance, wrap) → {[Phaser.BitmapData](phaser.bitmapdata)} Shifts the contents of this BitmapData horizontally. The image will wrap-around the sides if the wrap argument is true (the default). ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `distance` | integer | | | The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right. | | `wrap` | boolean | <optional> | true | Wrap the content of the BitmapData. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 267](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L267)) ### moveV(distance, wrap) → {[Phaser.BitmapData](phaser.bitmapdata)} Shifts the contents of this BitmapData vertically. The image will wrap-around the sides if the wrap argument is true (the default). ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `distance` | integer | | | The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down. | | `wrap` | boolean | <optional> | true | Wrap the content of the BitmapData. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 330](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L330)) ### processPixel(callback, callbackContext, x, y, width, height) → {[Phaser.BitmapData](phaser.bitmapdata)} Scans through the area specified in this BitmapData and sends the color for every pixel to the given callback along with its x and y coordinates. Whatever value the callback returns is set as the new color for that pixel, unless it returns the same color, in which case it's skipped. Note that the format of the color received will be different depending on if the system is big or little endian. It is expected that your callback will deal with endianess. If you'd rather Phaser did it then use processPixelRGB instead. The callback will also be sent the pixels x and y coordinates respectively. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The callback that will be sent each pixel color to be processed. | | `callbackContext` | object | | | The context under which the callback will be called. | | `x` | number | <optional> | 0 | The x coordinate of the top-left of the region to process from. | | `y` | number | <optional> | 0 | The y coordinate of the top-left of the region to process from. | | `width` | number | <optional> | | The width of the region to process. | | `height` | number | <optional> | | The height of the region to process. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 700](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L700)) ### processPixelRGB(callback, callbackContext, x, y, width, height) → {[Phaser.BitmapData](phaser.bitmapdata)} Scans through the area specified in this BitmapData and sends a color object for every pixel to the given callback. The callback will be sent a color object with 6 properties: `{ r: number, g: number, b: number, a: number, color: number, rgba: string }`. Where r, g, b and a are integers between 0 and 255 representing the color component values for red, green, blue and alpha. The `color` property is an Int32 of the full color. Note the endianess of this will change per system. The `rgba` property is a CSS style rgba() string which can be used with context.fillStyle calls, among others. The callback will also be sent the pixels x and y coordinates respectively. The callback must return either `false`, in which case no change will be made to the pixel, or a new color object. If a new color object is returned the pixel will be set to the r, g, b and a color values given within it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The callback that will be sent each pixel color object to be processed. | | `callbackContext` | object | | | The context under which the callback will be called. | | `x` | number | <optional> | 0 | The x coordinate of the top-left of the region to process from. | | `y` | number | <optional> | 0 | The y coordinate of the top-left of the region to process from. | | `width` | number | <optional> | | The width of the region to process. | | `height` | number | <optional> | | The height of the region to process. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 642](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L642)) ### rect(x, y, width, height, fillStyle) → {[Phaser.BitmapData](phaser.bitmapdata)} Draws a filled Rectangle to the BitmapData at the given x, y coordinates and width / height in size. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `x` | number | | The x coordinate of the top-left of the Rectangle. | | `y` | number | | The y coordinate of the top-left of the Rectangle. | | `width` | number | | The width of the Rectangle. | | `height` | number | | The height of the Rectangle. | | `fillStyle` | string | <optional> | If set the context fillStyle will be set to this value before the rect is drawn. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 1825](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L1825)) ### render() → {[Phaser.BitmapData](phaser.bitmapdata)} If the game is running in WebGL this will push the texture up to the GPU if it's dirty. This is called automatically if the BitmapData is being used by a Sprite, otherwise you need to remember to call it in your render function. If you wish to suppress this functionality set BitmapData.disableTextureUpload to `true`. ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 2004](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L2004)) ### replaceRGB(r1, g1, b1, a1, r2, g2, b2, a2, region) → {[Phaser.BitmapData](phaser.bitmapdata)} Replaces all pixels matching one color with another. The color values are given as two sets of RGBA values. An optional region parameter controls if the replacement happens in just a specific area of the BitmapData or the entire thing. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `r1` | number | | The red color value to be replaced. Between 0 and 255. | | `g1` | number | | The green color value to be replaced. Between 0 and 255. | | `b1` | number | | The blue color value to be replaced. Between 0 and 255. | | `a1` | number | | The alpha color value to be replaced. Between 0 and 255. | | `r2` | number | | The red color value that is the replacement color. Between 0 and 255. | | `g2` | number | | The green color value that is the replacement color. Between 0 and 255. | | `b2` | number | | The blue color value that is the replacement color. Between 0 and 255. | | `a2` | number | | The alpha color value that is the replacement color. Between 0 and 255. | | `region` | [Phaser.Rectangle](phaser.rectangle) | <optional> | The area to perform the search over. If not given it will replace over the whole BitmapData. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 754](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L754)) ### resize(width, height) → {[Phaser.BitmapData](phaser.bitmapdata)} Resizes the BitmapData. This changes the size of the underlying canvas and refreshes the buffer. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `width` | integer | The new width of the BitmapData. | | `height` | integer | The new height of the BitmapData. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 552](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L552)) ### setHSL(h, s, l, region) → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `h` | number | <optional> | null | The hue, in the range 0 - 1. | | `s` | number | <optional> | null | The saturation, in the range 0 - 1. | | `l` | number | <optional> | null | The lightness, in the range 0 - 1. | | `region` | [Phaser.Rectangle](phaser.rectangle) | <optional> | | The area to perform the operation on. If not given it will run over the whole BitmapData. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 804](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L804)) ### setPixel(x, y, red, green, blue, immediate) → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the color of the given pixel to the specified red, green and blue values. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData. | | `y` | number | | | The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData. | | `red` | number | | | The red color value, between 0 and 0xFF (255). | | `green` | number | | | The green color value, between 0 and 0xFF (255). | | `blue` | number | | | The blue color value, between 0 and 0xFF (255). | | `immediate` | boolean | <optional> | true | If `true` the context.putImageData will be called and the dirty flag set. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 967](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L967)) ### setPixel32(x, y, red, green, blue, alpha, immediate) → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the color of the given pixel to the specified red, green, blue and alpha values. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData. | | `y` | number | | | The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData. | | `red` | number | | | The red color value, between 0 and 0xFF (255). | | `green` | number | | | The green color value, between 0 and 0xFF (255). | | `blue` | number | | | The blue color value, between 0 and 0xFF (255). | | `alpha` | number | | | The alpha color value, between 0 and 0xFF (255). | | `immediate` | boolean | <optional> | true | If `true` the context.putImageData will be called and the dirty flag set. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 928](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L928)) ### shadow(color, blur, x, y) → {[Phaser.BitmapData](phaser.bitmapdata)} Sets the shadow properties of this BitmapDatas context which will affect all draw operations made to it. You can cancel an existing shadow by calling this method and passing no parameters. Note: At the time of writing (October 2014) Chrome still doesn't support shadowBlur used with drawImage. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `color` | string | | | The color of the shadow, given in a CSS format, i.e. `#000000` or `rgba(0,0,0,1)`. If `null` or `undefined` the shadow will be reset. | | `blur` | number | <optional> | 5 | The amount the shadow will be blurred by. Low values = a crisp shadow, high values = a softer shadow. | | `x` | number | <optional> | 10 | The horizontal offset of the shadow in pixels. | | `y` | number | <optional> | 10 | The vertical offset of the shadow in pixels. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 1706](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L1706)) ### shiftHSL(h, s, l, region) → {[Phaser.BitmapData](phaser.bitmapdata)} Shifts any or all of the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified. Shifting will add the given value onto the current h, s and l values, not replace them. The hue is wrapped to keep it within the range 0 to 1. Saturation and lightness are clamped to not exceed 1. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `h` | number | <optional> | null | The amount to shift the hue by. | | `s` | number | <optional> | null | The amount to shift the saturation by. | | `l` | number | <optional> | null | The amount to shift the lightness by. | | `region` | [Phaser.Rectangle](phaser.rectangle) | <optional> | | The area to perform the operation on. If not given it will run over the whole BitmapData. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 865](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L865)) ### text(text, x, y, font, color, shadow) → {[Phaser.BitmapData](phaser.bitmapdata)} Draws text to the BitmapData in the given font and color. The default font is 14px Courier, so useful for quickly drawing debug text. If you need to do a lot of font work to this BitmapData we'd recommend implementing your own text draw method. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `text` | string | | | The text to write to the BitmapData. | | `x` | number | | | The x coordinate of the top-left of the text string. | | `y` | number | | | The y coordinate of the top-left of the text string. | | `font` | string | <optional> | '14px Courier' | The font. This is passed directly to Context.font, so anything that can support, this can. | | `color` | string | <optional> | 'rgb(255,255,255)' | The color the text will be drawn in. | | `shadow` | boolean | <optional> | true | Draw a single pixel black shadow below the text (offset by text.x/y + 1) | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 1849](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L1849)) ### textureLine(line, image, repeat) → {[Phaser.BitmapData](phaser.bitmapdata)} Takes the given Line object and image and renders it to this BitmapData as a repeating texture line. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `line` | [Phaser.Line](phaser.line) | | | A Phaser.Line object that will be used to plot the start and end of the line. | | `image` | string | Image | | | The key of an image in the Phaser.Cache to use as the texture for this line, or an actual Image. | | `repeat` | string | <optional> | 'repeat-x' | The pattern repeat mode to use when drawing the line. Either `repeat`, `repeat-x` or `no-repeat`. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 1954](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L1954)) ### update(x, y, width, height) → {[Phaser.BitmapData](phaser.bitmapdata)} This re-creates the BitmapData.imageData from the current context. It then re-builds the ArrayBuffer, the data Uint8ClampedArray reference and the pixels Int32Array. If not given the dimensions defaults to the full size of the context. Warning: This is a very expensive operation, so use it sparingly. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | <optional> | 0 | The x coordinate of the top-left of the image data area to grab from. | | `y` | number | <optional> | 0 | The y coordinate of the top-left of the image data area to grab from. | | `width` | number | <optional> | 1 | The width of the image data area. | | `height` | number | <optional> | 1 | The height of the image data area. | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - This BitmapData object for method chaining. Source code: [gameobjects/BitmapData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js) ([Line 596](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/BitmapData.js#L596))
programming_docs
phaser Class: Phaser.Tileset Class: Phaser.Tileset ===================== Constructor ----------- ### new Tileset(name, firstgid, width, height, margin, spacing, properties) A Tile set is a combination of an image containing the tiles and collision data per tile. Tilesets are normally created automatically when Tiled data is loaded. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `name` | string | | | The name of the tileset in the map data. | | `firstgid` | integer | | | The first tile index this tileset contains. | | `width` | integer | <optional> | 32 | Width of each tile (in pixels). | | `height` | integer | <optional> | 32 | Height of each tile (in pixels). | | `margin` | integer | <optional> | 0 | The margin around all tiles in the sheet (in pixels). | | `spacing` | integer | <optional> | 0 | The spacing between each tile in the sheet (in pixels). | | `properties` | object | <optional> | {} | Custom Tileset properties. | Source code: [tilemap/Tileset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js#L22)) Public Properties ----------------- ### [readonly] columns : integer The number of tile columns in the tileset. Source code: [tilemap/Tileset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js) ([Line 101](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js#L101)) ### firstgid : integer The Tiled firstgid value. This is the starting index of the first tile index this Tileset contains. Source code: [tilemap/Tileset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js) ([Line 40](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js#L40)) ### [readonly] image : Object The cached image that contains the individual tiles. Use setImage to set. Source code: [tilemap/Tileset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js#L85)) ### name : string The name of the Tileset. Source code: [tilemap/Tileset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js) ([Line 33](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js#L33)) ### properties : Object Tileset-specific properties that are typically defined in the Tiled editor. Source code: [tilemap/Tileset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js) ([Line 77](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js#L77)) ### [readonly] rows The number of tile rows in the the tileset. ##### Properties: | Type | Description | | --- | --- | | integer | | Source code: [tilemap/Tileset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js#L93)) ### [readonly] tileHeight : integer The height of each tile (in pixels). Source code: [tilemap/Tileset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js#L54)) ### [readonly] tileMargin The margin around the tiles in the sheet (in pixels). Use `setSpacing` to change. ##### Properties: | Name | Type | Description | | --- | --- | --- | | `tileMarge` | integer | | Source code: [tilemap/Tileset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js) ([Line 63](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js#L63)) ### [readonly] tileSpacing : integer The spacing between each tile in the sheet (in pixels). Use `setSpacing` to change. Source code: [tilemap/Tileset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js) ([Line 71](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js#L71)) ### [readonly] tileWidth : integer The width of each tile (in pixels). Source code: [tilemap/Tileset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js) ([Line 47](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js#L47)) ### [readonly] total : integer The total number of tiles in the tileset. Source code: [tilemap/Tileset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js) ([Line 109](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js#L109)) Public Methods -------------- ### containsTileIndex() → {boolean} Returns true if and only if this tileset contains the given tile index. ##### Returns boolean - True if this tileset contains the given index. Source code: [tilemap/Tileset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js) ([Line 155](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js#L155)) ### draw(context, x, y, index) Draws a tile from this Tileset at the given coordinates on the context. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `context` | CanvasRenderingContext2D | The context to draw the tile onto. | | `x` | number | The x coordinate to draw to. | | `y` | number | The y coordinate to draw to. | | `index` | integer | The index of the tile within the set to draw. | Source code: [tilemap/Tileset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js) ([Line 123](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js#L123)) ### setImage(image) Set the image associated with this Tileset and update the tile data. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `image` | Image | The image that contains the tiles. | Source code: [tilemap/Tileset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js#L171)) ### setSpacing(margin, spacing) Sets tile spacing and margins. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `margin` | integer | <optional> | 0 | The margin around the tiles in the sheet (in pixels). | | `spacing` | integer | <optional> | 0 | The spacing between the tiles in the sheet (in pixels). | Source code: [tilemap/Tileset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js) ([Line 185](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tileset.js#L185)) phaser Class: Phaser.Component.Destroy Class: Phaser.Component.Destroy =============================== Constructor ----------- ### new Destroy() The Destroy component is responsible for destroying a Game Object. Source code: [gameobjects/components/Destroy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js) ([Line 12](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js#L12)) Public Properties ----------------- ### [readonly] destroyPhase : boolean As a Game Object runs through its destroy method this flag is set to true, and can be checked in any sub-systems or plugins it is being destroyed from. Source code: [gameobjects/components/Destroy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js#L22)) Public Methods -------------- ### destroy(destroyChildren, destroyTexture) Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present and nulls its reference to `game`, freeing it up for garbage collection. If this Game Object has the Events component it will also dispatch the `onDestroy` event. You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've more than one Game Object sharing the same BaseTexture. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroyChildren` | boolean | <optional> | true | Should every child of this object have its destroy method called as well? | | `destroyTexture` | boolean | <optional> | false | Destroy the BaseTexture this Game Object is using? Note that if another Game Object is sharing the same BaseTexture it will invalidate it. | Source code: [gameobjects/components/Destroy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js#L37)) phaser Class: Phaser.ScaleManager Class: Phaser.ScaleManager ========================== Constructor ----------- ### new ScaleManager(game, width, height) Create a new ScaleManager object - this is done automatically by [Phaser.Game](phaser.game) The `width` and `height` constructor parameters can either be a number which represents pixels or a string that represents a percentage: e.g. `800` (for 800 pixels) or `"80%"` for 80%. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | | `width` | number | string | The width of the game. See above. | | `height` | number | string | The height of the game. See above. | Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L46)) Public Properties ----------------- ### [static] EXACT\_FIT : integer A scale mode that stretches content to fill all available space - see [scaleMode](phaser.scalemanager#scaleMode). Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 609](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L609)) ### [static] NO\_SCALE : integer A scale mode that prevents any scaling - see [scaleMode](phaser.scalemanager#scaleMode). Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 617](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L617)) ### [static] RESIZE : integer A scale mode that causes the Game size to change - see [scaleMode](phaser.scalemanager#scaleMode). Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 633](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L633)) ### [static] SHOW\_ALL : integer A scale mode that shows the entire game while maintaining proportions - see [scaleMode](phaser.scalemanager#scaleMode). Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 625](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L625)) ### [static] USER\_SCALE : integer A scale mode that allows a custom scale factor - see [scaleMode](phaser.scalemanager#scaleMode). Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 641](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L641)) ### [readonly] aspectRatio : number The aspect ratio of the scaled Display canvas. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 349](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L349)) ### [readonly] boundingParent :DOMElement The DOM element that is considered the Parent bounding element, if any. This `null` if [parentIsWindow](phaser.scalemanager#parentIsWindow) is true or if fullscreen mode is entered and [fullScreenTarget](phaser.scalemanager#fullScreenTarget) is specified. It will also be null if there is no game canvas or if the game canvas has no parent. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 2091](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L2091)) ### [readonly] bounds : [Phaser.Rectangle](phaser.rectangle) The bounds of the scaled game. The x/y will match the offset of the canvas element and the width/height the scaled width and height. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 342](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L342)) ### <internal> compatibility Various compatibility settings. A value of "(auto)" indicates the setting is configured based on device and runtime information. A [refresh](phaser.scalemanager#refresh) may need to be performed after making changes. ##### Properties: | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `supportsFullScreen` | boolean | <optional> | (auto) | True only if fullscreen support will be used. (Changing to fullscreen still might not work.) | | `orientationFallback` | boolean | <optional> | (auto) | See [Phaser.DOM.getScreenOrientation](phaser.dom#.getScreenOrientation). | | `noMargins` | boolean | <optional> | false | If true then the Display canvas's margins will not be updated anymore: existing margins must be manually cleared. Disabling margins prevents automatic canvas alignment/centering, possibly in fullscreen. | | `scrollTo` | [Phaser.Point](phaser.point) | <optional> <nullable> | (auto) | If specified the window will be scrolled to this position on every refresh. | | `forceMinimumDocumentHeight` | boolean | <optional> | false | If enabled the document elements minimum height is explicitly set on updates. The height set varies by device and may either be the height of the window or the viewport. | | `canExpandParent` | boolean | <optional> | true | If enabled then SHOW\_ALL and USER\_SCALE modes can try and expand the parent element. It may be necessary for the parent element to impose CSS width/height restrictions. | | `clickTrampoline` | string | <optional> | (auto) | On certain browsers (eg. IE) FullScreen events need to be triggered via 'click' events. A value of 'when-not-mouse' uses a click trampoline when a pointer that is not the primary mouse is used. Any other string value (including the empty string) prevents using click trampolines. For more details on click trampolines see [Phaser.Pointer#addClickTrampoline](phaser.pointer#addClickTrampoline). | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 410](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L410)) ### <internal, readonly> currentScaleMode : number Returns the current scale mode - for normal or fullscreen operation. See [scaleMode](phaser.scalemanager#scaleMode) for the different modes allowed. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 2224](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L2224)) ### <internal, readonly> dom : [Phaser.DOM](phaser.dom) Provides access to some cross-device DOM functions. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 62](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L62)) ### enterIncorrectOrientation : [Phaser.Signal](phaser.signal) This signal is dispatched when the browser enters an incorrect orientation, as defined by [forceOrientation](phaser.scalemanager#forceOrientation). This is signaled from `preUpdate` (or `pauseUpdate`) *even when* the game is paused. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 211](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L211)) ### <internal, readonly> forceLandscape : boolean If true, the game should only run in a landscape orientation. Change with [forceOrientation](phaser.scalemanager#forceOrientation). Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 140](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L140)) ### <internal, readonly> forcePortrait : boolean If true, the game should only run in a portrait Change with [forceOrientation](phaser.scalemanager#forceOrientation). Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 150](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L150)) ### fullScreenScaleMode : integer The scaling method used by the ScaleManager when in fullscreen. See [scaleMode](phaser.scalemanager#scaleMode) for the different modes allowed. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 2183](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L2183)) ### fullScreenTarget :DOMElement If specified, this is the DOM element on which the Fullscreen API enter request will be invoked. The target element must have the correct CSS styling and contain the Display canvas. The elements style will be modified (ie. the width and height might be set to 100%) but it will not be added to, removed from, or repositioned within the DOM. An attempt is made to restore relevant style changes when fullscreen mode is left. For pre-2.2.0 behavior set `game.scale.fullScreenTarget = game.canvas`. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 248](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L248)) ### <internal, readonly> game : [Phaser.Game](phaser.game) A reference to the currently running game. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L54)) ### grid : [Phaser.FlexGrid](phaser.flexgrid) *EXPERIMENTAL:* A responsive grid on which you can align game objects. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 69](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L69)) ### hasPhaserSetFullScreen : boolean This boolean provides you with a way to determine if the browser is in Full Screen mode (via the Full Screen API), and Phaser was the one responsible for activating it. It's possible that ScaleManager.isFullScreen returns `true` even if Phaser wasn't the one that made the browser go full-screen, so this flag lets you determine that. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 233](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L233)) ### [readonly] height : number Target height (in pixels) of the Display canvas. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 83](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L83)) ### <internal, readonly> incorrectOrientation : boolean True if [forceLandscape](phaser.scalemanager#forceLandscape) or [forcePortrait](phaser.scalemanager#forcePortrait) are set and do not agree with the browser orientation. This value is not updated immediately. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 161](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L161)) ### [readonly] isFullScreen : boolean Returns true if the browser is in fullscreen mode, otherwise false. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 2315](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L2315)) ### [readonly] isGameLandscape : boolean Returns true if the game dimensions are landscape (width > height). This is especially useful to check when using the RESIZE scale mode but wanting to maintain game orientation on desktop browsers, where typically the screen orientation will always be landscape regardless of the browser viewport. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 2380](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L2380)) ### [readonly] isGamePortrait : boolean Returns true if the game dimensions are portrait (height > width). This is especially useful to check when using the RESIZE scale mode but wanting to maintain game orientation on desktop browsers, where typically the screen orientation will always be landscape regardless of the browser viewport. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 2362](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L2362)) ### [readonly] isLandscape : boolean Returns true if the screen orientation is in landscape mode. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 2347](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L2347)) ### [readonly] isPortrait : boolean Returns true if the screen orientation is in portrait mode. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 2332](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L2332)) ### leaveIncorrectOrientation : [Phaser.Signal](phaser.signal) This signal is dispatched when the browser leaves an incorrect orientation, as defined by [forceOrientation](phaser.scalemanager#forceOrientation). This is signaled from `preUpdate` (or `pauseUpdate`) *even when* the game is paused. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 221](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L221)) ### <internal, readonly> margin :Bounds-like The Display canvas is aligned by adjusting the margins; the last margins are stored here. ##### Type * Bounds-like Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 335](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L335)) ### <internal, readonly> maxHeight : number Maximum height the canvas should be scaled to (in pixels). If null it will scale to whatever height the browser can handle. Change with [setMinMax](phaser.scalemanager#setMinMax). Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 121](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L121)) ### <internal, readonly> maxWidth : number Maximum width the canvas should be scaled to (in pixels). If null it will scale to whatever width the browser can handle. Change with [setMinMax](phaser.scalemanager#setMinMax). Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 102](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L102)) ### <internal, readonly> minHeight : number Minimum height the canvas should be scaled to (in pixels). Change with [setMinMax](phaser.scalemanager#setMinMax). Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 111](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L111)) ### <internal, readonly> minWidth : number Minimum width the canvas should be scaled to (in pixels). Change with [setMinMax](phaser.scalemanager#setMinMax). Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 92](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L92)) ### <internal, readonly> offset : [Phaser.Point](phaser.point) The offset coordinates of the Display canvas from the top-left of the browser window. The is used internally by Phaser.Pointer (for Input) and possibly other types. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 130](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L130)) ### onFullScreenChange : [Phaser.Signal](phaser.signal) This signal is dispatched when the browser enters or leaves fullscreen mode, if supported. The signal is supplied with a single argument: `scale` (the ScaleManager). Use `scale.isFullScreen` to determine if currently running in Fullscreen mode. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 290](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L290)) ### onFullScreenError : [Phaser.Signal](phaser.signal) This signal is dispatched when the browser fails to enter fullscreen mode; or if the device does not support fullscreen mode and `startFullScreen` is invoked. The signal is supplied with a single argument: `scale` (the ScaleManager). Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 301](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L301)) ### onFullScreenInit : [Phaser.Signal](phaser.signal) This signal is dispatched when fullscreen mode is ready to be initialized but before the fullscreen request. The signal is passed two arguments: `scale` (the ScaleManager), and an object in the form `{targetElement: DOMElement}`. The `targetElement` is the [fullScreenTarget](phaser.scalemanager#fullScreenTarget) element, if such is assigned, or a new element created by [createFullScreenTarget](phaser.scalemanager#createFullScreenTarget). Custom CSS styling or resets can be applied to `targetElement` as required. If `targetElement` is *not* the same element as [fullScreenTarget](phaser.scalemanager#fullScreenTarget): * After initialization the Display canvas is moved onto the `targetElement` for the duration of the fullscreen mode, and restored to it's original DOM location when fullscreen is exited. * The `targetElement` is moved/re-parented within the DOM and may have its CSS styles updated. The behavior of a pre-assigned target element is covered in [fullScreenTarget](phaser.scalemanager#fullScreenTarget). Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 279](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L279)) ### onOrientationChange : [Phaser.Signal](phaser.signal) This signal is dispatched when the orientation changes *or* the validity of the current orientation changes. The signal is supplied with the following arguments: * `scale` - the ScaleManager object * `prevOrientation`, a string - The previous orientation as per [screenOrientation](phaser.scalemanager#screenOrientation). * `wasIncorrect`, a boolean - True if the previous orientation was last determined to be incorrect. Access the current orientation and validity with `scale.screenOrientation` and `scale.incorrectOrientation`. Thus the following tests can be done: ``` // The orientation itself changed: scale.screenOrientation !== prevOrientation // The orientation just became incorrect: scale.incorrectOrientation && !wasIncorrect ``` It is possible that this signal is triggered after [forceOrientation](phaser.scalemanager#forceOrientation) so the orientation correctness changes even if the orientation itself does not change. This is signaled from `preUpdate` (or `pauseUpdate`) *even when* the game is paused. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 201](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L201)) ### onSizeChange : [Phaser.Signal](phaser.signal) This signal is dispatched when the size of the Display canvas changes *or* the size of the Game changes. When invoked this is done *after* the Canvas size/position have been updated. This signal is *only* called when a change occurs and a reflow may be required. For example, if the canvas does not change sizes because of CSS settings (such as min-width) then this signal will *not* be triggered. Use this to handle responsive game layout options. This is signaled from `preUpdate` (or `pauseUpdate`) *even when* the game is paused. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 487](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L487)) To Do: * Formalize the arguments, if any, supplied to this signal. ### pageAlignHorizontally : boolean When enabled the Display canvas will be horizontally-aligned *in the Parent container* (or [window](phaser.scalemanager#parentIsWindow)). To align horizontally across the page the Display canvas should be added directly to page; or the parent container should itself be horizontally aligned. Horizontal alignment is not applicable with the [RESIZE](phaser.scalemanager#.RESIZE) scaling mode. Default Value * false Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 2244](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L2244)) ### pageAlignVertically : boolean When enabled the Display canvas will be vertically-aligned *in the Parent container* (or [window](phaser.scalemanager#parentIsWindow)). To align vertically the Parent element should have a *non-collapsible* height, such that it will maintain a height *larger* than the height of the contained Game canvas - the game canvas will then be scaled vertically *within* the remaining available height dictated by the Parent element. One way to prevent the parent from collapsing is to add an absolute "min-height" CSS property to the parent element. If specifying a relative "min-height/height" or adjusting margins, the Parent height must still be non-collapsible (see note). *Note*: In version 2.2 the minimum document height is *not* automatically set to the viewport/window height. To automatically update the minimum document height set [compatibility.forceMinimumDocumentHeight](phaser.scalemanager#compatibility) to true. Vertical alignment is not applicable with the [RESIZE](phaser.scalemanager#.RESIZE) scaling mode. Default Value * false Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 2276](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L2276)) ### parentIsWindow : boolean If the parent container of the Game canvas is the browser window itself (i.e. document.body), rather than another div, this should set to `true`. The [parentNode](phaser.scalemanager#parentNode) property is generally ignored while this is in effect. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 442](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L442)) ### parentNode :DOMElement The *original* DOM element for the parent of the Display canvas. This may be different in fullscreen - see [createFullScreenTarget](phaser.scalemanager#createFullScreenTarget). This should only be changed after moving the Game canvas to a different DOM parent. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 452](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L452)) ### [readonly] parentScaleFactor : [Phaser.Point](phaser.point) The scale of the game in relation to its parent container. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 459](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L459)) ### [readonly] scaleFactor : [Phaser.Point](phaser.point) The *current* scale factor based on the game dimensions vs. the scaled dimensions. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 318](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L318)) ### <internal, readonly> scaleFactorInversed : [Phaser.Point](phaser.point) The *current* inversed scale factor. The displayed dimensions divided by the game dimensions. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 326](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L326)) ### scaleMode : integer The scaling method used by the ScaleManager when not in fullscreen. [Phaser.ScaleManager.NO\_SCALE](phaser.scalemanager#.NO_SCALE) The Game display area will not be scaled - even if it is too large for the canvas/screen. This mode *ignores* any applied scaling factor and displays the canvas at the Game size. [Phaser.ScaleManager.EXACT\_FIT](phaser.scalemanager#.EXACT_FIT) The Game display area will be *stretched* to fill the entire size of the canvas's parent element and/or screen. Proportions are not maintained. [Phaser.ScaleManager.SHOW\_ALL](phaser.scalemanager#.SHOW_ALL) Show the entire game display area while *maintaining* the original aspect ratio. [Phaser.ScaleManager.RESIZE](phaser.scalemanager#.RESIZE) The dimensions of the game display area are changed to match the size of the parent container. That is, this mode *changes the Game size* to match the display size. Any manually set Game size (see [setGameSize](phaser.scalemanager#setGameSize)) is ignored while in effect. [Phaser.ScaleManager.USER\_SCALE](phaser.scalemanager#.USER_SCALE) The game Display is scaled according to the user-specified scale set by [setUserScale](phaser.scalemanager#setUserScale). This scale can be adjusted in the [resize callback](phaser.scalemanager#setResizeCallback) for flexible custom-sizing needs. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 2119](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L2119)) ### [readonly] screenOrientation : string The *last known* orientation of the screen, as defined in the Window Screen Web API. See [Phaser.DOM.getScreenOrientation](phaser.dom#.getScreenOrientation) for possible values. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 311](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L311)) ### [readonly] sourceAspectRatio : number The aspect ratio of the original game dimensions. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 356](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L356)) ### <internal> trackParentInterval : integer The maximum time (in ms) between dimension update checks for the Canvas's parent element (or window). Update checks normally happen quicker in response to other events. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Default Value * 2000 Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 470](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L470)) See * [refresh](phaser.scalemanager#refresh) ### [readonly] width : number Target width (in pixels) of the Display canvas. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 76](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L76)) ### windowConstraints The edges on which to constrain the game Display/canvas in *addition* to the restrictions of the parent container. The properties are strings and can be '', 'visual', 'layout', or 'layout-soft'. * If 'visual', the edge will be constrained to the Window / displayed screen area * If 'layout', the edge will be constrained to the CSS Layout bounds * An invalid value is treated as 'visual' ##### Properties: | Name | Type | Description | | --- | --- | --- | | `bottom` | string | | | `right` | string | | Default Value * {"right":"layout","bottom":""} Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 379](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L379)) Public Methods -------------- ### <internal> boot() Start the ScaleManager. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 645](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L645)) ### <internal> createFullScreenTarget() Creates a fullscreen target. This is called automatically as as needed when entering fullscreen mode and the resulting element is supplied to [onFullScreenInit](phaser.scalemanager#onFullScreenInit). Use [onFullScreenInit](phaser.scalemanager#onFullScreenInit) to customize the created object. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 1728](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L1728)) ### <internal> destroy() Destroys the ScaleManager and removes any event listeners. This should probably only be called when the game is destroyed. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 2058](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L2058)) ### forceOrientation(forceLandscape, forcePortrait) Force the game to run in only one orientation. This enables generation of incorrect orientation signals and affects resizing but does not otherwise rotate or lock the orientation. Orientation checks are performed via the Screen Orientation API, if available in browser. This means it will check your monitor orientation on desktop, or your device orientation on mobile, rather than comparing actual game dimensions. If you need to check the viewport dimensions instead and bypass the Screen Orientation API then set: `ScaleManager.compatibility.orientationFallback = 'viewport'` ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `forceLandscape` | boolean | | | true if the game should run in landscape mode only. | | `forcePortrait` | boolean | <optional> | false | true if the game should run in portrait mode only. | Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 1163](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L1163)) ### <internal> getParentBounds(target) → {[Phaser.Rectangle](phaser.rectangle)} Returns the computed Parent size/bounds that the Display canvas is allowed/expected to fill. If in fullscreen mode or without parent (see [parentIsWindow](phaser.scalemanager#parentIsWindow)), this will be the bounds of the visual viewport itself. This function takes the [windowConstraints](phaser.scalemanager#windowConstraints) into consideration - if the parent is partially outside the viewport then this function may return a smaller than expected size. Values are rounded to the nearest pixel. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `target` | [Phaser.Rectangle](phaser.rectangle) | <optional> | (new Rectangle) | The rectangle to update; a new one is created as needed. | ##### Returns [Phaser.Rectangle](phaser.rectangle) - The established parent bounds. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 1408](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L1408)) ### <internal> parseConfig(config) Load configuration settings. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `config` | object | The game configuration object. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 748](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L748)) ### <internal> preUpdate() The ScaleManager.preUpdate is called automatically by the core Game loop. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 1028](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L1028)) ### refresh() The "refresh" methods informs the ScaleManager that a layout refresh is required. The ScaleManager automatically queues a layout refresh (eg. updates the Game size or Display canvas layout) when the browser is resized, the orientation changes, or when there is a detected change of the Parent size. Refreshing is also done automatically when public properties, such as [scaleMode](phaser.scalemanager#scaleMode), are updated or state-changing methods are invoked. The "refresh" method *may* need to be used in a few (rare) situtations when * a device change event is not correctly detected; or * the Parent size changes (and an immediate reflow is desired); or * the ScaleManager state is updated by non-standard means; or * certain [compatibility](phaser.scalemanager#compatibility) properties are manually changed. The queued layout refresh is not immediate but will run promptly in an upcoming `preRender`. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 1301](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L1301)) ### <internal> scaleSprite(sprite, width, height, letterBox) → {[Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image)} Takes a Sprite or Image object and scales it to fit the given dimensions. Scaling happens proportionally without distortion to the sprites texture. The letterBox parameter controls if scaling will produce a letter-box effect or zoom the sprite until it fills the given values. Note that with letterBox set to false the scaled sprite may spill out over either the horizontal or vertical sides of the target dimensions. If you wish to stop this you can crop the Sprite. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `sprite` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | | | The sprite we want to scale. | | `width` | integer | <optional> | | The target width that we want to fit the sprite in to. If not given it defaults to ScaleManager.width. | | `height` | integer | <optional> | | The target height that we want to fit the sprite in to. If not given it defaults to ScaleManager.height. | | `letterBox` | boolean | <optional> | false | True if we want the `fitted` mode. Otherwise, the function uses the `zoom` mode. | ##### Returns [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) - The scaled sprite. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 1988](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L1988)) ### setGameSize(width, height) Set the actual Game size. Use this instead of directly changing `game.width` or `game.height`. The actual physical display (Canvas element size) depends on various settings including * Scale mode * Scaling factor * Size of Canvas's parent element or CSS rules such as min-height/max-height; * The size of the Window ##### Parameters | Name | Type | Description | | --- | --- | --- | | `width` | integer | *Game width*, in pixels. | | `height` | integer | *Game height*, in pixels. | Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 881](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L881)) ### setMinMax(minWidth, minHeight, maxWidth, maxHeight) Set the min and max dimensions for the Display canvas. *Note:* The min/max dimensions are only applied in some cases * When the device is not in an incorrect orientation; or * The scale mode is EXACT\_FIT when not in fullscreen ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `minWidth` | number | | The minimum width the game is allowed to scale down to. | | `minHeight` | number | | The minimum height the game is allowed to scale down to. | | `maxWidth` | number | <optional> | The maximum width the game is allowed to scale up to; only changed if specified. | | `maxHeight` | number | <optional> | The maximum height the game is allowed to scale up to; only changed if specified. | Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 996](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L996)) To Do: * These values are only sometimes honored. ### setResizeCallback(callback, context) Sets the callback that will be invoked before sizing calculations. This is the appropriate place to call [setUserScale](phaser.scalemanager#setUserScale) if needing custom dynamic scaling. The callback is supplied with two arguments `scale` and `parentBounds` where `scale` is the ScaleManager and `parentBounds`, a Phaser.Rectangle, is the size of the Parent element. This callback * May be invoked even though the parent container or canvas sizes have not changed * Unlike [onSizeChange](phaser.scalemanager#onSizeChange), it runs *before* the canvas is guaranteed to be updated * Will be invoked from `preUpdate`, *even when* the game is paused See [onSizeChange](phaser.scalemanager#onSizeChange) for a better way of reacting to layout updates. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `callback` | function | The callback that will be called each time a window.resize event happens or if set, the parent container resizes. | | `context` | object | The context in which the callback will be called. | Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 933](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L933)) ### <internal> setupScale(width, height) Calculates and sets the game dimensions based on the given width and height. This should *not* be called when in fullscreen mode. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `width` | number | string | The width of the game. | | `height` | number | string | The height of the game. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 781](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L781)) ### setUserScale(hScale, vScale, hTrim, vTrim) Set a User scaling factor used in the USER\_SCALE scaling mode. The target canvas size is computed by: ``` canvas.width = (game.width * hScale) - hTrim canvas.height = (game.height * vScale) - vTrim ``` This method can be used in the [resize callback](phaser.scalemanager#setResizeCallback). ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `hScale` | number | | | Horizontal scaling factor. | | `vScale` | numer | | | Vertical scaling factor. | | `hTrim` | integer | <optional> | 0 | Horizontal trim, applied after scaling. | | `vTrim` | integer | <optional> | 0 | Vertical trim, applied after scaling. | Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 909](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L909)) ### startFullScreen(antialias, allowTrampoline) → {boolean} Start the browsers fullscreen mode - this *must* be called from a user input Pointer or Mouse event. The Fullscreen API must be supported by the browser for this to work - it is not the same as setting the game size to fill the browser window. See [compatibility.supportsFullScreen](phaser.scalemanager#compatibility) to check if the current device is reported to support fullscreen mode. The fullScreenFailed signal will be dispatched if the fullscreen change request failed or the game does not support the Fullscreen API. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `antialias` | boolean | <optional> | Changes the anti-alias feature of the canvas before jumping in to fullscreen (false = retain pixel art, true = smooth art). If not specified then no change is made. Only works in CANVAS mode. | | `allowTrampoline` | boolean | <optional> | Internal argument. If `false` click trampolining is suppressed. | ##### Returns boolean - Returns true if the device supports fullscreen mode and fullscreen mode was attempted to be started. (It might not actually start, wait for the signals.) Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 1749](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L1749)) ### stopFullScreen() → {boolean} Stops / exits fullscreen mode, if active. ##### Returns boolean - Returns true if the browser supports fullscreen mode and fullscreen mode will be exited. Source code: [core/ScaleManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js) ([Line 1842](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/ScaleManager.js#L1842))
programming_docs
phaser Class: Phaser.Key Class: Phaser.Key ================= Constructor ----------- ### new Key(game, keycode) If you need more fine-grained control over the handling of specific keys you can create and use Phaser.Key objects. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | Current game instance. | | `keycode` | integer | The key code this Key is responsible for. See [Phaser.KeyCode](phaser.keycode). | Source code: [input/Key.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js) ([Line 15](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js#L15)) Public Properties ----------------- ### altKey : boolean The down state of the ALT key, if pressed at the same time as this key. Source code: [input/Key.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js#L51)) ### ctrlKey : boolean The down state of the CTRL key, if pressed at the same time as this key. Source code: [input/Key.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js) ([Line 57](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js#L57)) ### duration : number If the key is down this value holds the duration of that key press and is constantly updated. If the key is up it holds the duration of the previous down session. The number of milliseconds this key has been held down for. Source code: [input/Key.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js) ([Line 76](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js#L76)) ### [readonly] event : Object Stores the most recent DOM event. Source code: [input/Key.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js) ([Line 33](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js#L33)) ### game : [Phaser.Game](phaser.game) A reference to the currently running game. Source code: [input/Key.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js#L20)) ### isDown : boolean The "down" state of the key. This will remain `true` for as long as the keyboard thinks this key is held down. Source code: [input/Key.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js) ([Line 39](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js#L39)) ### isUp : boolean The "up" state of the key. This will remain `true` for as long as the keyboard thinks this key is up. Default Value * true Source code: [input/Key.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js#L45)) ### keyCode : number The keycode of this key. Source code: [input/Key.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js#L93)) ### onDown : [Phaser.Signal](phaser.signal) This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again). Source code: [input/Key.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js#L98)) ### onHoldCallback : Function A callback that is called while this Key is held down. Warning: Depending on refresh rate that could be 60+ times per second. Source code: [input/Key.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js) ([Line 103](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js#L103)) ### onHoldContext : Object The context under which the onHoldCallback will be called. Source code: [input/Key.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js) ([Line 108](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js#L108)) ### onUp : [Phaser.Signal](phaser.signal) This Signal is dispatched every time this Key is released. It is only dispatched once (until the key is pressed and released again). Source code: [input/Key.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js) ([Line 113](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js#L113)) ### repeats : number If a key is held down this holds down the number of times the key has 'repeated'. Source code: [input/Key.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js) ([Line 88](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js#L88)) ### shiftKey : boolean The down state of the SHIFT key, if pressed at the same time as this key. Source code: [input/Key.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js) ([Line 63](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js#L63)) ### timeDown : number The timestamp when the key was last pressed down. This is based on Game.time.now. Source code: [input/Key.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js) ([Line 68](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js#L68)) ### timeUp : number The timestamp when the key was last released. This is based on Game.time.now. Source code: [input/Key.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js) ([Line 82](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js#L82)) Public Methods -------------- ### downDuration(duration) → {boolean} Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, or was pressed down longer ago than then given duration. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `duration` | number | <optional> | 50 | The duration within which the key is considered as being just pressed. Given in ms. | ##### Returns boolean - True if the key was pressed down within the given duration. Source code: [input/Key.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js) ([Line 253](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js#L253)) ### <internal> processKeyDown(event) Called automatically by Phaser.Keyboard. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | KeyboardEvent | The DOM event that triggered this. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/Key.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js) ([Line 154](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js#L154)) ### <internal> processKeyUp(event) Called automatically by Phaser.Keyboard. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | KeyboardEvent | The DOM event that triggered this. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/Key.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js#L191)) ### reset(hard) Resets the state of this Key. This sets isDown to false, isUp to true, resets the time to be the current time, and *enables* the key. In addition, if it is a "hard reset", it clears clears any callbacks associated with the onDown and onUp events and removes the onHoldCallback. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `hard` | boolean | <optional> | true | A soft reset won't reset any events or callbacks; a hard reset will. | Source code: [input/Key.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js) ([Line 222](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js#L222)) ### <internal> update() Called automatically by Phaser.Keyboard. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/Key.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js) ([Line 131](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js#L131)) ### upDuration(duration) → {boolean} Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, or was pressed down longer ago than then given duration. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `duration` | number | <optional> | 50 | The duration within which the key is considered as being just released. Given in ms. | ##### Returns boolean - True if the key was released within the given duration. Source code: [input/Key.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js) ([Line 269](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Key.js#L269)) phaser Class: Phaser.RoundedRectangle Class: Phaser.RoundedRectangle ============================== Constructor ----------- ### new RoundedRectangle(x, y, width, height, radius) The Rounded Rectangle object is an area defined by its position and has nice rounded corners, as indicated by its top-left corner point (x, y) and by its width and its height. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | <optional> | 0 | The x coordinate of the top-left corner of the Rectangle. | | `y` | number | <optional> | 0 | The y coordinate of the top-left corner of the Rectangle. | | `width` | number | <optional> | 0 | The width of the Rectangle. Should always be either zero or a positive value. | | `height` | number | <optional> | 0 | The height of the Rectangle. Should always be either zero or a positive value. | | `radius` | number | <optional> | 20 | Controls the radius of the rounded corners. | Source code: [geom/RoundedRectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/RoundedRectangle.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/RoundedRectangle.js#L20)) Public Properties ----------------- ### height : number The height of the Rectangle. This value should never be set to a negative. Source code: [geom/RoundedRectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/RoundedRectangle.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/RoundedRectangle.js#L46)) ### radius : number The radius of the rounded corners. Source code: [geom/RoundedRectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/RoundedRectangle.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/RoundedRectangle.js#L51)) ### [readonly] type : number The const type of this object. Source code: [geom/RoundedRectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/RoundedRectangle.js) ([Line 57](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/RoundedRectangle.js#L57)) ### width : number The width of the Rectangle. This value should never be set to a negative. Source code: [geom/RoundedRectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/RoundedRectangle.js) ([Line 41](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/RoundedRectangle.js#L41)) ### x : number The x coordinate of the top-left corner of the Rectangle. Source code: [geom/RoundedRectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/RoundedRectangle.js) ([Line 31](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/RoundedRectangle.js#L31)) ### y : number The y coordinate of the top-left corner of the Rectangle. Source code: [geom/RoundedRectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/RoundedRectangle.js) ([Line 36](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/RoundedRectangle.js#L36)) Public Methods -------------- ### clone() → {[Phaser.RoundedRectangle](phaser.roundedrectangle)} Returns a new RoundedRectangle object with the same values for the x, y, width, height and radius properties as this RoundedRectangle object. ##### Returns [Phaser.RoundedRectangle](phaser.roundedrectangle) - Source code: [geom/RoundedRectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/RoundedRectangle.js) ([Line 62](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/RoundedRectangle.js#L62)) ### contains(x, y) → {boolean} Determines whether the specified coordinates are contained within the region defined by this Rounded Rectangle object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The x coordinate of the point to test. | | `y` | number | The y coordinate of the point to test. | ##### Returns boolean - A value of true if the RoundedRectangle Rectangle object contains the specified point; otherwise false. Source code: [geom/RoundedRectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/RoundedRectangle.js) ([Line 75](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/RoundedRectangle.js#L75)) phaser Class: Phaser.Sound Class: Phaser.Sound =================== Constructor ----------- ### new Sound(game, key, volume, loop) The Sound class constructor. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | | Reference to the current game instance. | | `key` | string | | | Asset key for the sound. | | `volume` | number | <optional> | 1 | Default value for the volume, between 0 and 1. | | `loop` | boolean | <optional> | false | Whether or not the sound will loop. | Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L17)) Public Properties ----------------- ### allowMultiple : boolean This will allow you to have multiple instances of this Sound playing at once. This is only useful when running under Web Audio, and we recommend you implement a local pooling system to not flood the sound channels. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 144](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L144)) ### autoplay : boolean Boolean indicating whether the sound should start automatically. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 57](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L57)) ### context :AudioContext Reference to the AudioContext instance. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 52](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L52)) ### currentMarker : string The string ID of the currently playing marker, if any. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 121](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L121)) ### currentTime : number The current time the sound is at. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 73](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L73)) ### duration : number The duration of the current sound marker in seconds. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L78)) ### durationMS : number The duration of the current sound marker in ms. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 83](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L83)) ### externalNode : Object If defined this Sound won't connect to the SoundManager master gain node, but will instead connect to externalNode. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 160](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L160)) ### fadeTween : [Phaser.Tween](phaser.tween) The tween that fades the audio, set via Sound.fadeIn and Sound.fadeOut. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 126](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L126)) ### gainNode : Object The gain node in a Web Audio system. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 170](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L170)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 27](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L27)) ### [readonly] isDecoded : boolean Returns true if the sound file has decoded. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 1087](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L1087)) ### [readonly] isDecoding : boolean Returns true if the sound file is still decoding. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 1074](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L1074)) ### isPlaying : boolean true if the sound is currently playing, otherwise false. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 115](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L115)) ### key : string Asset key for the sound. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L37)) ### loop : boolean Whether or not the sound or current sound marker will loop. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L42)) ### markers : Object The sound markers. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 47](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L47)) ### masterGainNode : Object The master gain node in a Web Audio system. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 165](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L165)) ### mute : boolean Gets or sets the muted state of this sound. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 1100](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L1100)) ### name : string Name of the sound. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 32](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L32)) ### onDecoded : [Phaser.Signal](phaser.signal) The onDecoded event is dispatched when the sound has finished decoding (typically for mp3 files) Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 220](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L220)) ### onFadeComplete : [Phaser.Signal](phaser.signal) The onFadeComplete event is dispatched when this sound finishes fading either in or out. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 260](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L260)) ### onLoop : [Phaser.Signal](phaser.signal) The onLoop event is dispatched when this sound loops during playback. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 240](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L240)) ### onMarkerComplete : [Phaser.Signal](phaser.signal) The onMarkerComplete event is dispatched when a marker within this sound completes playback. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 255](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L255)) ### onMute : [Phaser.Signal](phaser.signal) The onMute event is dispatched when this sound is muted. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 250](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L250)) ### onPause : [Phaser.Signal](phaser.signal) The onPause event is dispatched when this sound is paused. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 230](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L230)) ### onPlay : [Phaser.Signal](phaser.signal) The onPlay event is dispatched each time this sound is played. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 225](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L225)) ### onResume : [Phaser.Signal](phaser.signal) The onResume event is dispatched when this sound is resumed from a paused state. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 235](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L235)) ### onStop : [Phaser.Signal](phaser.signal) The onStop event is dispatched when this sound stops playback. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 245](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L245)) ### override : boolean if true when you play this sound it will always start from the beginning. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 138](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L138)) ### paused : boolean true if the sound is paused, otherwise false. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 99](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L99)) ### pausedPosition : number The position the sound had reached when it was paused. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 104](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L104)) ### pausedTime : number The game time at which the sound was paused. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 109](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L109)) ### [readonly] pendingPlayback : boolean true if the sound file is pending playback Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L132)) ### position : number The position of the current sound marker. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 88](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L88)) ### startTime : number The time the Sound starts at (typically 0 unless starting from a marker) Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 68](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L68)) ### stopTime : number The time the sound stopped. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L93)) ### totalDuration : number The total duration of the sound in seconds. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 62](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L62)) ### usingAudioTag : boolean true if the sound is being played via the Audio tag. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 155](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L155)) ### [readonly] usingWebAudio : boolean true if this sound is being played with Web Audio. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 150](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L150)) ### volume : number Gets or sets the volume of this sound, a value between 0 and 1. The value given is clamped to the range 0 to 1. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 1155](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L1155)) Public Methods -------------- ### addMarker(name, start, duration, volume, loop) Adds a marker into the current Sound. A marker is represented by a unique key and a start time and duration. This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `name` | string | | | A unique name for this marker, i.e. 'explosion', 'gunshot', etc. | | `start` | number | | | The start point of this marker in the audio file, given in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. | | `duration` | number | <optional> | 1 | The duration of the marker in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. | | `volume` | number | <optional> | 1 | The volume the sound will play back at, between 0 (silent) and 1 (full volume). | | `loop` | boolean | <optional> | false | Sets if the sound will loop or not. | Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 348](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L348)) ### destroy(remove) Destroys this sound and all associated events and removes it from the SoundManager. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `remove` | boolean | <optional> | true | If true this Sound is automatically removed from the SoundManager. | Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 1035](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L1035)) ### fadeIn(duration, loop, marker) Starts this sound playing (or restarts it if already doing so) and sets the volume to zero. Then increases the volume from 0 to 1 over the duration specified. At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, and the final volume (1) as the second parameter. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `duration` | number | <optional> | 1000 | The time in milliseconds over which the Sound should fade in. | | `loop` | boolean | <optional> | false | Should the Sound be set to loop? Note that this doesn't cause the fade to repeat. | | `marker` | string | <optional> | (current marker) | The marker to start at; defaults to the current (last played) marker. To start playing from the beginning specify specify a marker of `''`. | Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 924](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L924)) ### fadeOut(duration) Decreases the volume of this Sound from its current value to 0 over the duration specified. At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, and the final volume (0) as the second parameter. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `duration` | number | <optional> | 1000 | The time in milliseconds over which the Sound should fade out. | Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 952](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L952)) ### fadeTo(duration, volume) Fades the volume of this Sound from its current value to the given volume over the duration specified. At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, and the final volume (volume) as the second parameter. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `duration` | number | <optional> | 1000 | The time in milliseconds during which the Sound should fade out. | | `volume` | number | <optional> | | The volume which the Sound should fade to. This is a value between 0 and 1. | Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 966](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L966)) ### loopFull(volume) → {[Phaser.Sound](phaser.sound)} Loops this entire sound. If you need to loop a section of it then use Sound.play and the marker and loop parameters. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `volume` | number | <optional> | 1 | Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). | ##### Returns [Phaser.Sound](phaser.sound) - This sound instance. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 492](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L492)) ### <internal> onEndedHandler() Called automatically by the AudioContext when the sound stops playing. Doesn't get called if the sound is set to loop or is a section of an Audio Sprite. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 388](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L388)) ### pause() Pauses the sound. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 763](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L763)) ### play(marker, position, volume, loop, forceRestart) → {[Phaser.Sound](phaser.sound)} Play this sound, or a marked section of it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `marker` | string | <optional> | '' | If you want to play a marker then give the key here, otherwise leave blank to play the full sound. | | `position` | number | <optional> | 0 | The starting position to play the sound from - this is ignored if you provide a marker. | | `volume` | number | <optional> | 1 | Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). | | `loop` | boolean | <optional> | false | Loop when finished playing? If not using a marker / audio sprite the looping will be done via the WebAudio loop property, otherwise it's time based. | | `forceRestart` | boolean | <optional> | true | If the sound is already playing you can set forceRestart to restart it from the beginning. | ##### Returns [Phaser.Sound](phaser.sound) - This sound instance. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 505](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L505)) ### removeMarker(name) Removes a marker from the sound. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `name` | string | The key of the marker to remove. | Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 377](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L377)) ### restart(marker, position, volume, loop) Restart the sound, or a marked section of it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `marker` | string | <optional> | '' | If you want to play a marker then give the key here, otherwise leave blank to play the full sound. | | `position` | number | <optional> | 0 | The starting position to play the sound from - this is ignored if you provide a marker. | | `volume` | number | <optional> | 1 | Volume of the sound you want to play. | | `loop` | boolean | <optional> | false | Loop when it finished playing? | Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 743](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L743)) ### resume() Resumes the sound. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 782](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L782)) ### <internal> soundHasUnlocked(key) Called automatically when this sound is unlocked. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The Phaser.Cache key of the sound file to check for decoding. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 332](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L332)) ### stop() Stop playing this sound. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 858](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L858)) ### <internal> update() Called automatically by Phaser.SoundManager. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 404](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L404)) ### <internal> updateGlobalVolume(globalVolume) Called automatically by SoundManager.volume. Sets the volume of AudioTag Sounds as a percentage of the Global Volume. You should not normally call this directly. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `globalVolume` | float | The global SoundManager volume. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [sound/Sound.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js) ([Line 1013](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/Sound.js#L1013))
programming_docs
phaser Class: Phaser.Physics.Ninja.Tile Class: Phaser.Physics.Ninja.Tile ================================ Constructor ----------- ### new Tile(body, x, y, width, height, type) Ninja Physics Tile constructor. A Tile is defined by its width, height and type. It's type can include slope data, such as 45 degree slopes, or convex slopes. Understand that for any type including a slope (types 2 to 29) the Tile must be SQUARE, i.e. have an equal width and height. Also note that as Tiles are primarily used for levels they have gravity disabled and world bounds collision disabled by default. Note: This class could be massively optimised and reduced in size. I leave that challenge up to you. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `body` | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | | | The body that owns this shape. | | `x` | number | | | The x coordinate to create this shape at. | | `y` | number | | | The y coordinate to create this shape at. | | `width` | number | | | The width of this AABB. | | `height` | number | | | The height of this AABB. | | `type` | number | <optional> | 1 | The type of Ninja shape to create. 1 = AABB, 2 = Circle or 3 = Tile. | Source code: [physics/ninja/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js) ([Line 25](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js#L25)) Public Properties ----------------- ### body ##### Properties: | Name | Type | Description | | --- | --- | --- | | `system` | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | A reference to the body that owns this shape. | Source code: [physics/ninja/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js) ([Line 32](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js#L32)) ### [readonly] bottom : number The bottom value of this Body (same as Body.y + Body.height) Source code: [physics/ninja/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js) ([Line 701](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js#L701)) ### [readonly] height : number The height. Source code: [physics/ninja/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js) ([Line 89](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js#L89)) ### [readonly] id : number The ID of this Tile. Source code: [physics/ninja/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js) ([Line 43](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js#L43)) ### oldpos : [Phaser.Point](phaser.point) The position of this object in the previous update. Source code: [physics/ninja/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js) ([Line 59](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js#L59)) ### pos : [Phaser.Point](phaser.point) The position of this object. Source code: [physics/ninja/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js#L54)) ### [readonly] right : number The right value of this Body (same as Body.x + Body.width) Source code: [physics/ninja/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js) ([Line 714](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js#L714)) ### system : [Phaser.Physics.Ninja](phaser.physics.ninja) A reference to the physics system. Source code: [physics/ninja/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js#L37)) ### [readonly] type : number The type of this Tile. Source code: [physics/ninja/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js#L49)) ### velocity : [Phaser.Point](phaser.point) The velocity of this object. Source code: [physics/ninja/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js) ([Line 94](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js#L94)) ### [readonly] width : number The width. Source code: [physics/ninja/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js) ([Line 83](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js#L83)) ### x : number The x position. Source code: [physics/ninja/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js) ([Line 669](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js#L669)) ### [readonly] xw : number Half the width. Source code: [physics/ninja/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js) ([Line 71](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js#L71)) ### y : number The y position. Source code: [physics/ninja/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js) ([Line 685](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js#L685)) ### [readonly] yw ##### Properties: | Name | Type | Description | | --- | --- | --- | | `xw` | number | Half the height. | Source code: [physics/ninja/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js) ([Line 77](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js#L77)) Public Methods -------------- ### clear() Sets this tile to be empty. Source code: [physics/ninja/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js) ([Line 290](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js#L290)) ### collideWorldBounds() Tiles cannot collide with the world bounds, it's up to you to keep them where you want them. But we need this API stub to satisfy the Body. Source code: [physics/ninja/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js#L153)) ### destroy() Destroys this Tiles reference to Body and System. Source code: [physics/ninja/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js) ([Line 302](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js#L302)) ### integrate() Updates this objects position. Source code: [physics/ninja/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js) ([Line 135](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js#L135)) ### reportCollisionVsWorld(px, py, dx, dy, obj) Process a world collision and apply the resulting forces. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `px` | number | The tangent velocity | | `py` | number | The tangent velocity | | `dx` | number | Collision normal | | `dy` | number | Collision normal | | `obj` | number | Object this Tile collided with | Source code: [physics/ninja/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js) ([Line 194](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js#L194)) ### setType(id) Tiles cannot collide with the world bounds, it's up to you to keep them where you want them. But we need this API stub to satisfy the Body. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `id` | number | The type of Tile this will use, i.e. Phaser.Physics.Ninja.Tile.SLOPE\_45DEGpn, Phaser.Physics.Ninja.Tile.CONVEXpp, etc. | Source code: [physics/ninja/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js) ([Line 268](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/Tile.js#L268)) phaser Class: Phaser.Math Class: Phaser.Math ================== Constructor ----------- ### new Math() A collection of useful mathematical functions. These are normally accessed through `game.math`. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L17)) See * [Phaser.Utils](phaser.utils) * [Phaser.ArrayUtils](phaser.arrayutils) Public Properties ----------------- ### <static> PI2 Twice PI. ##### Properties: | Name | Type | Description | | --- | --- | --- | | `Phaser.Math#PI2` | number | | Default Value * ~6.283 Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L24)) Public Methods -------------- ### angleBetween(x1, y1, x2, y2) → {number} Find the angle of a segment from (x1, y1) -> (x2, y2). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x1` | number | The x coordinate of the first value. | | `y1` | number | The y coordinate of the first value. | | `x2` | number | The x coordinate of the second value. | | `y2` | number | The y coordinate of the second value. | ##### Returns number - The angle, in radians. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 404](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L404)) ### angleBetweenPoints(point1, point2) → {number} Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `point1` | [Phaser.Point](phaser.point) | The first point. | | `point2` | [Phaser.Point](phaser.point) | The second point. | ##### Returns number - The angle between the two points, in radians. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 439](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L439)) ### angleBetweenPointsY(point1, point2) → {number} Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `point1` | [Phaser.Point](phaser.point) | | | `point2` | [Phaser.Point](phaser.point) | | ##### Returns number - The angle, in radians. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 453](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L453)) ### angleBetweenY(x1, y1, x2, y2) → {number} Find the angle of a segment from (x1, y1) -> (x2, y2). The difference between this method and Math.angleBetween is that this assumes the y coordinate travels down the screen. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x1` | number | The x coordinate of the first value. | | `y1` | number | The y coordinate of the first value. | | `x2` | number | The x coordinate of the second value. | | `y2` | number | The y coordinate of the second value. | ##### Returns number - The angle, in radians. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 420](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L420)) ### average() → {number} Averages all values passed to the function and returns the result. ##### Returns number - The average of all given values. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 123](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L123)) ### <internal> bernstein(n, i) → {number} ##### Parameters | Name | Type | Description | | --- | --- | --- | | `n` | number | | | `i` | number | | ##### Returns number - Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 846](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L846)) ### between(min, max) → {number} Returns a number between the `min` and `max` values. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `min` | number | The minimum value. Must be positive, and less than 'max'. | | `max` | number | The maximum value. Must be position, and greater than 'min'. | ##### Returns number - A value between the range min to max. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L26)) ### bezierInterpolation(v, k) → {number} A Bezier Interpolation Method, mostly used by Phaser.Tween. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `v` | Array | The input array of values to interpolate between. | | `k` | number | The percentage of interpolation, between 0 and 1. | ##### Returns number - The interpolated value Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 769](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L769)) ### <internal> catmullRom(p0, p1, p2, p3, t) → {number} Calculates a catmum rom value. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `p0` | number | | | `p1` | number | | | `p2` | number | | | `p3` | number | | | `t` | number | | ##### Returns number - Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 882](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L882)) ### catmullRomInterpolation(v, k) → {number} A Catmull Rom Interpolation Method, mostly used by Phaser.Tween. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `v` | Array | The input array of values to interpolate between. | | `k` | number | The percentage of interpolation, between 0 and 1. | ##### Returns number - The interpolated value Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 791](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L791)) ### ceilTo(value, place, base) → {number} Ceils to some place comparative to a `base`, default is 10 for decimal place. The `place` is represented by the power applied to `base` to get that place. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `value` | number | | | The value to round. | | `place` | number | <optional> | 0 | The place to round to. | | `base` | number | <optional> | 10 | The base to round in. Default is 10 for decimal. | ##### Returns number - The rounded value. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 302](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L302)) ### clamp(v, min, max) → {number} Force a value within the boundaries by clamping it to the range `min`, `max`. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `v` | float | The value to be clamped. | | `min` | float | The minimum bounds. | | `max` | float | The maximum bounds. | ##### Returns number - The clamped value. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 1028](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L1028)) ### clampBottom(x, a) → {number} Clamp `x` to the range `[a, Infinity)`. Roughly the same as `Math.max(x, a)`, except for NaN handling. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | | | `a` | number | | ##### Returns number - Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 1054](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L1054)) ### degToRad(degrees) → {number} Convert degrees to radians. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `degrees` | number | Angle in degrees. | ##### Returns number - Angle in radians. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 1186](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L1186)) ### difference(a, b) → {number} The absolute difference between two values. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | number | The first value to check. | | `b` | number | The second value to check. | ##### Returns number - The absolute difference between the two values. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 902](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L902)) ### distance(x1, y1, x2, y2) → {number} Returns the euclidian distance between the two given set of coordinates. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x1` | number | | | `y1` | number | | | `x2` | number | | | `y2` | number | | ##### Returns number - The distance between the two sets of coordinates. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 970](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L970)) ### distancePow(x1, y1, x2, y2, pow) → {number} Returns the distance between the two given set of coordinates at the power given. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x1` | number | | | | | `y1` | number | | | | | `x2` | number | | | | | `y2` | number | | | | | `pow` | number | <optional> | 2 | | ##### Returns number - The distance between the two sets of coordinates. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 1009](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L1009)) ### distanceSq(x1, y1, x2, y2) → {number} Returns the euclidean distance squared between the two given set of coordinates (cuts out a square root operation before returning). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x1` | number | | | `y1` | number | | | `x2` | number | | | `y2` | number | | ##### Returns number - The distance squared between the two sets of coordinates. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 989](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L989)) ### factorial(value) → {number} ##### Parameters | Name | Type | Description | | --- | --- | --- | | `value` | number | the number you want to evaluate | ##### Returns number - Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 859](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L859)) ### floorTo(value, place, base) → {number} Floors to some place comparative to a `base`, default is 10 for decimal place. The `place` is represented by the power applied to `base` to get that place. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `value` | number | | | The value to round. | | `place` | number | <optional> | 0 | The place to round to. | | `base` | number | <optional> | 10 | The base to round in. Default is 10 for decimal. | ##### Returns number - The rounded value. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 281](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L281)) ### fuzzyCeil(val, epsilon) → {number} Applies a fuzzy ceil to the given value. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `val` | number | | | The value to ceil. | | `epsilon` | number | <optional> | 0.0001 | The epsilon (a small value used in the calculation) | ##### Returns number - ceiling(val-epsilon) Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 91](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L91)) ### fuzzyEqual(a, b, epsilon) → {boolean} Two number are fuzzyEqual if their difference is less than epsilon. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `a` | number | | | The first number to compare. | | `b` | number | | | The second number to compare. | | `epsilon` | number | <optional> | 0.0001 | The epsilon (a small value used in the calculation) | ##### Returns boolean - True if | a-b | <epsilon Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 40](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L40)) ### fuzzyFloor(val, epsilon) → {number} Applies a fuzzy floor to the given value. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `val` | number | | | The value to floor. | | `epsilon` | number | <optional> | 0.0001 | The epsilon (a small value used in the calculation) | ##### Returns number - floor(val+epsilon) Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 107](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L107)) ### fuzzyGreaterThan(a, b, epsilon) → {boolean} `a` is fuzzyGreaterThan `b` if it is more than b - epsilon. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `a` | number | | | The first number to compare. | | `b` | number | | | The second number to compare. | | `epsilon` | number | <optional> | 0.0001 | The epsilon (a small value used in the calculation) | ##### Returns boolean - True if a>b+epsilon Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 74](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L74)) ### fuzzyLessThan(a, b, epsilon) → {boolean} `a` is fuzzyLessThan `b` if it is less than b + epsilon. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `a` | number | | | The first number to compare. | | `b` | number | | | The second number to compare. | | `epsilon` | number | <optional> | 0.0001 | The epsilon (a small value used in the calculation) | ##### Returns boolean - True if a<b+epsilon Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 57](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L57)) ### getShortestAngle(angle1, angle2) → {number} Gets the shortest angle between `angle1` and `angle2`. Both angles must be in the range -180 to 180, which is the same clamped range that `sprite.angle` uses, so you can pass in two sprite angles to this method, and get the shortest angle back between the two of them. The angle returned will be in the same range. If the returned angle is greater than 0 then it's a counter-clockwise rotation, if < 0 then it's a clockwise rotation. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `angle1` | number | The first angle. In the range -180 to 180. | | `angle2` | number | The second angle. In the range -180 to 180. | ##### Returns number - The shortest angle, in degrees. If greater than zero it's a counter-clockwise rotation. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 374](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L374)) ### isEven(n) → {boolean} Returns true if the number given is even. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `n` | integer | The number to check. | ##### Returns boolean - True if the given number is even. False if the given number is odd. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 589](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L589)) ### isOdd(n) → {boolean} Returns true if the number given is odd. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `n` | integer | The number to check. | ##### Returns boolean - True if the given number is odd. False if the given number is even. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 575](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L575)) ### linear(p0, p1, t) → {number} Calculates a linear (interpolation) value over t. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `p0` | number | | | `p1` | number | | | `t` | number | A value between 0 and 1. | ##### Returns number - Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 831](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L831)) ### linearInterpolation(v, k) → {number} A Linear Interpolation Method, mostly used by Phaser.Tween. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `v` | Array | The input array of values to interpolate between. | | `k` | number | The percentage of interpolation, between 0 and 1. | ##### Returns number - The interpolated value Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 741](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L741)) ### mapLinear(x, a1, a2, b1, b2) → {number} Linear mapping from range to range ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The value to map | | `a1` | number | First endpoint of the range | | `a2` | number | Final endpoint of the range | | `b1` | number | First endpoint of the range | | `b2` | number | Final endpoint of the range | ##### Returns number - Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 1085](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L1085)) ### max() → {number} Variation of Math.max that can be passed either an array of numbers or the numbers as parameters. Prefer the standard `Math.max` function when appropriate. ##### Returns number - The largest value from those given. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 635](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L635)) See * <http://jsperf.com/math-s-min-max-vs-homemade> ### maxAdd(value, amount, max) → {number} Adds the given amount to the value, but never lets the value go over the specified maximum. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `value` | number | The value to add the amount to. | | `amount` | number | The amount to add to the value. | | `max` | number | The maximum the value is allowed to be. | ##### Returns number - The new value. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 491](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L491)) ### maxProperty() → {number} Variation of Math.max that can be passed a property and either an array of objects or the objects as parameters. It will find the largest matching property value from the given objects. ##### Returns number - The largest value from those given. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 697](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L697)) ### min() → {number} Variation of Math.min that can be passed either an array of numbers or the numbers as parameters. Prefer the standard `Math.min` function when appropriate. ##### Returns number - The lowest value from those given. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 603](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L603)) See * <http://jsperf.com/math-s-min-max-vs-homemade> ### minProperty() → {number} Variation of Math.min that can be passed a property and either an array of objects or the objects as parameters. It will find the lowest matching property value from the given objects. ##### Returns number - The lowest value from those given. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 667](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L667)) ### minSub(value, amount, min) → {number} Subtracts the given amount from the value, but never lets the value go below the specified minimum. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `value` | number | The base value. | | `amount` | number | The amount to subtract from the base value. | | `min` | number | The minimum the value is allowed to be. | ##### Returns number - The new value. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 506](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L506)) ### normalizeAngle(angleRad) → {number} Normalizes an angle to the [0,2pi) range. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `angleRad` | number | The angle to normalize, in radians. | ##### Returns number - The angle, fit within the [0,2pi] range, in radians. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 478](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L478)) ### percent(a, b, base) → {number} Work out what percentage value `a` is of value `b` using the given base. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `a` | number | | | The value to work out the percentage for. | | `b` | number | | | The value you wish to get the percentage of. | | `base` | number | <optional> | 0 | The base value. | ##### Returns number - The percentage a is of b, between 0 and 1. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 1153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L1153)) ### radToDeg(radians) → {number} Convert radians to degrees. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `radians` | number | Angle in radians. | ##### Returns number - Angle in degrees Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 1197](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L1197)) ### reverseAngle(angleRad) → {number} Reverses an angle. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `angleRad` | number | The angle to reverse, in radians. | ##### Returns number - The reverse angle, in radians. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 466](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L466)) ### rotateToAngle(currentAngle, targetAngle, lerp) → {number} Rotates currentAngle towards targetAngle, taking the shortest rotation distance. The lerp argument is the amount to rotate by in this call. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `currentAngle` | number | | | The current angle, in radians. | | `targetAngle` | number | | | The target angle to rotate to, in radians. | | `lerp` | number | <optional> | 0.05 | The lerp value to add to the current angle. | ##### Returns number - The adjusted angle. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 323](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L323)) ### roundAwayFromZero(value) → {integer} Round to the next whole number *away* from zero. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `value` | number | Any number. | ##### Returns integer - The rounded value of that number. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 916](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L916)) ### roundTo(value, place, base) → {number} Round to some place comparative to a `base`, default is 10 for decimal place. The `place` is represented by the power applied to `base` to get that place. ``` e.g. 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011 roundTo(2000/7,3) === 0 roundTo(2000/7,2) == 300 roundTo(2000/7,1) == 290 roundTo(2000/7,0) == 286 roundTo(2000/7,-1) == 285.7 roundTo(2000/7,-2) == 285.71 roundTo(2000/7,-3) == 285.714 roundTo(2000/7,-4) == 285.7143 roundTo(2000/7,-5) == 285.71429 roundTo(2000/7,3,2) == 288 -- 100100000 roundTo(2000/7,2,2) == 284 -- 100011100 roundTo(2000/7,1,2) == 286 -- 100011110 roundTo(2000/7,0,2) == 286 -- 100011110 roundTo(2000/7,-1,2) == 285.5 -- 100011101.1 roundTo(2000/7,-2,2) == 285.75 -- 100011101.11 roundTo(2000/7,-3,2) == 285.75 -- 100011101.11 roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011 roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111 ``` Note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed because we are rounding 100011.1011011011011011 which rounds up. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `value` | number | | | The value to round. | | `place` | number | <optional> | 0 | The place to round to. | | `base` | number | <optional> | 10 | The base to round in. Default is 10 for decimal. | ##### Returns number - The rounded value. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 235](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L235)) ### shear(n) → {number} ##### Parameters | Name | Type | Description | | --- | --- | --- | | `n` | number | | ##### Returns number - n mod 1 Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 144](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L144)) ### sign(x) → {integer} A value representing the sign of the value: -1 for negative, +1 for positive, 0 if value is 0. This works differently from `Math.sign` for values of NaN and -0, etc. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | | ##### Returns integer - An integer in {-1, 0, 1} Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 1138](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L1138)) ### sinCosGenerator(length, sinAmplitude, cosAmplitude, frequency) → {Object} Generate a sine and cosine table simultaneously and extremely quickly. The parameters allow you to specify the length, amplitude and frequency of the wave. This generator is fast enough to be used in real-time. Code based on research by Franky of scene.at ##### Parameters | Name | Type | Description | | --- | --- | --- | | `length` | number | The length of the wave | | `sinAmplitude` | number | The amplitude to apply to the sine table (default 1.0) if you need values between say -+ 125 then give 125 as the value | | `cosAmplitude` | number | The amplitude to apply to the cosine table (default 1.0) if you need values between say -+ 125 then give 125 as the value | | `frequency` | number | The frequency of the sine and cosine table data | ##### Returns Object - Returns the table data. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 930](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L930)) ### smootherstep(x, min, max) → {float} Smootherstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | float | The input value. | | `min` | float | The left edge. Should be smaller than the right edge. | | `max` | float | The right edge. | ##### Returns float - A value between 0 and 1. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 1121](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L1121)) ### smoothstep(x, min, max) → {float} Smoothstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | float | The input value. | | `min` | float | The left edge. Should be smaller than the right edge. | | `max` | float | The right edge. | ##### Returns float - A value between 0 and 1. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 1102](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L1102)) ### snapTo(input, gap, start) → {number} Snap a value to nearest grid slice, using rounding. Example: if you have an interval gap of 5 and a position of 12... you will snap to 10 whereas 14 will snap to 15. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `input` | number | | | The value to snap. | | `gap` | number | | | The interval gap of the grid. | | `start` | number | <optional> | 0 | Optional starting offset for gap. | ##### Returns number - The snapped value. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 155](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L155)) ### snapToCeil(input, gap, start) → {number} Snap a value to nearest grid slice, using ceil. Example: if you have an interval gap of 5 and a position of 12... you will snap to 15. As will 14 will snap to 15... but 16 will snap to 20. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `input` | number | | | The value to snap. | | `gap` | number | | | The interval gap of the grid. | | `start` | number | <optional> | 0 | Optional starting offset for gap. | ##### Returns number - The snapped value. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 208](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L208)) ### snapToFloor(input, gap, start) → {number} Snap a value to nearest grid slice, using floor. Example: if you have an interval gap of 5 and a position of 12... you will snap to 10. As will 14 snap to 10... but 16 will snap to 15. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `input` | number | | | The value to snap. | | `gap` | number | | | The interval gap of the grid. | | `start` | number | <optional> | 0 | Optional starting offset for gap. | ##### Returns number - The snapped value. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 181](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L181)) ### within(a, b, tolerance) → {boolean} Checks if two values are within the given tolerance of each other. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | number | The first number to check | | `b` | number | The second number to check | | `tolerance` | number | The tolerance. Anything equal to or less than this is considered within the range. | ##### Returns boolean - True if a is <= tolerance of b. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 1069](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L1069)) See * Phaser.Math.fuzzyEqual ### wrap(value, min, max) → {number} Ensures that the value always stays between min and max, by wrapping the value around. If `max` is not larger than `min` the result is 0. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `value` | number | The value to wrap. | | `min` | number | The minimum the value is allowed to be. | | `max` | number | The maximum the value is allowed to be, should be larger than `min`. | ##### Returns number - The wrapped value. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 521](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L521)) ### wrapAngle(angle, radians) → {number} Keeps an angle value between -180 and +180; or -PI and PI if radians. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `angle` | number | | | The angle value to wrap | | `radians` | boolean | <optional> | false | Set to `true` if the angle is given in radians, otherwise degrees is expected. | ##### Returns number - The new angle value; will be the same as the input angle if it was within bounds. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 727](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L727)) ### wrapValue(value, amount, max) → {number} Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around. Values *must* be positive integers, and are passed through Math.abs. See [Phaser.Math#wrap](phaser.math#wrap) for an alternative. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `value` | number | The value to add the amount to. | | `amount` | number | The amount to add to the value. | | `max` | number | The maximum the value is allowed to be. | ##### Returns number - The wrapped value. Source code: [math/Math.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js) ([Line 552](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/Math.js#L552))
programming_docs
phaser Class: Phaser.Group Class: Phaser.Group =================== Constructor ----------- ### new Group(game, parent, name, addToStage, enableBody, physicsBodyType) A Group is a container for [display objects](global#DisplayObject) including [Sprites](phaser.sprite) and [Images](phaser.image). Groups form the logical tree structure of the display/scene graph where local transformations are applied to children. For instance, all children are also moved/rotated/scaled when the group is moved/rotated/scaled. In addition, Groups provides support for fast pooling and object recycling. Groups are also display objects and can be nested as children within other Groups. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | | A reference to the currently running game. | | `parent` | [DisplayObject](global#DisplayObject) | null | <optional> | (game world) | The parent Group (or other [DisplayObject](global#DisplayObject)) that this group will be added to. If undefined/unspecified the Group will be added to the [Game World](phaser.game#world); if null the Group will not be added to any parent. | | `name` | string | <optional> | 'group' | A name for this group. Not used internally but useful for debugging. | | `addToStage` | boolean | <optional> | false | If true this group will be added directly to the Game.Stage instead of Game.World. | | `enableBody` | boolean | <optional> | false | If true all Sprites created with #create or #createMulitple will have a physics body created on them. Change the body type with #physicsBodyType. | | `physicsBodyType` | integer | <optional> | 0 | The physics body type to use when physics bodies are automatically added. See #physicsBodyType for values. | Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 27](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L27)) Extends ------- * [PIXI.DisplayObjectContainer](pixi.displayobjectcontainer) Public Properties ----------------- ### [static] RETURN\_ALL : integer A returnType value, as specified in [iterate](phaser.group#iterate) eg. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 325](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L325)) ### [static] RETURN\_CHILD : integer A returnType value, as specified in [iterate](phaser.group#iterate) eg. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 318](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L318)) ### [static] RETURN\_NONE : integer A returnType value, as specified in [iterate](phaser.group#iterate) eg. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 304](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L304)) ### [static] RETURN\_TOTAL : integer A returnType value, as specified in [iterate](phaser.group#iterate) eg. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 311](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L311)) ### [static] SORT\_ASCENDING : integer A sort ordering value, as specified in [sort](phaser.group#sort) eg. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 332](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L332)) ### [static] SORT\_DESCENDING : integer A sort ordering value, as specified in [sort](phaser.group#sort) eg. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 339](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L339)) ### alive : boolean The alive property is useful for Groups that are children of other Groups and need to be included/excluded in checks like forEachAlive. Default Value * true Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L93)) ### alpha : number The alpha value of the group container. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 3003](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L3003)) ### angle : number The angle of rotation of the group container, in degrees. This adjusts the group itself by modifying its local rotation transform. This has no impact on the rotation/angle properties of the children, but it will update their worldTransform and on-screen orientation and position. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2682](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2682)) ### bottom : number The bottom coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2845](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2845)) ### cameraOffset : [Phaser.Point](phaser.point) If this object is [fixedToCamera](phaser.group#fixedToCamera) then this stores the x/y position offset relative to the top-left of the camera view. If the parent of this Group is also `fixedToCamera` then the offset here is in addition to that and should typically be disabled. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 272](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L272)) ### centerX : number The center x coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2705](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2705)) ### centerY : number The center y coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2733](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2733)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### classType : Object The type of objects that will be created when using [create](phaser.group#create) or [createMultiple](phaser.group#createMultiple). Any object may be used but it should extend either Sprite or Image and accept the same constructor arguments: when a new object is created it is passed the following parameters to its constructor: `(game, x, y, key, frame)`. Default Value * [Phaser.Sprite](phaser.sprite) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 130](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L130)) ### cursor : [DisplayObject](global#DisplayObject) The current display object that the group cursor is pointing to, if any. (Can be set manually.) The cursor is a way to iterate through the children in a Group using [next](phaser.group#next) and [previous](phaser.group#previous). Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 138](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L138)) ### [readonly] cursorIndex : integer The current index of the Group cursor. Advance it with Group.next. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 255](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L255)) ### enableBody : boolean If true all Sprites created by, or added to this group, will have a physics body enabled on them. If there are children already in the Group at the time you set this property, they are not changed. The default body type is controlled with [physicsBodyType](phaser.group#physicsBodyType). Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 208](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L208)) ### enableBodyDebug : boolean If true when a physics body is created (via [enableBody](phaser.group#enableBody)) it will create a physics debug object as well. This only works for P2 bodies. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L217)) ### exists : boolean If exists is true the group is updated, otherwise it is skipped. Default Value * true Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 100](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L100)) ### fixedToCamera : boolean A Group that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Group.cameraOffset. Note that the cameraOffset values are in addition to any parent in the display list. So if this Group was in a Group that has x: 200, then this will be added to the cameraOffset.x Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 265](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L265)) ### <internal> game : [Phaser.Game](phaser.game) A reference to the currently running Game. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L38)) ### hash :array The hash array is an array belonging to this Group into which you can add any of its children via Group.addToHash and Group.removeFromHash. Only children of this Group can be added to and removed from the hash. This hash is used automatically by Phaser Arcade Physics in order to perform non z-index based destructive sorting. However if you don't use Arcade Physics, or this isn't a physics enabled Group, then you can use the hash to perform your own sorting and filtering of Group children without touching their z-index (and therefore display draw order) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 285](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L285)) ### height : number The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#height](pixi.displayobjectcontainer#height) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 600](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L600)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### ignoreDestroy : boolean A group with `ignoreDestroy` set to `true` ignores all calls to its `destroy` method. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 107](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L107)) ### inputEnableChildren : boolean A Group with `inputEnableChildren` set to `true` will automatically call `inputEnabled = true` on any children *added* to, or *created by*, this Group. If there are children already in the Group at the time you set this property, they are not changed. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 149](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L149)) ### left : number The left coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2761](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2761)) ### [readonly] length : integer Total number of children in this group, regardless of exists/alive status. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2665](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2665)) ### name : string A name for this group. Not used internally but useful for debugging. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L49)) ### onChildInputDown : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputDown signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and a reference to the Pointer that caused it. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 161](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L161)) ### onChildInputOut : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputOut signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and a reference to the Pointer that caused it. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 198](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L198)) ### onChildInputOver : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputOver signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and a reference to the Pointer that caused it. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 186](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L186)) ### onChildInputUp : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputUp signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 3 arguments: A reference to the Sprite that triggered the signal, a reference to the Pointer that caused it, and a boolean value `isOver` that tells you if the Pointer is still over the Sprite or not. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 174](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L174)) ### onDestroy : [Phaser.Signal](phaser.signal) This signal is dispatched when the group is destroyed. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 249](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L249)) ### pendingDestroy : boolean A Group is that has `pendingDestroy` set to `true` is flagged to have its destroy method called on the next logic update. You can set it directly to flag the Group to be destroyed on its next update. This is extremely useful if you wish to destroy a Group from within one of its own callbacks or a callback of one of its children. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 119](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L119)) ### physicsBodyType : integer If [enableBody](phaser.group#enableBody) is true this is the type of physics body that is created on new Sprites. The valid values are [Phaser.Physics.ARCADE](phaser.physics#.ARCADE), [Phaser.Physics.P2JS](phaser.physics#.P2JS), [Phaser.Physics.NINJA](phaser.physics#.NINJA), etc. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 225](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L225)) ### physicsSortDirection : integer If this Group contains Arcade Physics Sprites you can set a custom sort direction via this property. It should be set to one of the Phaser.Physics.Arcade sort direction constants: Phaser.Physics.Arcade.SORT\_NONE Phaser.Physics.Arcade.LEFT\_RIGHT Phaser.Physics.Arcade.RIGHT\_LEFT Phaser.Physics.Arcade.TOP\_BOTTOM Phaser.Physics.Arcade.BOTTOM\_TOP If set to `null` the Group will use whatever Phaser.Physics.Arcade.sortDirection is set to. This is the default behavior. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 243](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L243)) ### [readonly] physicsType : number The const physics body type of this object. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L86)) ### right : number The right coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2789](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2789)) ### rotation : number The angle of rotation of the group container, in radians. This will adjust the group container itself by modifying its rotation. This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2987](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2987)) ### top : number The top coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2817](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2817)) ### [readonly] total : integer Total number of existing children in the group. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2648](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2648)) ### <internal> type : integer Internal Phaser Type value. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 80](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L80)) ### visible : boolean The visible state of the group. Non-visible Groups and all of their children are not rendered. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2996](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2996)) ### width : number The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#width](pixi.displayobjectcontainer#width) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 571](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L571)) ### x : number The x coordinate of the group container. You can adjust the group container itself by modifying its coordinates. This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2969](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2969)) ### y : number The y coordinate of the group container. You can adjust the group container itself by modifying its coordinates. This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2978](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2978)) ### [readonly] z : integer The z-depth value of this object within its parent container/Group - the World is a Group as well. This value must be unique for each child in a Group. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 57](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L57)) Public Methods -------------- ### add(child, silent, index) → {[DisplayObject](global#DisplayObject)} Adds an existing object as the top child in this group. The child is automatically added to the top of the group, and is displayed above every previous child. Or if the *optional* index is specified, the child is added at the location specified by the index value, this allows you to control child ordering. If the child was already in this Group, it is simply returned, and nothing else happens to it. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. Use [addAt](phaser.group#addAt) to control where a child is added. Use [create](phaser.group#create) to create and add a new child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | | | The display object to add as a child. | | `silent` | boolean | <optional> | false | If true the child will not dispatch the `onAddedToGroup` event. | | `index` | integer | <optional> | | The index within the group to insert the child to. Where 0 is the bottom of the Group. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added to the group. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 341](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L341)) ### addAll(property, amount, checkAlive, checkVisible) Adds the amount to the given property on all children in this group. `Group.addAll('x', 10)` will add 10 to the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to increment, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1386](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1386)) ### addAt(child, index, silent) → {[DisplayObject](global#DisplayObject)} Adds an existing object to this group. The child is added to the group at the location specified by the index value, this allows you to control child ordering. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | | | The display object to add as a child. | | `index` | integer | <optional> | 0 | The index within the group to insert the child to. | | `silent` | boolean | <optional> | false | If true the child will not dispatch the `onAddedToGroup` event. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added to the group. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 418](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L418)) ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### addMultiple(children, silent) → {Array.<[DisplayObject](global#DisplayObject)> | [Phaser.Group](phaser.group)} Adds an array of existing Display Objects to this Group. The Display Objects are automatically added to the top of this Group, and will render on-top of everything already in this Group. As well as an array you can also pass another Group as the first argument. In this case all of the children from that Group will be removed from it and added into this Group. If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `children` | Array.<[DisplayObject](global#DisplayObject)> | [Phaser.Group](phaser.group) | | | An array of display objects or a Phaser.Group. If a Group is given then *all* children will be moved from it. | | `silent` | boolean | <optional> | false | If true the children will not dispatch the `onAddedToGroup` event. | ##### Returns Array.<[DisplayObject](global#DisplayObject)> | [Phaser.Group](phaser.group) - The array of children or Group of children that were added to this Group. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 489](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L489)) ### addToHash(child) → {boolean} Adds a child of this Group into the hash array. This call will return false if the child is not a child of this Group, or is already in the hash. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The display object to add to this Groups hash. Must be a member of this Group already and not present in the hash. | ##### Returns boolean - True if the child was successfully added to the hash, otherwise false. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 439](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L439)) ### align(width, height, cellWidth, cellHeight, position, offset) → {boolean} This method iterates through all children in the Group (regardless if they are visible or exist) and then changes their position so they are arranged in a Grid formation. Children must have the `alignTo` method in order to be positioned by this call. All default Phaser Game Objects have this. The grid dimensions are determined by the first four arguments. The `width` and `height` arguments relate to the width and height of the grid respectively. For example if the Group had 100 children in it: `Group.align(10, 10, 32, 32)` This will align all of the children into a grid formation of 10x10, using 32 pixels per grid cell. If you want a wider grid, you could do: `Group.align(25, 4, 32, 32)` This will align the children into a grid of 25x4, again using 32 pixels per grid cell. You can choose to set *either* the `width` or `height` value to -1. Doing so tells the method to keep on aligning children until there are no children left. For example if this Group had 48 children in it, the following: `Group.align(-1, 8, 32, 32)` ... will align the children so that there are 8 children vertically (the second argument), and each row will contain 6 sprites, except the last one, which will contain 5 (totaling 48) You can also do: `Group.align(10, -1, 32, 32)` In this case it will create a grid 10 wide, and as tall as it needs to be in order to fit all of the children in. The `position` property allows you to control where in each grid cell the child is positioned. This is a constant and can be one of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. The final argument; `offset` lets you start the alignment from a specific child index. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `width` | integer | | | The width of the grid in items (not pixels). Set to -1 for a dynamic width. If -1 then you must set an explicit height value. | | `height` | integer | | | The height of the grid in items (not pixels). Set to -1 for a dynamic height. If -1 then you must set an explicit width value. | | `cellWidth` | integer | | | The width of each grid cell, in pixels. | | `cellHeight` | integer | | | The height of each grid cell, in pixels. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offset` | integer | <optional> | 0 | Optional index to start the alignment from. Defaults to zero, the first child in the Group, but can be set to any valid child index value. | ##### Returns boolean - True if the Group children were aligned, otherwise false. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 682](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L682)) ### alignIn(container, position, offsetX, offsetY) → {[Phaser.Group](phaser.group)} Aligns this Group within another Game Object, or Rectangle, known as the 'container', to one of 9 possible positions. The container must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Groups within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Group to another Game Object does **not** make it a child of the container. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. Groups are placed in such a way that their *bounds* align with the container, taking into consideration rotation and scale of its children. This allows you to neatly align Groups, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Group. For example: `group.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `container` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns [Phaser.Group](phaser.group) - This Group. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2873](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2873)) ### alignTo(parent, position, offsetX, offsetY) → {[Phaser.Group](phaser.group)} Aligns this Group to the side of another Game Object, or Rectangle, known as the 'parent', in one of 11 possible positions. The parent must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Groups within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Group to another Game Object does **not** make it a child of the parent. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. Groups are placed in such a way that their *bounds* align with the parent, taking into consideration rotation and scale of the children. This allows you to neatly align Groups, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Group. For example: `group.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns [Phaser.Group](phaser.group) - This Group. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2915](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2915)) ### <internal> ascendingSortHandler(a, b) An internal helper function for the sort process. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | object | The first object being sorted. | | `b` | object | The second object being sorted. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1919](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1919)) ### bringToTop(child) → {any} Brings the given child to the top of this group so it renders above all other children. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to bring to the top of this group. | ##### Returns any - The child that was moved. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 907](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L907)) ### callAll(method, context, args) Calls a function, specified by name, on all on children. The function is called for all children regardless if they are dead or alive (see callAllExists for different options). After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `method` | string | | | Name of the function on the child to call. Deep property lookup is supported. | | `context` | string | <optional> | null | A string containing the context under which the method will be executed. Set to null to default to the child. | | `args` | any | <repeatable> | | Additional parameters that will be passed to the method. | Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1538](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1538)) ### callAllExists(callback, existsValue, parameter) Calls a function, specified by name, on all children in the group who exist (or do not exist). After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `callback` | string | | Name of the function on the children to call. | | `existsValue` | boolean | | Only children with exists=existsValue will be called. | | `parameter` | any | <repeatable> | Additional parameters that will be passed to the callback. | Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1454](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1454)) ### <internal> callbackFromArray(child, callback, length) Returns a reference to a function that exists on a child of the group based on the given callback array. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | object | The object to inspect. | | `callback` | array | The array of function names. | | `length` | integer | The size of the array (pre-calculated in callAll). | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1488](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1488)) ### checkAll(key, value, checkAlive, checkVisible, force) Quickly check that the same property across all children of this group is equal to the given value. This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be checked. | | `checkAlive` | boolean | <optional> | false | If set then only children with alive=true will be checked. This includes any Groups that are children. | | `checkVisible` | boolean | <optional> | false | If set then only children with visible=true will be checked. This includes any Groups that are children. | | `force` | boolean | <optional> | false | If `force` is true then the property will be checked on the child regardless if it already exists or not. If true and the property doesn't exist, false will be returned. | Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1353](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1353)) ### checkProperty(child, key, value, force) → {boolean} Checks a property for the given value on the child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | any | | | The child to check the property value on. | | `key` | array | | | An array of strings that make up the property that will be set. | | `value` | any | | | The value that will be checked. | | `force` | boolean | <optional> | false | If `force` is true then the property will be checked on the child regardless if it already exists or not. If true and the property doesn't exist, false will be returned. | ##### Returns boolean - True if the property was was equal to value, false if not. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1217)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### countDead() → {integer} Get the number of dead children in this group. ##### Returns integer - The number of children flagged as dead. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2338](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2338)) ### countLiving() → {integer} Get the number of living children in this group. ##### Returns integer - The number of children flagged as alive. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2326](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2326)) ### create(x, y, key, frame, exists, index) → {[DisplayObject](global#DisplayObject)} Creates a new Phaser.Sprite object and adds it to the top of this group. Use [classType](phaser.group#classType) to change the type of object created. The child is automatically added to the top of the group, and is displayed above every previous child. Or if the *optional* index is specified, the child is added at the location specified by the index value, this allows you to control child ordering. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate to display the newly created Sprite at. The value is in relation to the group.x point. | | `y` | number | | | The y coordinate to display the newly created Sprite at. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | | `exists` | boolean | <optional> | true | The default exists state of the Sprite. | | `index` | integer | <optional> | | The index within the group to insert the child to. Where 0 is the bottom of the Group. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was created: will be a [Phaser.Sprite](phaser.sprite) unless #classType has been changed. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 544](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L544)) ### createMultiple(quantity, key, frame, exists) → {array} Creates multiple Phaser.Sprite objects and adds them to the top of this Group. This method is useful if you need to quickly generate a pool of sprites, such as bullets. Use [classType](phaser.group#classType) to change the type of object created. You can provide an array as the `key` and / or `frame` arguments. When you do this it will create `quantity` Sprites for every key (and frame) in the arrays. For example: `createMultiple(25, ['ball', 'carrot'])` In the above code there are 2 keys (ball and carrot) which means that 50 sprites will be created in total, 25 of each. You can also have the `frame` as an array: `createMultiple(5, 'bricks', [0, 1, 2, 3])` In the above there is one key (bricks), which is a sprite sheet. The frames array tells this method to use frames 0, 1, 2 and 3. So in total it will create 20 sprites, because the quantity was set to 5, so that is 5 brick sprites of frame 0, 5 brick sprites with frame 1, and so on. If you set both the key and frame arguments to be arrays then understand it will create a total quantity of sprites equal to the size of both arrays times each other. I.e.: `createMultiple(20, ['diamonds', 'balls'], [0, 1, 2])` The above will create 20 'diamonds' of frame 0, 20 with frame 1 and 20 with frame 2. It will then create 20 'balls' of frame 0, 20 with frame 1 and 20 with frame 2. In total it will have created 120 sprites. By default the Sprites will have their `exists` property set to `false`, and they will be positioned at 0x0, relative to the `Group.x / y` values. If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `quantity` | integer | | | The number of Sprites to create. | | `key` | string | array | | | The Cache key of the image that the Sprites will use. Or an Array of keys. See the description for details on how the quantity applies when arrays are used. | | `frame` | integer | string | array | <optional> | 0 | If the Sprite image contains multiple frames you can specify which one to use here. Or an Array of frames. See the description for details on how the quantity applies when arrays are used. | | `exists` | boolean | <optional> | false | The default exists state of the Sprite. | ##### Returns array - An array containing all of the Sprites that were created. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 581](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L581)) ### customSort(sortHandler, context) Sort the children in the group according to custom sort function. The `sortHandler` is provided the two parameters: the two children involved in the comparison (a and b). It should return -1 if `a > b`, 1 if `a < b` or 0 if `a === b`. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `sortHandler` | function | | The custom sort function. | | `context` | object | <optional> | The context in which the sortHandler is called. | Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1895](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1895)) ### <internal> descendingSortHandler(a, b) An internal helper function for the sort process. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | object | The first object being sorted. | | `b` | object | The second object being sorted. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1951](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1951)) ### destroy(destroyChildren, soft) Destroys this group. Removes all children, then removes this group from its parent and nulls references. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroyChildren` | boolean | <optional> | true | If true `destroy` will be invoked on each removed child. | | `soft` | boolean | <optional> | false | A 'soft destroy' (set to true) doesn't remove this group from its parent or null the game reference. Set to false and it does. | Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2611](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2611)) ### divideAll(property, amount, checkAlive, checkVisible) Divides the given property by the amount on all children in this group. `Group.divideAll('x', 2)` will half the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to divide, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1437](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1437)) ### filter(predicate, checkExists) → {[Phaser.ArraySet](phaser.arrayset)} Find children matching a certain predicate. For example: ``` var healthyList = Group.filter(function(child, index, children) { return child.health > 10 ? true : false; }, true); healthyList.callAll('attack'); ``` Note: Currently this will skip any children which are Groups themselves. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `predicate` | function | | | The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, the index as the second, and the entire child array as the third | | `checkExists` | boolean | <optional> | false | If true, only existing can be selected; otherwise all children can be selected and will be passed to the predicate. | ##### Returns [Phaser.ArraySet](phaser.arrayset) - Returns an array list containing all the children that the predicate returned true for Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1677](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1677)) ### forEach(callback, callbackContext, checkExists, args) Call a function on each child in this group. Additional arguments for the callback can be specified after the `checkExists` parameter. For example, ``` Group.forEach(awardBonusGold, this, true, 100, 500) ``` would invoke `awardBonusGold` function with the parameters `(child, 100, 500)`. Note: This check will skip any children which are Groups themselves. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `checkExists` | boolean | <optional> | false | If set only children matching for which `exists` is true will be passed to the callback, otherwise all children will be passed. | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1717](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1717)) ### forEachAlive(callback, callbackContext, args) Call a function on each alive child in this group. See [forEach](phaser.group#forEach) for details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1799](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1799)) ### forEachDead(callback, callbackContext, args) Call a function on each dead child in this group. See [forEach](phaser.group#forEach) for details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1827](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1827)) ### forEachExists(callback, callbackContext, args) Call a function on each existing child in this group. See [forEach](phaser.group#forEach) for details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1771](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1771)) ### getAll(property, value, startIndex, endIndex) → {any} Returns all children in this Group. You can optionally specify a matching criteria using the `property` and `value` arguments. For example: `getAll('exists', true)` would return only children that have their exists property set. Optionally you can specify a start and end index. For example if this Group had 100 children, and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only the first 50 children in the Group. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `property` | string | <optional> | | An optional property to test against the value argument. | | `value` | any | <optional> | | If property is set then Child.property must strictly equal this value to be included in the results. | | `startIndex` | integer | <optional> | 0 | The first child index to start the search from. | | `endIndex` | integer | <optional> | | The last child index to search up until. | ##### Returns any - A random existing child of this Group. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2392](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2392)) ### getAt(index) → {[DisplayObject](global#DisplayObject) | integer} Returns the child found at the given index within this group. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | integer | The index to return the child from. | ##### Returns [DisplayObject](global#DisplayObject) | integer - The child that was found at the given index, or -1 for an invalid index. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 524](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L524)) ### getBottom() → {any} Returns the child at the bottom of this group. The bottom child the child being displayed (rendered) below every other child. ##### Returns any - The child at the bottom of the Group. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2221](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2221)) ### getBounds(targetCoordinateSpace) → {Rectangle} Retrieves the global bounds of the displayObjectContainer as a rectangle. The bounds calculation takes all visible children into consideration. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `targetCoordinateSpace` | PIXIDisplayObject | PIXIMatrix | <optional> | Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object. | ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.DisplayObjectContainer#getBounds](pixi.displayobjectcontainer#getBounds) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 280](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L280)) ### getByName(name) → {any} Searches the Group for the first instance of a child with the `name` property matching the given argument. Should more than one child have the same name only the first instance is returned. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `name` | string | The name to search for. | ##### Returns any - The first child with a matching name, or null if none were found. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1042](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1042)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getClosestTo(object, callback, callbackContext) → {any} Get the closest child to given Object, with optional callback to filter children. This can be a Sprite, Group, Image or any object with public x and y properties. 'close' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. You can use the optional `callback` argument to apply your own filter to the distance checks. If the child is closer then the previous child, it will be sent to `callback` as the first argument, with the distance as the second. The callback should return `true` if it passes your filtering criteria, otherwise it should return `false`. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `object` | any | | The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. | | `callback` | function | <optional> | The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. | | `callbackContext` | object | <optional> | The context in which the function should be called (usually 'this'). | ##### Returns any - The child closest to given object, or `null` if no child was found. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2238](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2238)) ### getFirstAlive(createIfNull, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Get the first child that is alive (`child.alive === true`). This is handy for choosing a squad leader, etc. You can use the optional argument `createIfNull` to create a new Game Object if no alive ones were found in this Group. It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `createIfNull` | boolean | <optional> | false | If `true` and no alive children are found a new one is created. | | `x` | number | <optional> | | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The alive dead child, or `null` if none found and `createIfNull` was false. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2105](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2105)) ### getFirstDead(createIfNull, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Get the first child that is dead (`child.alive === false`). This is handy for checking if everything has been wiped out and adding to the pool as needed. You can use the optional argument `createIfNull` to create a new Game Object if no dead ones were found in this Group. It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `createIfNull` | boolean | <optional> | false | If `true` and no dead children are found a new one is created. | | `x` | number | <optional> | | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The first dead child, or `null` if none found and `createIfNull` was false. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2135](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2135)) ### getFirstExists(exists, createIfNull, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Get the first display object that exists, or doesn't exist. You can use the optional argument `createIfNull` to create a new Game Object if none matching your exists argument were found in this Group. It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `exists` | boolean | <optional> | true | If true, find the first existing child; otherwise find the first non-existing child. | | `createIfNull` | boolean | <optional> | false | If `true` and no alive children are found a new one is created. | | `x` | number | <optional> | | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The first child, or `null` if none found and `createIfNull` was false. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2071](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2071)) ### getFurthestFrom(object, callback, callbackContext) → {any} Get the child furthest away from the given Object, with optional callback to filter children. This can be a Sprite, Group, Image or any object with public x and y properties. 'furthest away' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. You can use the optional `callback` argument to apply your own filter to the distance checks. If the child is closer then the previous child, it will be sent to `callback` as the first argument, with the distance as the second. The callback should return `true` if it passes your filtering criteria, otherwise it should return `false`. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `object` | any | | The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. | | `callback` | function | <optional> | The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. | | `callbackContext` | object | <optional> | The context in which the function should be called (usually 'this'). | ##### Returns any - The child furthest from the given object, or `null` if no child was found. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2282](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2282)) ### getIndex(child) → {integer} Get the index position of the given child in this group, which should match the child's `z` property. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to get the index for. | ##### Returns integer - The index of the child or -1 if it's not a member of this group. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1029](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1029)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the displayObjectContainer as a rectangle without any transformations. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.DisplayObjectContainer#getLocalBounds](pixi.displayobjectcontainer#getLocalBounds) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 437](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L437)) ### getRandom(startIndex, length) → {any} Returns a random child from the group. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `startIndex` | integer | <optional> | 0 | Offset from the front of the group (lowest child). | | `length` | integer | <optional> | (to top) | Restriction on the number of values you want to randomly select from. | ##### Returns any - A random child of this Group. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2350](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2350)) ### getRandomExists(startIndex, endIndex) → {any} Returns a random child from the Group that has `exists` set to `true`. Optionally you can specify a start and end index. For example if this Group had 100 children, and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only the first 50 children in the Group. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `startIndex` | integer | <optional> | 0 | The first child index to start the search from. | | `endIndex` | integer | <optional> | | The last child index to search up to. | ##### Returns any - A random child of this Group that exists. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2372](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2372)) ### getTop() → {any} Return the child at the top of this group. The top child is the child displayed (rendered) above every other child. ##### Returns any - The child at the top of the Group. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2204](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2204)) ### hasProperty(child, key) → {boolean} Checks if the child has the given property. Will scan up to 4 levels deep only. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to check for the existence of the property on. | | `key` | Array.<string> | An array of strings that make up the property. | ##### Returns boolean - True if the child has the property, otherwise false. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1104](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1104)) ### iterate(key, value, returnType, callback, callbackContext, args) → {any} Iterates over the children of the group performing one of several actions for matched children. A child is considered a match when it has a property, named `key`, whose value is equal to `value` according to a strict equality comparison. The result depends on the `returnType`: * [RETURN\_TOTAL](phaser.group#.RETURN_TOTAL): The callback, if any, is applied to all matching children. The number of matched children is returned. * [RETURN\_NONE](phaser.group#.RETURN_NONE): The callback, if any, is applied to all matching children. No value is returned. * [RETURN\_CHILD](phaser.group#.RETURN_CHILD): The callback, if any, is applied to the *first* matching child and the *first* matched child is returned. If there is no matching child then null is returned. If `args` is specified it must be an array. The matched child will be assigned to the first element and the entire array will be applied to the callback function. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The child property to check, i.e. 'exists', 'alive', 'health' | | `value` | any | | | A child matches if `child[key] === value` is true. | | `returnType` | integer | | | How to iterate the children and what to return. | | `callback` | function | <optional> | null | Optional function that will be called on each matching child. The matched child is supplied as the first argument. | | `callbackContext` | object | <optional> | | The context in which the function should be called (usually 'this'). | | `args` | Array.<any> | <optional> | (none) | The arguments supplied to to the callback; the first array index (argument) will be replaced with the matched child. | ##### Returns any - Returns either an integer (for RETURN\_TOTAL), the first matched child (for RETURN\_CHILD), or null. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1976](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1976)) ### moveAll(group, silent) → {[Phaser.Group](phaser.group)} Moves all children from this Group to the Group given. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `group` | [Phaser.Group](phaser.group) | | | The new Group to which the children will be moved to. | | `silent` | boolean | <optional> | false | If true the children will not dispatch the `onAddedToGroup` event for the new Group. | ##### Returns [Phaser.Group](phaser.group) - The Group to which all the children were moved. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2479](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2479)) ### moveDown(child) → {any} Moves the given child down one place in this group unless it's already at the bottom. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to move down in the group. | ##### Returns any - The child that was moved. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 969](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L969)) ### moveUp(child) → {any} Moves the given child up one place in this group unless it's already at the top. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to move up in the group. | ##### Returns any - The child that was moved. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 945](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L945)) ### multiplyAll(property, amount, checkAlive, checkVisible) Multiplies the given property by the amount on all children in this group. `Group.multiplyAll('x', 2)` will x2 the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to multiply, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1420](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1420)) ### next() → {any} Advances the group cursor to the next (higher) object in the group. If the cursor is at the end of the group (top child) it is moved the start of the group (bottom child). ##### Returns any - The child the cursor now points to. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 833](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L833)) ### <internal> postUpdate() The core postUpdate - as called by World. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1656](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1656)) ### <internal> preUpdate() The core preUpdate - as called by World. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1611](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1611)) ### previous() → {any} Moves the group cursor to the previous (lower) child in the group. If the cursor is at the start of the group (bottom child) it is moved to the end (top child). ##### Returns any - The child the cursor now points to. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 862](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L862)) ### remove(child, destroy, silent) → {boolean} Removes the given child from this group. This will dispatch an `onRemovedFromGroup` event from the child (if it has one), and optionally destroy the child. If the group cursor was referring to the removed child it is updated to refer to the next child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | any | | | The child to remove. | | `destroy` | boolean | <optional> | false | If true `destroy` will be invoked on the removed child. | | `silent` | boolean | <optional> | false | If true the the child will not dispatch the `onRemovedFromGroup` event. | ##### Returns boolean - true if the child was removed from this group, otherwise false. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2431](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2431)) ### removeAll(destroy, silent, destroyTexture) Removes all children from this Group, but does not remove the group from its parent. The children can be optionally destroyed as they are removed. You can also optionally also destroy the BaseTexture the Child is using. Be careful if you've more than one Game Object sharing the same BaseTexture. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroy` | boolean | <optional> | false | If true `destroy` will be invoked on each removed child. | | `silent` | boolean | <optional> | false | If true the children will not dispatch their `onRemovedFromGroup` events. | | `destroyTexture` | boolean | <optional> | false | If true, and if the `destroy` argument is also true, the BaseTexture belonging to the Child is also destroyed. Note that if another Game Object is sharing the same BaseTexture it will invalidate it. | Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2508](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2508)) ### removeBetween(startIndex, endIndex, destroy, silent) Removes all children from this group whose index falls beteen the given startIndex and endIndex values. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `startIndex` | integer | | | The index to start removing children from. | | `endIndex` | integer | <optional> | | The index to stop removing children at. Must be higher than startIndex. If undefined this method will remove all children between startIndex and the end of the group. | | `destroy` | boolean | <optional> | false | If true `destroy` will be invoked on each removed child. | | `silent` | boolean | <optional> | false | If true the children will not dispatch their `onRemovedFromGroup` events. | Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2556](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2556)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### removeFromHash(child) → {boolean} Removes a child of this Group from the hash array. This call will return false if the child is not in the hash. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The display object to remove from this Groups hash. Must be a member of this Group and in the hash. | ##### Returns boolean - True if the child was successfully removed from the hash, otherwise false. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 464](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L464)) ### replace(oldChild, newChild) → {any} Replaces a child of this Group with the given newChild. The newChild cannot be a member of this Group. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `oldChild` | any | The child in this group that will be replaced. | | `newChild` | any | The child to be inserted into this group. | ##### Returns any - Returns the oldChild that was replaced within this group. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1065](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1065)) ### resetChild(child, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Takes a child and if the `x` and `y` arguments are given it calls `child.reset(x, y)` on it. If the `key` and optionally the `frame` arguments are given, it calls `child.loadTexture(key, frame)` on it. The two operations are separate. For example if you just wish to load a new texture then pass `null` as the x and y values. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | | The child to reset and/or load the texture on. | | `x` | number | <optional> | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was reset: usually a [Phaser.Sprite](phaser.sprite). Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2165](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2165)) ### resetCursor(index) → {any} Sets the group cursor to the first child in the group. If the optional index parameter is given it sets the cursor to the object at that index instead. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `index` | integer | <optional> | 0 | Set the cursor to point to a specific index. | ##### Returns any - The child the cursor now points to. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 806](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L806)) ### reverse() Reverses all children in this group. This operation applies only to immediate children and does not propagate to subgroups. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1015](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1015)) ### sendToBack(child) → {any} Sends the given child to the bottom of this group so it renders below all other children. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to send to the bottom of this group. | ##### Returns any - The child that was moved. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 926](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L926)) ### set(child, key, value, checkAlive, checkVisible, operation, force) → {boolean} Quickly set a property on a single child of this group to a new value. The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | [Phaser.Sprite](phaser.sprite) | | | The child to set the property on. | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be set. | | `checkAlive` | boolean | <optional> | false | If set then the child will only be updated if alive=true. | | `checkVisible` | boolean | <optional> | false | If set then the child will only be updated if visible=true. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | ##### Returns boolean - True if the property was set, false if not. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1246](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1246)) ### setAll(key, value, checkAlive, checkVisible, operation, force) Quickly set the same property across all children of this group to a new value. This call doesn't descend down children, so if you have a Group inside of this group, the property will be set on the group but not its children. If you need that ability please see `Group.setAllChildren`. The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be set. | | `checkAlive` | boolean | <optional> | false | If set then only children with alive=true will be updated. This includes any Groups that are children. | | `checkVisible` | boolean | <optional> | false | If set then only children with visible=true will be updated. This includes any Groups that are children. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1277](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1277)) ### setAllChildren(key, value, checkAlive, checkVisible, operation, force) Quickly set the same property across all children of this group, and any child Groups, to a new value. If this group contains other Groups then the same property is set across their children as well, iterating down until it reaches the bottom. Unlike with `setAll` the property is NOT set on child Groups itself. The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be set. | | `checkAlive` | boolean | <optional> | false | If set then only children with alive=true will be updated. This includes any Groups that are children. | | `checkVisible` | boolean | <optional> | false | If set then only children with visible=true will be updated. This includes any Groups that are children. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1312](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1312)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### setProperty(child, key, value, operation, force) → {boolean} Sets a property to the given value on the child. The operation parameter controls how the value is set. The operations are: * 0: set the existing value to the given value; if force is `true` a new property will be created if needed * 1: will add the given value to the value already present. * 2: will subtract the given value from the value already present. * 3: will multiply the value already present by the given value. * 4: will divide the value already present by the given value. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | any | | | The child to set the property value on. | | `key` | array | | | An array of strings that make up the property that will be set. | | `value` | any | | | The value that will be set. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | ##### Returns boolean - True if the property was set, false if not. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1139](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1139)) ### sort(key, order) Sort the children in the group according to a particular key and ordering. Call this function to sort the group according to a particular key value and order. For example to depth sort Sprites for Zelda-style game you might call `group.sort('y', Phaser.Group.SORT_ASCENDING)` at the bottom of your `State.update()`. Internally this uses a standard JavaScript Array sort, so everything that applies there also applies here, including alphabetical sorting, mixing strings and numbers, and Unicode sorting. See MDN for more details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | <optional> | 'z' | The name of the property to sort on. Defaults to the objects z-depth value. | | `order` | integer | <optional> | Phaser.Group.SORT\_ASCENDING | Order ascending ([SORT\_ASCENDING](phaser.group#.SORT_ASCENDING)) or descending ([SORT\_DESCENDING](phaser.group#.SORT_DESCENDING)). | Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1855](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1855)) ### subAll(property, amount, checkAlive, checkVisible) Subtracts the amount from the given property on all children in this group. `Group.subAll('x', 10)` will minus 10 from the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to decrement, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1403](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1403)) ### swap(child1, child2) Swaps the position of two children in this group. Both children must be in this group, a child cannot be swapped with itself, and unparented children cannot be swapped. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child1` | any | The first child to swap. | | `child2` | any | The second child to swap. | Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 891](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L891)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) ### <internal> update() The core update - as called by World. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1639](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1639)) ### <internal> updateZ() Internal method that re-applies all of the children's Z values. This must be called whenever children ordering is altered so that their `z` indices are correctly updated. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 663](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L663)) ### xy(index, x, y) Positions the child found at the given index within this group to the given x and y coordinates. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | integer | The index of the child in the group to set the position of. | | `x` | number | The new x position of the child. | | `y` | number | The new y position of the child. | Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 993](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L993))
programming_docs
phaser Class: Phaser.TileSprite Class: Phaser.TileSprite ======================== Constructor ----------- ### new TileSprite(game, x, y, width, height, key, frame) A TileSprite is a Sprite that has a repeating texture. The texture can be scrolled and scaled independently of the TileSprite itself. Textures will automatically wrap and are designed so that you can create game backdrops using seamless textures as a source. TileSprites have no input handler or physics bodies by default, both need enabling in the same way as for normal Sprites. You shouldn't ever create a TileSprite any larger than your actual screen size. If you want to create a large repeating background that scrolls across the whole map of your game, then you create a TileSprite that fits the screen size and then use the `tilePosition` property to scroll the texture as the player moves. If you create a TileSprite that is thousands of pixels in size then it will consume huge amounts of memory and cause performance issues. Remember: use `tilePosition` to scroll your texture and `tileScale` to adjust the scale of the texture - don't resize the sprite itself or make it larger than it needs. An important note about texture dimensions: When running under Canvas a TileSprite can use any texture size without issue. When running under WebGL the texture should ideally be a power of two in size (i.e. 4, 8, 16, 32, 64, 128, 256, 512, etc pixels width by height). If the texture isn't a power of two it will be rendered to a blank canvas that is the correct size, which means you may have 'blank' areas appearing to the right and bottom of your frame. To avoid this ensure your textures are perfect powers of two. TileSprites support animations in the same way that Sprites do. You add and play animations using the AnimationManager. However if your game is running under WebGL please note that each frame of the animation must be a power of two in size, or it will receive additional padding to enforce it to be so. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | | `x` | number | The x coordinate (in world space) to position the TileSprite at. | | `y` | number | The y coordinate (in world space) to position the TileSprite at. | | `width` | number | The width of the TileSprite. | | `height` | number | The height of the TileSprite. | | `key` | string | [Phaser.BitmapData](phaser.bitmapdata) | [PIXI.Texture](pixi.texture) | This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. | | `frame` | string | number | If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | Source code: [gameobjects/TileSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/TileSprite.js) ([Line 59](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/TileSprite.js#L59)) Extends ------- * [PIXI.TilingSprite](pixi.tilingsprite) * [Phaser.Component.Core](phaser.component.core) * [Phaser.Component.Angle](phaser.component.angle) * [Phaser.Component.Animation](phaser.component.animation) * [Phaser.Component.AutoCull](phaser.component.autocull) * [Phaser.Component.Bounds](phaser.component.bounds) * [Phaser.Component.BringToTop](phaser.component.bringtotop) * [Phaser.Component.Destroy](phaser.component.destroy) * [Phaser.Component.FixedToCamera](phaser.component.fixedtocamera) * [Phaser.Component.Health](phaser.component.health) * [Phaser.Component.InCamera](phaser.component.incamera) * [Phaser.Component.InputEnabled](phaser.component.inputenabled) * [Phaser.Component.InWorld](phaser.component.inworld) * [Phaser.Component.LifeSpan](phaser.component.lifespan) * [Phaser.Component.LoadTexture](phaser.component.loadtexture) * [Phaser.Component.Overlap](phaser.component.overlap) * [Phaser.Component.PhysicsBody](phaser.component.physicsbody) * [Phaser.Component.Reset](phaser.component.reset) * [Phaser.Component.Smoothed](phaser.component.smoothed) Public Properties ----------------- ### alive : boolean A useful flag to control if the Game Object is alive or dead. This is set automatically by the Health components `damage` method should the object run out of health. Or you can toggle it via your game code. This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. Inherited From * [Phaser.Component.LifeSpan#alive](phaser.component.lifespan#alive) Default Value * true Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L50)) ### anchor :Point The anchor sets the origin point of the texture. The default is 0,0 this means the texture's origin is the top left Setting than anchor to 0.5,0.5 means the textures origin is centered Setting the anchor to 1,1 would mean the textures origin points will be the bottom right corner Inherited From * [PIXI.Sprite#anchor](pixi.sprite#anchor) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L17)) ### angle : number The angle property is the rotation of the Game Object in *degrees* from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90. If you wish to work in radians instead of degrees you can use the property `rotation` instead. Working in radians is slightly faster as it doesn't have to perform any calculations. Inherited From * [Phaser.Component.Angle#angle](phaser.component.angle#angle) Source code: [gameobjects/components/Angle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js#L29)) ### animations : [Phaser.AnimationManager](phaser.animationmanager) If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. Through it you can create, play, pause and stop animations. Inherited From * [Phaser.Component.Core#animations](phaser.component.core#animations) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 193](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L193)) See * [Phaser.AnimationManager](phaser.animationmanager) ### autoCull : boolean A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, or you have tested performance and find it acceptable. Inherited From * [Phaser.Component.AutoCull#autoCull](phaser.component.autocull#autoCull) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L28)) ### blendMode : number The blend mode to be applied to the sprite Inherited From * [PIXI.TilingSprite#blendMode](pixi.tilingsprite#blendMode) Default Value * PIXI.blendModes.NORMAL; Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L86)) ### body : [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | null `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated properties and methods via it. By default Game Objects won't add themselves to any physics system and their `body` property will be `null`. To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`. You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group. Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5, so the physics body is centered on the Game Object. If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics. ##### Type * [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | null Inherited From * [Phaser.Component.PhysicsBody#body](phaser.component.physicsbody#body) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 91](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L91)) ### bottom : number The sum of the y and height properties. This is the same as `y + height - offsetY`. Inherited From * [Phaser.Component.Bounds#bottom](phaser.component.bounds#bottom) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 168](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L168)) ### cameraOffset : [Phaser.Point](phaser.point) The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. Inherited From * [Phaser.Component.FixedToCamera#cameraOffset](phaser.component.fixedtocamera#cameraOffset) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L86)) ### canvasBuffer :PIXICanvasBuffer The CanvasBuffer object that the tiled texture is drawn to. Inherited From * [PIXI.TilingSprite#canvasBuffer](pixi.tilingsprite#canvasBuffer) Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 95](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L95)) ### centerX : number The center x coordinate of the Game Object. This is the same as `(x - offsetX) + (width / 2)`. Inherited From * [Phaser.Component.Bounds#centerX](phaser.component.bounds#centerX) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L58)) ### centerY : number The center y coordinate of the Game Object. This is the same as `(y - offsetY) + (height / 2)`. Inherited From * [Phaser.Component.Bounds#centerY](phaser.component.bounds#centerY) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 80](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L80)) ### checkWorldBounds : boolean If this is set to `true` the Game Object checks if it is within the World bounds each frame. When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event. If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event. It also optionally kills the Game Object if `outOfBoundsKill` is `true`. When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame. This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, or you have tested performance and find it acceptable. Inherited From * [Phaser.Component.InWorld#checkWorldBounds](phaser.component.inworld#checkWorldBounds) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L98)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### <internal> components : Object The components this Game Object has installed. Inherited From * [Phaser.Component.Core#components](phaser.component.core#components) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 167](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L167)) ### damage Damages the Game Object. This removes the given amount of health from the `health` property. If health is taken below or is equal to zero then the `kill` method is called. Inherited From * [Phaser.Component.Health#damage](phaser.component.health#damage) Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L46)) ### data : Object An empty Object that belongs to this Game Object. This value isn't ever used internally by Phaser, but may be used by your own code, or by Phaser Plugins, to store data that needs to be associated with the Game Object, without polluting the Game Object directly. Inherited From * [Phaser.Component.Core#data](phaser.component.core#data) Default Value * {} Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 160](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L160)) ### debug : boolean A debug flag designed for use with `Game.enableStep`. Inherited From * [Phaser.Component.Core#debug](phaser.component.core#debug) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 218](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L218)) ### [readonly] destroyPhase : boolean As a Game Object runs through its destroy method this flag is set to true, and can be checked in any sub-systems or plugins it is being destroyed from. Inherited From * [Phaser.Component.Destroy#destroyPhase](phaser.component.destroy#destroyPhase) Source code: [gameobjects/components/Destroy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js#L22)) ### events : [Phaser.Events](phaser.events) All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this Game Object, or any of its components. Inherited From * [Phaser.Component.Core#events](phaser.component.core#events) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 185](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L185)) See * [Phaser.Events](phaser.events) ### exists : boolean Controls if this Sprite is processed by the core Phaser game loops and Group loops. Inherited From * [PIXI.Sprite#exists](pixi.sprite#exists) Default Value * true Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 103](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L103)) ### fixedToCamera : boolean A Game Object that is "fixed" to the camera uses its x/y coordinates as offsets from the top left of the camera during rendering. The values are adjusted at the rendering stage, overriding the Game Objects actual world position. The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times regardless where in the world the camera is. The offsets are stored in the `cameraOffset` property. Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. Inherited From * [Phaser.Component.FixedToCamera#fixedToCamera](phaser.component.fixedtocamera#fixedToCamera) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 56](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L56)) ### frame : integer Gets or sets the current frame index of the texture being used to render this Game Object. To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use, for example: `player.frame = 4`. If the frame index given doesn't exist it will revert to the first frame found in the texture. If you are using a texture atlas then you should use the `frameName` property instead. If you wish to fully replace the texture being used see `loadTexture`. Inherited From * [Phaser.Component.LoadTexture#frame](phaser.component.loadtexture#frame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 254](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L254)) ### frameName : string Gets or sets the current frame name of the texture being used to render this Game Object. To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use, for example: `player.frameName = "idle"`. If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning. If you are using a sprite sheet then you should use the `frame` property instead. If you wish to fully replace the texture being used see `loadTexture`. Inherited From * [Phaser.Component.LoadTexture#frameName](phaser.component.loadtexture#frameName) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 279](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L279)) ### [readonly] fresh : boolean A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. This property is mostly used internally by the physics systems, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#fresh](phaser.component.core#fresh) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 248](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L248)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Inherited From * [Phaser.Component.Core#game](phaser.component.core#game) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 142](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L142)) ### heal Heal the Game Object. This adds the given amount of health to the `health` property. Inherited From * [Phaser.Component.Health#heal](phaser.component.health#heal) Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 90](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L90)) ### health : number The Game Objects health value. This is a handy property for setting and manipulating health on a Game Object. It can be used in combination with the `damage` method or modified directly. Inherited From * [Phaser.Component.Health#health](phaser.component.health#health) Default Value * 1 Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L26)) ### height : number The height of the tiling sprite Inherited From * [PIXI.TilingSprite#height](pixi.tilingsprite#height) Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 27](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L27)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### [readonly] inCamera : boolean Checks if the Game Objects bounds intersect with the Game Camera bounds. Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. Inherited From * [Phaser.Component.AutoCull#inCamera](phaser.component.autocull#inCamera) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L37)) ### input : [Phaser.InputHandler](phaser.inputhandler) | null The Input Handler for this Game Object. By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`. After you have done this, this property will be a reference to the Phaser InputHandler. ##### Type * [Phaser.InputHandler](phaser.inputhandler) | null Inherited From * [Phaser.Component.InputEnabled#input](phaser.component.inputenabled#input) Source code: [gameobjects/components/InputEnabled.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js#L24)) ### inputEnabled : boolean By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created for this Game Object and it will then start to process click / touch events and more. You can then access the Input Handler via `this.input`. Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`. If you set this property to false it will stop the Input Handler from processing any more input events. If you want to *temporarily* disable input for a Game Object, then it's better to set `input.enabled = false`, as it won't reset any of the Input Handlers internal properties. You can then toggle this back on as needed. Inherited From * [Phaser.Component.InputEnabled#inputEnabled](phaser.component.inputenabled#inputEnabled) Source code: [gameobjects/components/InputEnabled.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js#L42)) ### [readonly] inWorld : boolean Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds. Inherited From * [Phaser.Component.InWorld#inWorld](phaser.component.inworld#inWorld) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 129](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L129)) ### key : string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) The key of the image or texture used by this Game Object during rendering. If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. ##### Type * string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) Inherited From * [Phaser.Component.Core#key](phaser.component.core#key) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 203](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L203)) ### left : number The left coordinate of the Game Object. This is the same as `x - offsetX`. Inherited From * [Phaser.Component.Bounds#left](phaser.component.bounds#left) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 102](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L102)) ### lifespan : number The lifespan allows you to give a Game Object a lifespan in milliseconds. Once the Game Object is 'born' you can set this to a positive value. It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. When it reaches zero it will call the `kill` method. Very handy for particles, bullets, collectibles, or any other short-lived entity. Inherited From * [Phaser.Component.LifeSpan#lifespan](phaser.component.lifespan#lifespan) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 65](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L65)) ### maxHealth : number The Game Objects maximum health value. This works in combination with the `heal` method to ensure the health value never exceeds the maximum. Inherited From * [Phaser.Component.Health#maxHealth](phaser.component.health#maxHealth) Default Value * 100 Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 35](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L35)) ### name : string A user defined name given to this Game Object. This value isn't ever used internally by Phaser, it is meant as a game level property. Inherited From * [Phaser.Component.Core#name](phaser.component.core#name) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 150](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L150)) ### [readonly] offsetX : number The amount the Game Object is visually offset from its x coordinate. This is the same as `width * anchor.x`. It will only be > 0 if anchor.x is not equal to zero. Inherited From * [Phaser.Component.Bounds#offsetX](phaser.component.bounds#offsetX) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L24)) ### [readonly] offsetY : number The amount the Game Object is visually offset from its y coordinate. This is the same as `height * anchor.y`. It will only be > 0 if anchor.y is not equal to zero. Inherited From * [Phaser.Component.Bounds#offsetY](phaser.component.bounds#offsetY) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L42)) ### outOfBoundsKill : boolean If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false. Inherited From * [Phaser.Component.InWorld#outOfBoundsKill](phaser.component.inworld#outOfBoundsKill) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 106](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L106)) ### outOfCameraBoundsKill : boolean If this and the `autoCull` property are both set to `true`, then the `kill` method is called as soon as the Game Object leaves the camera bounds. Inherited From * [Phaser.Component.InWorld#outOfCameraBoundsKill](phaser.component.inworld#outOfCameraBoundsKill) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 115](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L115)) ### pendingDestroy : boolean A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. You can set it directly to allow you to flag an object to be destroyed on its next update. This is extremely useful if you wish to destroy an object from within one of its own callbacks such as with Buttons or other Input events. Inherited From * [Phaser.Component.Core#pendingDestroy](phaser.component.core#pendingDestroy) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 259](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L259)) ### [readonly] physicsType : number The const physics body type of this object. Source code: [gameobjects/TileSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/TileSprite.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/TileSprite.js#L78)) ### [readonly] previousPosition : [Phaser.Point](phaser.point) The position the Game Object was located in the previous frame. Inherited From * [Phaser.Component.Core#previousPosition](phaser.component.core#previousPosition) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 225](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L225)) ### [readonly] previousRotation : number The rotation the Game Object was in set to in the previous frame. Value is in radians. Inherited From * [Phaser.Component.Core#previousRotation](phaser.component.core#previousRotation) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L232)) ### refreshTexture : boolean If true the TilingSprite will run generateTexture on its **next** render pass. This is set by the likes of Phaser.LoadTexture.setFrame. Inherited From * [PIXI.TilingSprite#refreshTexture](pixi.tilingsprite#refreshTexture) Default Value * true Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 119](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L119)) ### renderable : boolean Whether this sprite is renderable or not Inherited From * [PIXI.TilingSprite#renderable](pixi.tilingsprite#renderable) Default Value * true Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 59](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L59)) ### [readonly] renderOrderID : number The render order ID is used internally by the renderer and Input Manager and should not be modified. This property is mostly used internally by the renderers, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#renderOrderID](phaser.component.core#renderOrderID) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 240](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L240)) ### right : number The right coordinate of the Game Object. This is the same as `x + width - offsetX`. Inherited From * [Phaser.Component.Bounds#right](phaser.component.bounds#right) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L124)) ### setHealth Sets the health property of the Game Object to the given amount. Will never exceed the `maxHealth` value. Inherited From * [Phaser.Component.Health#setHealth](phaser.component.health#setHealth) Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 70](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L70)) ### shader : [PIXI.AbstractFilter](pixi.abstractfilter) The shader that will be used to render this Sprite. Set to null to remove a current shader. Inherited From * [PIXI.Sprite#shader](pixi.sprite#shader) Default Value * null Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L93)) ### smoothed : boolean Enable or disable texture smoothing for this Game Object. It only takes effect if the Game Object is using an image based texture. Smoothing is enabled by default. Inherited From * [Phaser.Component.Smoothed#smoothed](phaser.component.smoothed#smoothed) Source code: [gameobjects/components/Smoothed.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Smoothed.js) ([Line 25](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Smoothed.js#L25)) ### texture : [PIXI.Texture](pixi.texture) The texture that the sprite is using Inherited From * [PIXI.Sprite#texture](pixi.sprite#texture) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L28)) ### textureDebug : boolean If enabled a green rectangle will be drawn behind the generated tiling texture, allowing you to visually debug the texture being used. Inherited From * [PIXI.TilingSprite#textureDebug](pixi.tilingsprite#textureDebug) Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 77](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L77)) ### tilePattern :PIXITexture The Context fill pattern that is used to draw the TilingSprite in Canvas mode only (will be null in WebGL). Inherited From * [PIXI.TilingSprite#tilePattern](pixi.tilingsprite#tilePattern) Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 111](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L111)) ### tilePosition :Point The offset position of the image that is being tiled Inherited From * [PIXI.TilingSprite#tilePosition](pixi.tilingsprite#tilePosition) Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L51)) ### tileScale :Point The scaling of the image that is being tiled Inherited From * [PIXI.TilingSprite#tileScale](pixi.tilingsprite#tileScale) Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 35](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L35)) ### tileScaleOffset :Point A point that represents the scale of the texture object Inherited From * [PIXI.TilingSprite#tileScaleOffset](pixi.tilingsprite#tileScaleOffset) Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 43](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L43)) ### tilingTexture :PIXITexture An internal Texture object that holds the tiling texture that was generated from TilingSprite.texture. Inherited From * [PIXI.TilingSprite#tilingTexture](pixi.tilingsprite#tilingTexture) Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 103](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L103)) ### tint : number The tint applied to the sprite. This is a hex value Inherited From * [PIXI.TilingSprite#tint](pixi.tilingsprite#tint) Default Value * 0xFFFFFF Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 68](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L68)) ### tintedTexture :Canvas A canvas that contains the tinted version of the Sprite (in Canvas mode, WebGL doesn't populate this) Inherited From * [PIXI.Sprite#tintedTexture](pixi.sprite#tintedTexture) Default Value * null Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 73](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L73)) ### top : number The y coordinate of the Game Object. This is the same as `y - offsetY`. Inherited From * [Phaser.Component.Bounds#top](phaser.component.bounds#top) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 146](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L146)) ### [readonly] type : number The const type of this object. Source code: [gameobjects/TileSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/TileSprite.js) ([Line 72](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/TileSprite.js#L72)) ### width : number The width of the tiling sprite Inherited From * [PIXI.TilingSprite#width](pixi.tilingsprite#width) Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 19](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L19)) ### world : [Phaser.Point](phaser.point) The world coordinates of this Game Object in pixels. Depending on where in the display list this Game Object is placed this value can differ from `position`, which contains the x/y coordinates relative to the Game Objects parent. Inherited From * [Phaser.Component.Core#world](phaser.component.core#world) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 211](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L211)) ### x : number The position of the Game Object on the x axis relative to the local coordinates of the parent. Inherited From * [Phaser.Component.PhysicsBody#x](phaser.component.physicsbody#x) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L98)) ### y : number The position of the Game Object on the y axis relative to the local coordinates of the parent. Inherited From * [Phaser.Component.PhysicsBody#y](phaser.component.physicsbody#y) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L124)) ### [readonly] z : number The z depth of this Game Object within its parent Group. No two objects in a Group can have the same z value. This value is adjusted automatically whenever the Group hierarchy changes. If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. Inherited From * [Phaser.Component.Core#z](phaser.component.core#z) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 177](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L177)) Public Methods -------------- ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### alignIn(container, position, offsetX, offsetY) → {Object} Aligns this Game Object within another Game Object, or Rectangle, known as the 'container', to one of 9 possible positions. The container must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the container. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the container, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `container` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Inherited From * [Phaser.Component.Bounds#alignIn](phaser.component.bounds#alignIn) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 223](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L223)) ### alignTo(parent, position, offsetX, offsetY) → {Object} Aligns this Game Object to the side of another Game Object, or Rectangle, known as the 'parent', in one of 11 possible positions. The parent must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the parent. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the parent, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Inherited From * [Phaser.Component.Bounds#alignTo](phaser.component.bounds#alignTo) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 321](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L321)) ### autoScroll(x, y) Sets this TileSprite to automatically scroll in the given direction until stopped via TileSprite.stopScroll(). The scroll speed is specified in pixels per second. A negative x value will scroll to the left. A positive x value will scroll to the right. A negative y value will scroll up. A positive y value will scroll down. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Horizontal scroll speed in pixels per second. | | `y` | number | Vertical scroll speed in pixels per second. | Source code: [gameobjects/TileSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/TileSprite.js) ([Line 149](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/TileSprite.js#L149)) ### bringToTop() → {PIXI.DisplayObject} Brings this Game Object to the top of its parents display list. Visually this means it will render over the top of any old child in the same Group. If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#bringToTop](phaser.component.bringtotop#bringToTop) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L24)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### destroy(destroyChildren) Destroys the TileSprite. This removes it from its parent group, destroys the event and animation handlers if present and nulls its reference to game, freeing it up for garbage collection. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroyChildren` | boolean | <optional> | true | Should every child of this object have its destroy method called? | Source code: [gameobjects/TileSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/TileSprite.js) ([Line 178](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/TileSprite.js#L178)) ### generateTilingTexture(forcePowerOfTwo, renderSession) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `forcePowerOfTwo` | Boolean | Whether we want to force the texture to be a power of two | | `renderSession` | RenderSession | - | Inherited From * [PIXI.TilingSprite#generateTilingTexture](pixi.tilingsprite#generateTilingTexture) Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 332](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L332)) ### getBounds() → {Rectangle} Returns the framing rectangle of the sprite as a PIXI.Rectangle object ##### Returns Rectangle - the framing rectangle Inherited From * [PIXI.TilingSprite#getBounds](pixi.tilingsprite#getBounds) Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 417](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L417)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the Sprite as a rectangle. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.Sprite#getLocalBounds](pixi.sprite#getLocalBounds) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 315](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L315)) ### kill() → {PIXI.DisplayObject} Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false. It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal. Note that killing a Game Object is a way for you to quickly recycle it in an object pool, it doesn't destroy the object or free it up from memory. If you don't need this Game Object any more you should call `destroy` instead. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.LifeSpan#kill](phaser.component.lifespan#kill) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 113](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L113)) ### loadTexture(key, frame, stopAnimation) Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache. If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead. You should only use `loadTexture` if you want to replace the base texture entirely. Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU. You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite. Doing this then sets the key to be the `frame` argument (the frame is set to zero). This allows you to create sprites using `load.image` during development, and then change them to use a Texture Atlas later in development by simply searching your code for 'PENDING\_ATLAS' and swapping it to be the key of the atlas data. Note: You cannot use a RenderTexture as a texture for a TileSprite. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | | `stopAnimation` | boolean | <optional> | true | If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing. | Inherited From * [Phaser.Component.LoadTexture#loadTexture](phaser.component.loadtexture#loadTexture) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L51)) ### moveDown() → {PIXI.DisplayObject} Moves this Game Object down one place in its parents display list. This call has no effect if the Game Object is already at the bottom of the display list. If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#moveDown](phaser.component.bringtotop#moveDown) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L87)) ### moveUp() → {PIXI.DisplayObject} Moves this Game Object up one place in its parents display list. This call has no effect if the Game Object is already at the top of the display list. If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#moveUp](phaser.component.bringtotop#moveUp) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 66](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L66)) ### overlap(displayObject) → {boolean} Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object, which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result. This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result. Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency. It should be fine for low-volume testing where physics isn't required. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `displayObject` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.TileSprite](phaser.tilesprite) | [Phaser.Button](phaser.button) | PIXI.DisplayObject | The display object to check against. | ##### Returns boolean - True if the bounds of this Game Object intersects at any point with the bounds of the given display object. Inherited From * [Phaser.Component.Overlap#overlap](phaser.component.overlap#overlap) Source code: [gameobjects/components/Overlap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Overlap.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Overlap.js#L29)) ### play(name, frameRate, loop, killOnComplete) → {[Phaser.Animation](phaser.animation)} Plays an Animation. The animation should have previously been created via `animations.add`. If the animation is already playing calling this again won't do anything. If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `name` | string | | | The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'. | | `frameRate` | number | <optional> | null | The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. | | `loop` | boolean | <optional> | false | Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. | | `killOnComplete` | boolean | <optional> | false | If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. | ##### Returns [Phaser.Animation](phaser.animation) - A reference to playing Animation. Inherited From * [Phaser.Component.Animation#play](phaser.component.animation#play) Source code: [gameobjects/components/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Animation.js) ([Line 31](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Animation.js#L31)) ### <internal> postUpdate() Internal method called by the World postUpdate cycle. Inherited From * [Phaser.Component.Core#postUpdate](phaser.component.core#postUpdate) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 338](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L338)) ### preUpdate() Automatically called by World.preUpdate. Source code: [gameobjects/TileSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/TileSprite.js) ([Line 122](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/TileSprite.js#L122)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### reset(x, y) → {[Phaser.TileSprite](phaser.tilesprite)} Resets the TileSprite. This places the TileSprite at the given x/y world coordinates, resets the tilePosition and then sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state. If the TileSprite has a physics body that too is reset. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The x coordinate (in world space) to position the Sprite at. | | `y` | number | The y coordinate (in world space) to position the Sprite at. | ##### Returns [Phaser.TileSprite](phaser.tilesprite) - This instance. Source code: [gameobjects/TileSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/TileSprite.js) ([Line 194](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/TileSprite.js#L194)) ### resetFrame() Resets the texture frame dimensions that the Game Object uses for rendering. Inherited From * [Phaser.Component.LoadTexture#resetFrame](phaser.component.loadtexture#resetFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L232)) ### resizeFrame(parent, width, height) Resizes the Frame dimensions that the Game Object uses for rendering. You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData it can be useful to adjust the dimensions directly in this way. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `parent` | object | The parent texture object that caused the resize, i.e. a Phaser.Video object. | | `width` | integer | The new width of the texture. | | `height` | integer | The new height of the texture. | Inherited From * [Phaser.Component.LoadTexture#resizeFrame](phaser.component.loadtexture#resizeFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 220](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L220)) ### revive(health) → {PIXI.DisplayObject} Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `health` | number | <optional> | 100 | The health to give the Game Object. Only set if the GameObject has the Health component. | ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.LifeSpan#revive](phaser.component.lifespan#revive) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L78)) ### sendToBack() → {PIXI.DisplayObject} Sends this Game Object to the bottom of its parents display list. Visually this means it will render below all other children in the same Group. If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#sendToBack](phaser.component.bringtotop#sendToBack) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L45)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### setFrame(frame) Sets the texture frame the Game Object uses for rendering. This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `frame` | [Phaser.Frame](phaser.frame) | The Frame to be used by the texture. | Inherited From * [Phaser.Component.LoadTexture#setFrame](phaser.component.loadtexture#setFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 155](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L155)) ### setTexture(texture, destroy) Sets the texture of the sprite. Be warned that this doesn't remove or destroy the previous texture this Sprite was using. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `texture` | [PIXI.Texture](pixi.texture) | | | The PIXI texture that is displayed by the sprite | | `destroy` | Boolean | <optional> | false | Call Texture.destroy on the current texture before replacing it with the new one? | Inherited From * [PIXI.Sprite#setTexture](pixi.sprite#setTexture) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 163](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L163)) ### stopScroll() Stops an automatically scrolling TileSprite. Source code: [gameobjects/TileSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/TileSprite.js) ([Line 166](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/TileSprite.js#L166)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) ### update() Override this method in your own custom objects to handle any update requirements. It is called immediately after `preUpdate` and before `postUpdate`. Remember if this Game Object has any children you should call update on those too. Inherited From * [Phaser.Component.Core#update](phaser.component.core#update) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 328](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L328))
programming_docs
phaser Class: Phaser.RandomDataGenerator Class: Phaser.RandomDataGenerator ================================= Constructor ----------- ### new RandomDataGenerator(seeds) An extremely useful repeatable random data generator. Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense. The random number genererator is based on the Alea PRNG, but is modified. * https://github.com/coverslide/node-alea * https://github.com/nquinlan/better-random-numbers-for-javascript-mirror * http://baagoe.org/en/wiki/Better\_random\_numbers\_for\_javascript (original, perm. 404) ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `seeds` | Array.<any> | string | <optional> | An array of values to use as the seed, or a generator state (from {#state}). | Source code: [math/RandomDataGenerator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js) ([Line 23](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js#L23)) Public Methods -------------- ### angle() → {number} Returns a random angle between -180 and 180. ##### Returns number - A random number between -180 and 180. Source code: [math/RandomDataGenerator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js) ([Line 310](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js#L310)) ### between(min, max) → {number} Returns a random integer between and including min and max. This method is an alias for RandomDataGenerator.integerInRange. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `min` | number | The minimum value in the range. | | `max` | number | The maximum value in the range. | ##### Returns number - A random number between min and max. Source code: [math/RandomDataGenerator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js) ([Line 198](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js#L198)) ### frac() → {number} Returns a random real number between 0 and 1. ##### Returns number - A random real number between 0 and 1. Source code: [math/RandomDataGenerator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js) ([Line 160](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js#L160)) ### integer() → {number} Returns a random integer between 0 and 2^32. ##### Returns number - A random integer between 0 and 2^32. Source code: [math/RandomDataGenerator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js) ([Line 148](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js#L148)) ### integerInRange(min, max) → {number} Returns a random integer between and including min and max. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `min` | number | The minimum value in the range. | | `max` | number | The maximum value in the range. | ##### Returns number - A random number between min and max. Source code: [math/RandomDataGenerator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js) ([Line 184](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js#L184)) ### normal() → {number} Returns a random real number between -1 and 1. ##### Returns number - A random real number between -1 and 1. Source code: [math/RandomDataGenerator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js) ([Line 227](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js#L227)) ### pick(ary) → {any} Returns a random member of `array`. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `ary` | Array | An Array to pick a random member of. | ##### Returns any - A random member of the array. Source code: [math/RandomDataGenerator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js) ([Line 258](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js#L258)) ### real() → {number} Returns a random real number between 0 and 2^32. ##### Returns number - A random real number between 0 and 2^32. Source code: [math/RandomDataGenerator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js) ([Line 172](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js#L172)) ### realInRange(min, max) → {number} Returns a random real number between min and max. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `min` | number | The minimum value in the range. | | `max` | number | The maximum value in the range. | ##### Returns number - A random number between min and max. Source code: [math/RandomDataGenerator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js#L213)) ### sign() → {number} Returns a sign to be used with multiplication operator. ##### Returns number - -1 or +1. Source code: [math/RandomDataGenerator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js) ([Line 271](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js#L271)) ### sow(seeds) Reset the seed of the random data generator. *Note*: the seed array is only processed up to the first `undefined` (or `null`) value, should such be present. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `seeds` | Array.<any> | The array of seeds: the `toString()` of each value is used. | Source code: [math/RandomDataGenerator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js) ([Line 83](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js#L83)) ### state(state) → {string} Gets or Sets the state of the generator. This allows you to retain the values that the generator is using between games, i.e. in a game save file. To seed this generator with a previously saved state you can pass it as the `seed` value in your game config, or call this method directly after Phaser has booted. Call this method with no parameters to return the current state. If providing a state it should match the same format that this method returns, which is a string with a header `!rnd` followed by the `c`, `s0`, `s1` and `s2` values respectively, each comma-delimited. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `state` | string | <optional> | Generator state to be set. | ##### Returns string - The current state of the generator. Source code: [math/RandomDataGenerator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js) ([Line 322](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js#L322)) ### timestamp(min, max) → {number} Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `min` | number | The minimum value in the range. | | `max` | number | The maximum value in the range. | ##### Returns number - A random timestamp between min and max. Source code: [math/RandomDataGenerator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js) ([Line 296](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js#L296)) ### uuid() → {string} Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368 ##### Returns string - A valid RFC4122 version4 ID hex string Source code: [math/RandomDataGenerator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js) ([Line 239](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js#L239)) ### weightedPick(ary) → {any} Returns a random member of `array`, favoring the earlier entries. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `ary` | Array | An Array to pick a random member of. | ##### Returns any - A random member of the array. Source code: [math/RandomDataGenerator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js) ([Line 283](https://github.com/photonstorm/phaser/tree/v2.6.2/src/math/RandomDataGenerator.js#L283)) phaser Class: Phaser.GameObjectFactory Class: Phaser.GameObjectFactory =============================== Constructor ----------- ### new GameObjectFactory(game) The GameObjectFactory is a quick way to create many common game objects using [``game.add``](phaser.game#add). Created objects are *automatically added* to the appropriate Manager, World, or manually specified parent Group. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L17)) Public Properties ----------------- ### <internal> game : [Phaser.Game](phaser.game) A reference to the currently running Game. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 23](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L23)) ### <internal> world : [Phaser.World](phaser.world) A reference to the game world. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L29)) Public Methods -------------- ### audio(key, volume, loop, connect) → {[Phaser.Sound](phaser.sound)} Creates a new Sound object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The Game.cache key of the sound that this object will use. | | `volume` | number | <optional> | 1 | The volume at which the sound will be played. | | `loop` | boolean | <optional> | false | Whether or not the sound will loop. | | `connect` | boolean | <optional> | true | Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. | ##### Returns [Phaser.Sound](phaser.sound) - The newly created sound object. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 230](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L230)) ### audioSprite(key) → {[Phaser.AudioSprite](phaser.audiosprite)} Creates a new AudioSprite object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The Game.cache key of the sound that this object will use. | ##### Returns [Phaser.AudioSprite](phaser.audiosprite) - The newly created AudioSprite object. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 262](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L262)) ### bitmapData(width, height, key, addToCache) → {[Phaser.BitmapData](phaser.bitmapdata)} Create a BitmapData object. A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `width` | number | <optional> | 256 | The width of the BitmapData in pixels. | | `height` | number | <optional> | 256 | The height of the BitmapData in pixels. | | `key` | string | <optional> | '' | Asset key for the BitmapData when stored in the Cache (see addToCache parameter). | | `addToCache` | boolean | <optional> | false | Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key) | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - The newly created BitmapData object. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 526](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L526)) ### bitmapText(x, y, font, text, size, group) → {[Phaser.BitmapText](phaser.bitmaptext)} Create a new BitmapText object. BitmapText objects work by taking a texture file and an XML file that describes the font structure. It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to match the font structure. BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by processing the font texture in an image editor first, applying fills and any other effects required. To create multi-line text insert \r, \n or \r\n escape codes into the text string. To create a BitmapText data files you can use: BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner Littera (Web-based, free): http://kvazars.com/littera/ ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | X coordinate to display the BitmapText object at. | | `y` | number | | | Y coordinate to display the BitmapText object at. | | `font` | string | | | The key of the BitmapText as stored in Phaser.Cache. | | `text` | string | <optional> | '' | The text that will be rendered. This can also be set later via BitmapText.text. | | `size` | number | <optional> | 32 | The size the font will be rendered at in pixels. | | `group` | [Phaser.Group](phaser.group) | <optional> | | Optional Group to add the object to. If not specified it will be added to the World group. | ##### Returns [Phaser.BitmapText](phaser.bitmaptext) - The newly created bitmapText object. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 425](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L425)) ### button(x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame, group) → {[Phaser.Button](phaser.button)} Creates a new Button object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | <optional> | 0 | The x coordinate of the Button. The coordinate is relative to any parent container this button may be in. | | `y` | number | <optional> | 0 | The y coordinate of the Button. The coordinate is relative to any parent container this button may be in. | | `key` | string | <optional> | | The image key as defined in the Game.Cache to use as the texture for this button. | | `callback` | function | <optional> | | The function to call when this button is pressed | | `callbackContext` | object | <optional> | | The context in which the callback will be called (usually 'this') | | `overFrame` | string | number | <optional> | | This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. | | `outFrame` | string | number | <optional> | | This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. | | `downFrame` | string | number | <optional> | | This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. | | `upFrame` | string | number | <optional> | | This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name. | | `group` | [Phaser.Group](phaser.group) | <optional> | | Optional Group to add the object to. If not specified it will be added to the World group. | ##### Returns [Phaser.Button](phaser.button) - The newly created Button object. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 337](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L337)) ### creature(x, y, key, group) → {[Phaser.Creature](phaser.creature)} Create a new Creature Animation object. Creature is a custom Game Object used in conjunction with the Creature Runtime libraries by Kestrel Moon Studios. It allows you to display animated Game Objects that were created with the [Creature Automated Animation Tool](http://www.kestrelmoon.com/creature/). Note 1: You can only use Phaser.Creature objects in WebGL enabled games. They do not work in Canvas mode games. Note 2: You must use a build of Phaser that includes the CreatureMeshBone.js runtime and gl-matrix.js, or have them loaded before your Phaser game boots. See the Phaser custom build process for more details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | <optional> | 0 | The x coordinate of the creature. The coordinate is relative to any parent container this creature may be in. | | `y` | number | <optional> | 0 | The y coordinate of the creature. The coordinate is relative to any parent container this creature may be in. | | `key` | string | [PIXI.Texture](pixi.texture) | <optional> | | The image used as a texture by this creature object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a PIXI.Texture. | | `group` | [Phaser.Group](phaser.group) | <optional> | | Optional Group to add the object to. If not specified it will be added to the World group. | ##### Returns [Phaser.Creature](phaser.creature) - The newly created Sprite object. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 125](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L125)) ### emitter(x, y, maxParticles) → {[Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter)} Create a new Emitter. A particle emitter can be used for one-time explosions or for continuous effects like rain and fire. All it really does is launch Particle objects out at set intervals, and fixes their positions and velocities accordingly. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | <optional> | 0 | The x coordinate within the Emitter that the particles are emitted from. | | `y` | number | <optional> | 0 | The y coordinate within the Emitter that the particles are emitted from. | | `maxParticles` | number | <optional> | 50 | The total number of particles in this emitter. | ##### Returns [Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter) - The newly created emitter object. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 378](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L378)) ### existing(object) → {any} Adds an existing display object to the game world. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `object` | any | An instance of Phaser.Sprite, Phaser.Button or any other display object. | ##### Returns any - The child that was added to the World. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 35](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L35)) ### filter(filter) → {[Phaser.Filter](phaser.filter)} A WebGL shader/filter that can be applied to Sprites. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `filter` | string | The name of the filter you wish to create, for example HueRotate or SineWave. | | | any | Whatever parameters are needed to be passed to the filter init function. | ##### Returns [Phaser.Filter](phaser.filter) - The newly created Phaser.Filter object. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 554](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L554)) ### graphics(x, y, group) → {[Phaser.Graphics](phaser.graphics)} Creates a new Graphics object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | <optional> | 0 | The x coordinate of the Graphic. The coordinate is relative to any parent container this object may be in. | | `y` | number | <optional> | 0 | The y coordinate of the Graphic. The coordinate is relative to any parent container this object may be in. | | `group` | [Phaser.Group](phaser.group) | <optional> | | Optional Group to add the object to. If not specified it will be added to the World group. | ##### Returns [Phaser.Graphics](phaser.graphics) - The newly created graphics object. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 361](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L361)) ### group(parent, name, addToStage, enableBody, physicsBodyType) → {[Phaser.Group](phaser.group)} A Group is a container for display objects that allows for fast pooling, recycling and collision checks. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | any | <optional> | | The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default. | | `name` | string | <optional> | 'group' | A name for this Group. Not used internally but useful for debugging. | | `addToStage` | boolean | <optional> | false | If set to true this Group will be added directly to the Game.Stage instead of Game.World. | | `enableBody` | boolean | <optional> | false | If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType. | | `physicsBodyType` | number | <optional> | 0 | If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc. | ##### Returns [Phaser.Group](phaser.group) - The newly created Group. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 173](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L173)) ### image(x, y, key, frame, group) → {[Phaser.Image](phaser.image)} Create a new `Image` object. An Image is a light-weight object you can use to display anything that doesn't need physics or animation. It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | <optional> | 0 | The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in. | | `y` | number | <optional> | 0 | The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. | | `group` | [Phaser.Group](phaser.group) | <optional> | | Optional Group to add the object to. If not specified it will be added to the World group. | ##### Returns [Phaser.Image](phaser.image) - The newly created Image object. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L78)) ### physicsGroup(physicsBodyType, parent, name, addToStage) → {[Phaser.Group](phaser.group)} A Group is a container for display objects that allows for fast pooling, recycling and collision checks. A Physics Group is the same as an ordinary Group except that is has enableBody turned on by default, so any Sprites it creates are automatically given a physics body. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `physicsBodyType` | number | <optional> | Phaser.Physics.ARCADE | If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA, etc. | | `parent` | any | <optional> | | The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default. | | `name` | string | <optional> | 'group' | A name for this Group. Not used internally but useful for debugging. | | `addToStage` | boolean | <optional> | false | If set to true this Group will be added directly to the Game.Stage instead of Game.World. | ##### Returns [Phaser.Group](phaser.group) - The newly created Group. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 190](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L190)) ### plugin(plugin, parameter) → {[Phaser.Plugin](phaser.plugin)} Add a new Plugin into the PluginManager. The Plugin must have 2 properties: `game` and `parent`. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `plugin` | object | [Phaser.Plugin](phaser.plugin) | | The Plugin to add into the PluginManager. This can be a function or an existing object. | | `parameter` | \* | <repeatable> | Additional parameters that will be passed to the Plugin.init method. | ##### Returns [Phaser.Plugin](phaser.plugin) - The Plugin that was added to the manager. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 574](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L574)) ### renderTexture(width, height, key, addToCache) → {[Phaser.RenderTexture](phaser.rendertexture)} A dynamic initially blank canvas to which images can be drawn. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `width` | number | <optional> | 100 | the width of the RenderTexture. | | `height` | number | <optional> | 100 | the height of the RenderTexture. | | `key` | string | <optional> | '' | Asset key for the RenderTexture when stored in the Cache (see addToCache parameter). | | `addToCache` | boolean | <optional> | false | Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key) | ##### Returns [Phaser.RenderTexture](phaser.rendertexture) - The newly created RenderTexture object. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 484](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L484)) ### retroFont(font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) → {[Phaser.RetroFont](phaser.retrofont)} Create a new RetroFont object. A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache. A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set. If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text. The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all, i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `font` | string | | | The key of the image in the Game.Cache that the RetroFont will use. | | `characterWidth` | number | | | The width of each character in the font set. | | `characterHeight` | number | | | The height of each character in the font set. | | `chars` | string | | | The characters used in the font set, in display order. You can use the TEXT\_SET consts for common font set arrangements. | | `charsPerRow` | number | | | The number of characters per row in the font set. | | `xSpacing` | number | <optional> | 0 | If the characters in the font set have horizontal spacing between them set the required amount here. | | `ySpacing` | number | <optional> | 0 | If the characters in the font set have vertical spacing between them set the required amount here. | | `xOffset` | number | <optional> | 0 | If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. | | `yOffset` | number | <optional> | 0 | If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. | ##### Returns [Phaser.RetroFont](phaser.retrofont) - The newly created RetroFont texture which can be applied to an Image or Sprite. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 397](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L397)) ### rope(x, y, key, frame, points, group) → {[Phaser.Rope](phaser.rope)} Creates a new Rope object. Example usage: https://github.com/codevinsky/phaser-rope-demo/blob/master/dist/demo.js ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | <optional> | 0 | The x coordinate of the Rope. The coordinate is relative to any parent container this rope may be in. | | `y` | number | <optional> | 0 | The y coordinate of the Rope. The coordinate is relative to any parent container this rope may be in. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. | | `points` | Array | | | An array of {Phaser.Point}. | | `group` | [Phaser.Group](phaser.group) | <optional> | | Optional Group to add the object to. If not specified it will be added to the World group. | ##### Returns [Phaser.Rope](phaser.rope) - The newly created Rope object. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 296](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L296)) ### sound(key, volume, loop, connect) → {[Phaser.Sound](phaser.sound)} Creates a new Sound object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The Game.cache key of the sound that this object will use. | | `volume` | number | <optional> | 1 | The volume at which the sound will be played. | | `loop` | boolean | <optional> | false | Whether or not the sound will loop. | | `connect` | boolean | <optional> | true | Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. | ##### Returns [Phaser.Sound](phaser.sound) - The newly created sound object. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 246](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L246)) ### sprite(x, y, key, frame, group) → {[Phaser.Sprite](phaser.sprite)} Create a new Sprite with specific position and sprite sheet key. At its most basic a Sprite consists of a set of coordinates and a texture that is used when rendered. They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input), events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | <optional> | 0 | The x coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in. | | `y` | number | <optional> | 0 | The y coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. | | `group` | [Phaser.Group](phaser.group) | <optional> | | Optional Group to add the object to. If not specified it will be added to the World group. | ##### Returns [Phaser.Sprite](phaser.sprite) - The newly created Sprite object. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 102](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L102)) ### spriteBatch(parent, name, addToStage) → {[Phaser.SpriteBatch](phaser.spritebatch)} A SpriteBatch is a really fast version of a Phaser Group built solely for speed. Use when you need a lot of sprites or particles all sharing the same texture. The speed gains are specifically for WebGL. In Canvas mode you won't see any real difference. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | [Phaser.Group](phaser.group) | null | | | The parent Group that will hold this Sprite Batch. Set to `undefined` or `null` to add directly to game.world. | | `name` | string | <optional> | 'group' | A name for this Sprite Batch. Not used internally but useful for debugging. | | `addToStage` | boolean | <optional> | false | If set to true this Sprite Batch will be added directly to the Game.Stage instead of the parent. | ##### Returns [Phaser.SpriteBatch](phaser.spritebatch) - The newly created Sprite Batch. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 209](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L209)) ### text(x, y, text, style, group) → {[Phaser.Text](phaser.text)} Creates a new Text object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | <optional> | 0 | The x coordinate of the Text. The coordinate is relative to any parent container this text may be in. | | `y` | number | <optional> | 0 | The y coordinate of the Text. The coordinate is relative to any parent container this text may be in. | | `text` | string | <optional> | '' | The text string that will be displayed. | | `style` | object | <optional> | | The style object containing style attributes like font, font size , etc. | | `group` | [Phaser.Group](phaser.group) | <optional> | | Optional Group to add the object to. If not specified it will be added to the World group. | ##### Returns [Phaser.Text](phaser.text) - The newly created text object. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 318](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L318)) ### tilemap(key, tileWidth, tileHeight, width, height) → {[Phaser.Tilemap](phaser.tilemap)} Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file. To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. When using CSV data you must provide the key and the tileWidth and tileHeight parameters. If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | <optional> | | The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. | | `tileWidth` | number | <optional> | 32 | The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. | | `tileHeight` | number | <optional> | 32 | The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. | | `width` | number | <optional> | 10 | The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. | | `height` | number | <optional> | 10 | The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. | ##### Returns [Phaser.Tilemap](phaser.tilemap) - The newly created tilemap object. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 461](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L461)) ### tileSprite(x, y, width, height, key, frame, group) → {[Phaser.TileSprite](phaser.tilesprite)} Creates a new TileSprite object. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `x` | number | | The x coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in. | | `y` | number | | The y coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in. | | `width` | number | | The width of the TileSprite. | | `height` | number | | The height of the TileSprite. | | `key` | string | [Phaser.BitmapData](phaser.bitmapdata) | [PIXI.Texture](pixi.texture) | | This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. | | `frame` | string | number | <optional> | If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. | | `group` | [Phaser.Group](phaser.group) | <optional> | Optional Group to add the object to. If not specified it will be added to the World group. | ##### Returns [Phaser.TileSprite](phaser.tilesprite) - The newly created TileSprite object. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 275](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L275)) ### tween(object) → {[Phaser.Tween](phaser.tween)} Create a tween on a specific object. The object can be any JavaScript object or Phaser object such as Sprite. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `object` | object | Object the tween will be run on. | ##### Returns [Phaser.Tween](phaser.tween) - The newly created Phaser.Tween object. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 158](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L158)) ### video(key, url) → {[Phaser.Video](phaser.video)} Create a Video object. This will return a Phaser.Video object which you can pass to a Sprite to be used as a texture. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | null | <optional> | null | The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture. | | `url` | string | null | <optional> | null | If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null) | ##### Returns [Phaser.Video](phaser.video) - The newly created Video object. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 510](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L510)) ### weapon(quantity, key, frame, group) → {[Phaser.Weapon](phaser.weapon)} Weapons provide the ability to easily create a bullet pool and manager. Weapons fire Phaser.Bullet objects, which are essentially Sprites with a few extra properties. The Bullets are enabled for Arcade Physics. They do not currently work with P2 Physics. The Bullets are created inside of `Weapon.bullets`, which is a Phaser.Group instance. Anything you can usually do with a Group, such as move it around the display list, iterate it, etc can be done to the bullets Group too. Bullets can have textures and even animations. You can control the speed at which they are fired, the firing rate, the firing angle, and even set things like gravity for them. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `quantity` | integer | <optional> | 1 | The quantity of bullets to seed the Weapon with. If -1 it will set the pool to automatically expand. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | The image used as a texture by the bullets during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used by the bullets. Use either an integer for a Frame ID or a string for a frame name. | | `group` | [Phaser.Group](phaser.group) | <optional> | | Optional Group to add the Weapon to. If not specified it will be added to the World group. | ##### Returns [Phaser.Weapon](phaser.weapon) - A Weapon instance. Source code: [gameobjects/GameObjectFactory.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js) ([Line 48](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectFactory.js#L48))
programming_docs
phaser Class: Phaser.Physics.P2.GearConstraint Class: Phaser.Physics.P2.GearConstraint ======================================= Constructor ----------- ### new GearConstraint(world, bodyA, bodyB, angle, ratio) Connects two bodies at given offset points, letting them rotate relative to each other around this point. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `world` | [Phaser.Physics.P2](phaser.physics.p2) | | | A reference to the P2 World. | | `bodyA` | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | First connected body. | | `bodyB` | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | Second connected body. | | `angle` | number | <optional> | 0 | The relative angle | | `ratio` | number | <optional> | 1 | The gear ratio. | Source code: [physics/p2/GearConstraint.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/GearConstraint.js) ([Line 18](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/GearConstraint.js#L18)) Public Properties ----------------- ### game : [Phaser.Game](phaser.game) Local reference to game. Source code: [physics/p2/GearConstraint.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/GearConstraint.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/GearConstraint.js#L26)) ### world : [Phaser.Physics.P2](phaser.physics.p2) Local reference to P2 World. Source code: [physics/p2/GearConstraint.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/GearConstraint.js) ([Line 31](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/GearConstraint.js#L31)) phaser Class: Phaser.Easing.Quadratic Class: Phaser.Easing.Quadratic ============================== Constructor ----------- ### new Quadratic() Quadratic easing. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 43](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L43)) Public Methods -------------- ### In(k) → {number} Ease-in. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - k^2. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L45)) ### InOut(k) → {number} Ease-in/out. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 71](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L71)) ### Out(k) → {number} Ease-out. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - k\* (2-k). Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L58)) phaser Class: Phaser.Physics.Arcade.TilemapCollision Class: Phaser.Physics.Arcade.TilemapCollision ============================================= Constructor ----------- ### new TilemapCollision() The Arcade Physics Tile map collision methods. Source code: [physics/arcade/TilemapCollision.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/TilemapCollision.js) ([Line 13](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/TilemapCollision.js#L13)) Public Properties ----------------- ### TILE\_BIAS : number A value added to the delta values during collision with tiles. Adjust this if you get tunneling. Source code: [physics/arcade/TilemapCollision.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/TilemapCollision.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/TilemapCollision.js#L20)) phaser Class: Phaser.World Class: Phaser.World =================== Constructor ----------- ### new World(game) "This world is but a canvas to our imagination." - Henry David Thoreau A game has only one world. The world is an abstract place in which all game objects live. It is not bound by stage limits and can be any size. You look into the world via cameras. All game objects live within the world at world-based coordinates. By default a world is created the same size as your Stage. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | Reference to the current game instance. | Source code: [core/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js) ([Line 19](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js#L19)) Extends ------- * [Phaser.Group](phaser.group) Public Properties ----------------- ### [readonly] \_definedSize : boolean True if the World has been given a specifically defined size (i.e. from a Tilemap or direct in code) or false if it's just matched to the Game dimensions. Source code: [core/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js) ([Line 41](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js#L41)) ### \_height ##### Properties: | Name | Type | Description | | --- | --- | --- | | `height` | number | The defined height of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension. | Source code: [core/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js#L51)) ### \_width ##### Properties: | Name | Type | Description | | --- | --- | --- | | `width` | number | The defined width of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension. | Source code: [core/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js#L46)) ### alive : boolean The alive property is useful for Groups that are children of other Groups and need to be included/excluded in checks like forEachAlive. Inherited From * [Phaser.Group#alive](phaser.group#alive) Default Value * true Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L93)) ### alpha : number The alpha value of the group container. Inherited From * [Phaser.Group#alpha](phaser.group#alpha) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 3003](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L3003)) ### angle : number The angle of rotation of the group container, in degrees. This adjusts the group itself by modifying its local rotation transform. This has no impact on the rotation/angle properties of the children, but it will update their worldTransform and on-screen orientation and position. Inherited From * [Phaser.Group#angle](phaser.group#angle) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2682](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2682)) ### bottom : number The bottom coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#bottom](phaser.group#bottom) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2845](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2845)) ### bounds : [Phaser.Rectangle](phaser.rectangle) The World has no fixed size, but it does have a bounds outside of which objects are no longer considered as being "in world" and you should use this to clean-up the display list and purge dead objects. By default we set the Bounds to be from 0,0 to Game.width,Game.height. I.e. it will match the size given to the game constructor with 0,0 representing the top-left of the display. However 0,0 is actually the center of the world, and if you rotate or scale the world all of that will happen from 0,0. So if you want to make a game in which the world itself will rotate you should adjust the bounds so that 0,0 is the center point, i.e. set them to -1000,-1000,2000,2000 for a 2000x2000 sized world centered around 0,0. Bound of this world that objects can not escape from. Source code: [core/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js#L30)) ### camera : [Phaser.Camera](phaser.camera) Camera instance. Source code: [core/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js) ([Line 35](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js#L35)) ### cameraOffset : [Phaser.Point](phaser.point) If this object is [fixedToCamera](phaser.group#fixedToCamera) then this stores the x/y position offset relative to the top-left of the camera view. If the parent of this Group is also `fixedToCamera` then the offset here is in addition to that and should typically be disabled. Inherited From * [Phaser.Group#cameraOffset](phaser.group#cameraOffset) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 272](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L272)) ### [readonly] centerX : number Gets the X position corresponding to the center point of the world. Source code: [core/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js) ([Line 293](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js#L293)) ### [readonly] centerY : number Gets the Y position corresponding to the center point of the world. Source code: [core/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js) ([Line 306](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js#L306)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### classType : Object The type of objects that will be created when using [create](phaser.group#create) or [createMultiple](phaser.group#createMultiple). Any object may be used but it should extend either Sprite or Image and accept the same constructor arguments: when a new object is created it is passed the following parameters to its constructor: `(game, x, y, key, frame)`. Inherited From * [Phaser.Group#classType](phaser.group#classType) Default Value * [Phaser.Sprite](phaser.sprite) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 130](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L130)) ### cursor : [DisplayObject](global#DisplayObject) The current display object that the group cursor is pointing to, if any. (Can be set manually.) The cursor is a way to iterate through the children in a Group using [next](phaser.group#next) and [previous](phaser.group#previous). Inherited From * [Phaser.Group#cursor](phaser.group#cursor) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 138](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L138)) ### [readonly] cursorIndex : integer The current index of the Group cursor. Advance it with Group.next. Inherited From * [Phaser.Group#cursorIndex](phaser.group#cursorIndex) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 255](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L255)) ### enableBody : boolean If true all Sprites created by, or added to this group, will have a physics body enabled on them. If there are children already in the Group at the time you set this property, they are not changed. The default body type is controlled with [physicsBodyType](phaser.group#physicsBodyType). Inherited From * [Phaser.Group#enableBody](phaser.group#enableBody) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 208](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L208)) ### enableBodyDebug : boolean If true when a physics body is created (via [enableBody](phaser.group#enableBody)) it will create a physics debug object as well. This only works for P2 bodies. Inherited From * [Phaser.Group#enableBodyDebug](phaser.group#enableBodyDebug) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L217)) ### exists : boolean If exists is true the group is updated, otherwise it is skipped. Inherited From * [Phaser.Group#exists](phaser.group#exists) Default Value * true Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 100](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L100)) ### fixedToCamera : boolean A Group that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Group.cameraOffset. Note that the cameraOffset values are in addition to any parent in the display list. So if this Group was in a Group that has x: 200, then this will be added to the cameraOffset.x Inherited From * [Phaser.Group#fixedToCamera](phaser.group#fixedToCamera) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 265](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L265)) ### <internal> game : [Phaser.Game](phaser.game) A reference to the currently running Game. Inherited From * [Phaser.Group#game](phaser.group#game) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L38)) ### hash :array The hash array is an array belonging to this Group into which you can add any of its children via Group.addToHash and Group.removeFromHash. Only children of this Group can be added to and removed from the hash. This hash is used automatically by Phaser Arcade Physics in order to perform non z-index based destructive sorting. However if you don't use Arcade Physics, or this isn't a physics enabled Group, then you can use the hash to perform your own sorting and filtering of Group children without touching their z-index (and therefore display draw order) Inherited From * [Phaser.Group#hash](phaser.group#hash) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 285](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L285)) ### height : number Gets or sets the current height of the game world. The world can never be smaller than the game (canvas) dimensions. Source code: [core/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js) ([Line 268](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js#L268)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### ignoreDestroy : boolean A group with `ignoreDestroy` set to `true` ignores all calls to its `destroy` method. Inherited From * [Phaser.Group#ignoreDestroy](phaser.group#ignoreDestroy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 107](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L107)) ### inputEnableChildren : boolean A Group with `inputEnableChildren` set to `true` will automatically call `inputEnabled = true` on any children *added* to, or *created by*, this Group. If there are children already in the Group at the time you set this property, they are not changed. Inherited From * [Phaser.Group#inputEnableChildren](phaser.group#inputEnableChildren) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 149](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L149)) ### left : number The left coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#left](phaser.group#left) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2761](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2761)) ### [readonly] length : integer Total number of children in this group, regardless of exists/alive status. Inherited From * [Phaser.Group#length](phaser.group#length) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2665](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2665)) ### name : string A name for this group. Not used internally but useful for debugging. Inherited From * [Phaser.Group#name](phaser.group#name) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L49)) ### onChildInputDown : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputDown signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and a reference to the Pointer that caused it. Inherited From * [Phaser.Group#onChildInputDown](phaser.group#onChildInputDown) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 161](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L161)) ### onChildInputOut : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputOut signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and a reference to the Pointer that caused it. Inherited From * [Phaser.Group#onChildInputOut](phaser.group#onChildInputOut) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 198](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L198)) ### onChildInputOver : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputOver signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and a reference to the Pointer that caused it. Inherited From * [Phaser.Group#onChildInputOver](phaser.group#onChildInputOver) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 186](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L186)) ### onChildInputUp : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputUp signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 3 arguments: A reference to the Sprite that triggered the signal, a reference to the Pointer that caused it, and a boolean value `isOver` that tells you if the Pointer is still over the Sprite or not. Inherited From * [Phaser.Group#onChildInputUp](phaser.group#onChildInputUp) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 174](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L174)) ### onDestroy : [Phaser.Signal](phaser.signal) This signal is dispatched when the group is destroyed. Inherited From * [Phaser.Group#onDestroy](phaser.group#onDestroy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 249](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L249)) ### pendingDestroy : boolean A Group is that has `pendingDestroy` set to `true` is flagged to have its destroy method called on the next logic update. You can set it directly to flag the Group to be destroyed on its next update. This is extremely useful if you wish to destroy a Group from within one of its own callbacks or a callback of one of its children. Inherited From * [Phaser.Group#pendingDestroy](phaser.group#pendingDestroy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 119](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L119)) ### physicsBodyType : integer If [enableBody](phaser.group#enableBody) is true this is the type of physics body that is created on new Sprites. The valid values are [Phaser.Physics.ARCADE](phaser.physics#.ARCADE), [Phaser.Physics.P2JS](phaser.physics#.P2JS), [Phaser.Physics.NINJA](phaser.physics#.NINJA), etc. Inherited From * [Phaser.Group#physicsBodyType](phaser.group#physicsBodyType) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 225](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L225)) ### physicsSortDirection : integer If this Group contains Arcade Physics Sprites you can set a custom sort direction via this property. It should be set to one of the Phaser.Physics.Arcade sort direction constants: Phaser.Physics.Arcade.SORT\_NONE Phaser.Physics.Arcade.LEFT\_RIGHT Phaser.Physics.Arcade.RIGHT\_LEFT Phaser.Physics.Arcade.TOP\_BOTTOM Phaser.Physics.Arcade.BOTTOM\_TOP If set to `null` the Group will use whatever Phaser.Physics.Arcade.sortDirection is set to. This is the default behavior. Inherited From * [Phaser.Group#physicsSortDirection](phaser.group#physicsSortDirection) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 243](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L243)) ### [readonly] physicsType : number The const physics body type of this object. Inherited From * [Phaser.Group#physicsType](phaser.group#physicsType) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L86)) ### [readonly] randomX : number Gets a random integer which is lesser than or equal to the current width of the game world. Source code: [core/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js) ([Line 319](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js#L319)) ### [readonly] randomY : number Gets a random integer which is lesser than or equal to the current height of the game world. Source code: [core/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js) ([Line 341](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js#L341)) ### right : number The right coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#right](phaser.group#right) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2789](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2789)) ### rotation : number The angle of rotation of the group container, in radians. This will adjust the group container itself by modifying its rotation. This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position. Inherited From * [Phaser.Group#rotation](phaser.group#rotation) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2987](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2987)) ### top : number The top coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#top](phaser.group#top) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2817](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2817)) ### [readonly] total : integer Total number of existing children in the group. Inherited From * [Phaser.Group#total](phaser.group#total) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2648](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2648)) ### <internal> type : integer Internal Phaser Type value. Inherited From * [Phaser.Group#type](phaser.group#type) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 80](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L80)) ### visible : boolean The visible state of the group. Non-visible Groups and all of their children are not rendered. Inherited From * [Phaser.Group#visible](phaser.group#visible) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2996](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2996)) ### width : number Gets or sets the current width of the game world. The world can never be smaller than the game (canvas) dimensions. Source code: [core/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js) ([Line 243](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js#L243)) ### x : number The x coordinate of the group container. You can adjust the group container itself by modifying its coordinates. This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. Inherited From * [Phaser.Group#x](phaser.group#x) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2969](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2969)) ### y : number The y coordinate of the group container. You can adjust the group container itself by modifying its coordinates. This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. Inherited From * [Phaser.Group#y](phaser.group#y) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2978](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2978)) ### [readonly] z : integer The z-depth value of this object within its parent container/Group - the World is a Group as well. This value must be unique for each child in a Group. Inherited From * [Phaser.Group#z](phaser.group#z) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 57](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L57)) Public Methods -------------- ### add(child, silent, index) → {[DisplayObject](global#DisplayObject)} Adds an existing object as the top child in this group. The child is automatically added to the top of the group, and is displayed above every previous child. Or if the *optional* index is specified, the child is added at the location specified by the index value, this allows you to control child ordering. If the child was already in this Group, it is simply returned, and nothing else happens to it. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. Use [addAt](phaser.group#addAt) to control where a child is added. Use [create](phaser.group#create) to create and add a new child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | | | The display object to add as a child. | | `silent` | boolean | <optional> | false | If true the child will not dispatch the `onAddedToGroup` event. | | `index` | integer | <optional> | | The index within the group to insert the child to. Where 0 is the bottom of the Group. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added to the group. Inherited From * [Phaser.Group#add](phaser.group#add) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 341](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L341)) ### addAll(property, amount, checkAlive, checkVisible) Adds the amount to the given property on all children in this group. `Group.addAll('x', 10)` will add 10 to the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to increment, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Inherited From * [Phaser.Group#addAll](phaser.group#addAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1386](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1386)) ### addAt(child, index, silent) → {[DisplayObject](global#DisplayObject)} Adds an existing object to this group. The child is added to the group at the location specified by the index value, this allows you to control child ordering. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | | | The display object to add as a child. | | `index` | integer | <optional> | 0 | The index within the group to insert the child to. | | `silent` | boolean | <optional> | false | If true the child will not dispatch the `onAddedToGroup` event. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added to the group. Inherited From * [Phaser.Group#addAt](phaser.group#addAt) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 418](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L418)) ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### addMultiple(children, silent) → {Array.<[DisplayObject](global#DisplayObject)> | [Phaser.Group](phaser.group)} Adds an array of existing Display Objects to this Group. The Display Objects are automatically added to the top of this Group, and will render on-top of everything already in this Group. As well as an array you can also pass another Group as the first argument. In this case all of the children from that Group will be removed from it and added into this Group. If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `children` | Array.<[DisplayObject](global#DisplayObject)> | [Phaser.Group](phaser.group) | | | An array of display objects or a Phaser.Group. If a Group is given then *all* children will be moved from it. | | `silent` | boolean | <optional> | false | If true the children will not dispatch the `onAddedToGroup` event. | ##### Returns Array.<[DisplayObject](global#DisplayObject)> | [Phaser.Group](phaser.group) - The array of children or Group of children that were added to this Group. Inherited From * [Phaser.Group#addMultiple](phaser.group#addMultiple) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 489](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L489)) ### addToHash(child) → {boolean} Adds a child of this Group into the hash array. This call will return false if the child is not a child of this Group, or is already in the hash. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The display object to add to this Groups hash. Must be a member of this Group already and not present in the hash. | ##### Returns boolean - True if the child was successfully added to the hash, otherwise false. Inherited From * [Phaser.Group#addToHash](phaser.group#addToHash) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 439](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L439)) ### align(width, height, cellWidth, cellHeight, position, offset) → {boolean} This method iterates through all children in the Group (regardless if they are visible or exist) and then changes their position so they are arranged in a Grid formation. Children must have the `alignTo` method in order to be positioned by this call. All default Phaser Game Objects have this. The grid dimensions are determined by the first four arguments. The `width` and `height` arguments relate to the width and height of the grid respectively. For example if the Group had 100 children in it: `Group.align(10, 10, 32, 32)` This will align all of the children into a grid formation of 10x10, using 32 pixels per grid cell. If you want a wider grid, you could do: `Group.align(25, 4, 32, 32)` This will align the children into a grid of 25x4, again using 32 pixels per grid cell. You can choose to set *either* the `width` or `height` value to -1. Doing so tells the method to keep on aligning children until there are no children left. For example if this Group had 48 children in it, the following: `Group.align(-1, 8, 32, 32)` ... will align the children so that there are 8 children vertically (the second argument), and each row will contain 6 sprites, except the last one, which will contain 5 (totaling 48) You can also do: `Group.align(10, -1, 32, 32)` In this case it will create a grid 10 wide, and as tall as it needs to be in order to fit all of the children in. The `position` property allows you to control where in each grid cell the child is positioned. This is a constant and can be one of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. The final argument; `offset` lets you start the alignment from a specific child index. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `width` | integer | | | The width of the grid in items (not pixels). Set to -1 for a dynamic width. If -1 then you must set an explicit height value. | | `height` | integer | | | The height of the grid in items (not pixels). Set to -1 for a dynamic height. If -1 then you must set an explicit width value. | | `cellWidth` | integer | | | The width of each grid cell, in pixels. | | `cellHeight` | integer | | | The height of each grid cell, in pixels. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offset` | integer | <optional> | 0 | Optional index to start the alignment from. Defaults to zero, the first child in the Group, but can be set to any valid child index value. | ##### Returns boolean - True if the Group children were aligned, otherwise false. Inherited From * [Phaser.Group#align](phaser.group#align) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 682](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L682)) ### alignIn(container, position, offsetX, offsetY) → {[Phaser.Group](phaser.group)} Aligns this Group within another Game Object, or Rectangle, known as the 'container', to one of 9 possible positions. The container must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Groups within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Group to another Game Object does **not** make it a child of the container. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. Groups are placed in such a way that their *bounds* align with the container, taking into consideration rotation and scale of its children. This allows you to neatly align Groups, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Group. For example: `group.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `container` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns [Phaser.Group](phaser.group) - This Group. Inherited From * [Phaser.Group#alignIn](phaser.group#alignIn) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2873](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2873)) ### alignTo(parent, position, offsetX, offsetY) → {[Phaser.Group](phaser.group)} Aligns this Group to the side of another Game Object, or Rectangle, known as the 'parent', in one of 11 possible positions. The parent must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Groups within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Group to another Game Object does **not** make it a child of the parent. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. Groups are placed in such a way that their *bounds* align with the parent, taking into consideration rotation and scale of the children. This allows you to neatly align Groups, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Group. For example: `group.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns [Phaser.Group](phaser.group) - This Group. Inherited From * [Phaser.Group#alignTo](phaser.group#alignTo) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2915](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2915)) ### <internal> ascendingSortHandler(a, b) An internal helper function for the sort process. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | object | The first object being sorted. | | `b` | object | The second object being sorted. | Inherited From * [Phaser.Group#ascendingSortHandler](phaser.group#ascendingSortHandler) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1919](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1919)) ### <internal> boot() Initialises the game world. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js) ([Line 60](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js#L60)) ### bringToTop(child) → {any} Brings the given child to the top of this group so it renders above all other children. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to bring to the top of this group. | ##### Returns any - The child that was moved. Inherited From * [Phaser.Group#bringToTop](phaser.group#bringToTop) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 907](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L907)) ### callAll(method, context, args) Calls a function, specified by name, on all on children. The function is called for all children regardless if they are dead or alive (see callAllExists for different options). After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `method` | string | | | Name of the function on the child to call. Deep property lookup is supported. | | `context` | string | <optional> | null | A string containing the context under which the method will be executed. Set to null to default to the child. | | `args` | any | <repeatable> | | Additional parameters that will be passed to the method. | Inherited From * [Phaser.Group#callAll](phaser.group#callAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1538](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1538)) ### callAllExists(callback, existsValue, parameter) Calls a function, specified by name, on all children in the group who exist (or do not exist). After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `callback` | string | | Name of the function on the children to call. | | `existsValue` | boolean | | Only children with exists=existsValue will be called. | | `parameter` | any | <repeatable> | Additional parameters that will be passed to the callback. | Inherited From * [Phaser.Group#callAllExists](phaser.group#callAllExists) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1454](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1454)) ### <internal> callbackFromArray(child, callback, length) Returns a reference to a function that exists on a child of the group based on the given callback array. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | object | The object to inspect. | | `callback` | array | The array of function names. | | `length` | integer | The size of the array (pre-calculated in callAll). | Inherited From * [Phaser.Group#callbackFromArray](phaser.group#callbackFromArray) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1488](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1488)) ### checkAll(key, value, checkAlive, checkVisible, force) Quickly check that the same property across all children of this group is equal to the given value. This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be checked. | | `checkAlive` | boolean | <optional> | false | If set then only children with alive=true will be checked. This includes any Groups that are children. | | `checkVisible` | boolean | <optional> | false | If set then only children with visible=true will be checked. This includes any Groups that are children. | | `force` | boolean | <optional> | false | If `force` is true then the property will be checked on the child regardless if it already exists or not. If true and the property doesn't exist, false will be returned. | Inherited From * [Phaser.Group#checkAll](phaser.group#checkAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1353](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1353)) ### checkProperty(child, key, value, force) → {boolean} Checks a property for the given value on the child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | any | | | The child to check the property value on. | | `key` | array | | | An array of strings that make up the property that will be set. | | `value` | any | | | The value that will be checked. | | `force` | boolean | <optional> | false | If `force` is true then the property will be checked on the child regardless if it already exists or not. If true and the property doesn't exist, false will be returned. | ##### Returns boolean - True if the property was was equal to value, false if not. Inherited From * [Phaser.Group#checkProperty](phaser.group#checkProperty) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1217)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### countDead() → {integer} Get the number of dead children in this group. ##### Returns integer - The number of children flagged as dead. Inherited From * [Phaser.Group#countDead](phaser.group#countDead) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2338](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2338)) ### countLiving() → {integer} Get the number of living children in this group. ##### Returns integer - The number of children flagged as alive. Inherited From * [Phaser.Group#countLiving](phaser.group#countLiving) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2326](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2326)) ### create(x, y, key, frame, exists, index) → {[DisplayObject](global#DisplayObject)} Creates a new Phaser.Sprite object and adds it to the top of this group. Use [classType](phaser.group#classType) to change the type of object created. The child is automatically added to the top of the group, and is displayed above every previous child. Or if the *optional* index is specified, the child is added at the location specified by the index value, this allows you to control child ordering. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate to display the newly created Sprite at. The value is in relation to the group.x point. | | `y` | number | | | The y coordinate to display the newly created Sprite at. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | | `exists` | boolean | <optional> | true | The default exists state of the Sprite. | | `index` | integer | <optional> | | The index within the group to insert the child to. Where 0 is the bottom of the Group. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was created: will be a [Phaser.Sprite](phaser.sprite) unless #classType has been changed. Inherited From * [Phaser.Group#create](phaser.group#create) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 544](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L544)) ### createMultiple(quantity, key, frame, exists) → {array} Creates multiple Phaser.Sprite objects and adds them to the top of this Group. This method is useful if you need to quickly generate a pool of sprites, such as bullets. Use [classType](phaser.group#classType) to change the type of object created. You can provide an array as the `key` and / or `frame` arguments. When you do this it will create `quantity` Sprites for every key (and frame) in the arrays. For example: `createMultiple(25, ['ball', 'carrot'])` In the above code there are 2 keys (ball and carrot) which means that 50 sprites will be created in total, 25 of each. You can also have the `frame` as an array: `createMultiple(5, 'bricks', [0, 1, 2, 3])` In the above there is one key (bricks), which is a sprite sheet. The frames array tells this method to use frames 0, 1, 2 and 3. So in total it will create 20 sprites, because the quantity was set to 5, so that is 5 brick sprites of frame 0, 5 brick sprites with frame 1, and so on. If you set both the key and frame arguments to be arrays then understand it will create a total quantity of sprites equal to the size of both arrays times each other. I.e.: `createMultiple(20, ['diamonds', 'balls'], [0, 1, 2])` The above will create 20 'diamonds' of frame 0, 20 with frame 1 and 20 with frame 2. It will then create 20 'balls' of frame 0, 20 with frame 1 and 20 with frame 2. In total it will have created 120 sprites. By default the Sprites will have their `exists` property set to `false`, and they will be positioned at 0x0, relative to the `Group.x / y` values. If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `quantity` | integer | | | The number of Sprites to create. | | `key` | string | array | | | The Cache key of the image that the Sprites will use. Or an Array of keys. See the description for details on how the quantity applies when arrays are used. | | `frame` | integer | string | array | <optional> | 0 | If the Sprite image contains multiple frames you can specify which one to use here. Or an Array of frames. See the description for details on how the quantity applies when arrays are used. | | `exists` | boolean | <optional> | false | The default exists state of the Sprite. | ##### Returns array - An array containing all of the Sprites that were created. Inherited From * [Phaser.Group#createMultiple](phaser.group#createMultiple) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 581](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L581)) ### customSort(sortHandler, context) Sort the children in the group according to custom sort function. The `sortHandler` is provided the two parameters: the two children involved in the comparison (a and b). It should return -1 if `a > b`, 1 if `a < b` or 0 if `a === b`. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `sortHandler` | function | | The custom sort function. | | `context` | object | <optional> | The context in which the sortHandler is called. | Inherited From * [Phaser.Group#customSort](phaser.group#customSort) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1895](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1895)) ### <internal> descendingSortHandler(a, b) An internal helper function for the sort process. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | object | The first object being sorted. | | `b` | object | The second object being sorted. | Inherited From * [Phaser.Group#descendingSortHandler](phaser.group#descendingSortHandler) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1951](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1951)) ### destroy(destroyChildren, soft) Destroys this group. Removes all children, then removes this group from its parent and nulls references. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroyChildren` | boolean | <optional> | true | If true `destroy` will be invoked on each removed child. | | `soft` | boolean | <optional> | false | A 'soft destroy' (set to true) doesn't remove this group from its parent or null the game reference. Set to false and it does. | Inherited From * [Phaser.Group#destroy](phaser.group#destroy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2611](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2611)) ### divideAll(property, amount, checkAlive, checkVisible) Divides the given property by the amount on all children in this group. `Group.divideAll('x', 2)` will half the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to divide, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Inherited From * [Phaser.Group#divideAll](phaser.group#divideAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1437](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1437)) ### filter(predicate, checkExists) → {[Phaser.ArraySet](phaser.arrayset)} Find children matching a certain predicate. For example: ``` var healthyList = Group.filter(function(child, index, children) { return child.health > 10 ? true : false; }, true); healthyList.callAll('attack'); ``` Note: Currently this will skip any children which are Groups themselves. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `predicate` | function | | | The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, the index as the second, and the entire child array as the third | | `checkExists` | boolean | <optional> | false | If true, only existing can be selected; otherwise all children can be selected and will be passed to the predicate. | ##### Returns [Phaser.ArraySet](phaser.arrayset) - Returns an array list containing all the children that the predicate returned true for Inherited From * [Phaser.Group#filter](phaser.group#filter) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1677](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1677)) ### forEach(callback, callbackContext, checkExists, args) Call a function on each child in this group. Additional arguments for the callback can be specified after the `checkExists` parameter. For example, ``` Group.forEach(awardBonusGold, this, true, 100, 500) ``` would invoke `awardBonusGold` function with the parameters `(child, 100, 500)`. Note: This check will skip any children which are Groups themselves. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `checkExists` | boolean | <optional> | false | If set only children matching for which `exists` is true will be passed to the callback, otherwise all children will be passed. | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Inherited From * [Phaser.Group#forEach](phaser.group#forEach) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1717](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1717)) ### forEachAlive(callback, callbackContext, args) Call a function on each alive child in this group. See [forEach](phaser.group#forEach) for details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Inherited From * [Phaser.Group#forEachAlive](phaser.group#forEachAlive) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1799](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1799)) ### forEachDead(callback, callbackContext, args) Call a function on each dead child in this group. See [forEach](phaser.group#forEach) for details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Inherited From * [Phaser.Group#forEachDead](phaser.group#forEachDead) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1827](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1827)) ### forEachExists(callback, callbackContext, args) Call a function on each existing child in this group. See [forEach](phaser.group#forEach) for details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Inherited From * [Phaser.Group#forEachExists](phaser.group#forEachExists) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1771](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1771)) ### getAll(property, value, startIndex, endIndex) → {any} Returns all children in this Group. You can optionally specify a matching criteria using the `property` and `value` arguments. For example: `getAll('exists', true)` would return only children that have their exists property set. Optionally you can specify a start and end index. For example if this Group had 100 children, and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only the first 50 children in the Group. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `property` | string | <optional> | | An optional property to test against the value argument. | | `value` | any | <optional> | | If property is set then Child.property must strictly equal this value to be included in the results. | | `startIndex` | integer | <optional> | 0 | The first child index to start the search from. | | `endIndex` | integer | <optional> | | The last child index to search up until. | ##### Returns any - A random existing child of this Group. Inherited From * [Phaser.Group#getAll](phaser.group#getAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2392](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2392)) ### getAt(index) → {[DisplayObject](global#DisplayObject) | integer} Returns the child found at the given index within this group. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | integer | The index to return the child from. | ##### Returns [DisplayObject](global#DisplayObject) | integer - The child that was found at the given index, or -1 for an invalid index. Inherited From * [Phaser.Group#getAt](phaser.group#getAt) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 524](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L524)) ### getBottom() → {any} Returns the child at the bottom of this group. The bottom child the child being displayed (rendered) below every other child. ##### Returns any - The child at the bottom of the Group. Inherited From * [Phaser.Group#getBottom](phaser.group#getBottom) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2221](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2221)) ### getBounds(targetCoordinateSpace) → {Rectangle} Retrieves the global bounds of the displayObjectContainer as a rectangle. The bounds calculation takes all visible children into consideration. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `targetCoordinateSpace` | PIXIDisplayObject | PIXIMatrix | <optional> | Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object. | ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.DisplayObjectContainer#getBounds](pixi.displayobjectcontainer#getBounds) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 280](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L280)) ### getByName(name) → {any} Searches the Group for the first instance of a child with the `name` property matching the given argument. Should more than one child have the same name only the first instance is returned. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `name` | string | The name to search for. | ##### Returns any - The first child with a matching name, or null if none were found. Inherited From * [Phaser.Group#getByName](phaser.group#getByName) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1042](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1042)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getClosestTo(object, callback, callbackContext) → {any} Get the closest child to given Object, with optional callback to filter children. This can be a Sprite, Group, Image or any object with public x and y properties. 'close' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. You can use the optional `callback` argument to apply your own filter to the distance checks. If the child is closer then the previous child, it will be sent to `callback` as the first argument, with the distance as the second. The callback should return `true` if it passes your filtering criteria, otherwise it should return `false`. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `object` | any | | The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. | | `callback` | function | <optional> | The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. | | `callbackContext` | object | <optional> | The context in which the function should be called (usually 'this'). | ##### Returns any - The child closest to given object, or `null` if no child was found. Inherited From * [Phaser.Group#getClosestTo](phaser.group#getClosestTo) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2238](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2238)) ### getFirstAlive(createIfNull, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Get the first child that is alive (`child.alive === true`). This is handy for choosing a squad leader, etc. You can use the optional argument `createIfNull` to create a new Game Object if no alive ones were found in this Group. It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `createIfNull` | boolean | <optional> | false | If `true` and no alive children are found a new one is created. | | `x` | number | <optional> | | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The alive dead child, or `null` if none found and `createIfNull` was false. Inherited From * [Phaser.Group#getFirstAlive](phaser.group#getFirstAlive) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2105](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2105)) ### getFirstDead(createIfNull, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Get the first child that is dead (`child.alive === false`). This is handy for checking if everything has been wiped out and adding to the pool as needed. You can use the optional argument `createIfNull` to create a new Game Object if no dead ones were found in this Group. It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `createIfNull` | boolean | <optional> | false | If `true` and no dead children are found a new one is created. | | `x` | number | <optional> | | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The first dead child, or `null` if none found and `createIfNull` was false. Inherited From * [Phaser.Group#getFirstDead](phaser.group#getFirstDead) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2135](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2135)) ### getFirstExists(exists, createIfNull, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Get the first display object that exists, or doesn't exist. You can use the optional argument `createIfNull` to create a new Game Object if none matching your exists argument were found in this Group. It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `exists` | boolean | <optional> | true | If true, find the first existing child; otherwise find the first non-existing child. | | `createIfNull` | boolean | <optional> | false | If `true` and no alive children are found a new one is created. | | `x` | number | <optional> | | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The first child, or `null` if none found and `createIfNull` was false. Inherited From * [Phaser.Group#getFirstExists](phaser.group#getFirstExists) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2071](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2071)) ### getFurthestFrom(object, callback, callbackContext) → {any} Get the child furthest away from the given Object, with optional callback to filter children. This can be a Sprite, Group, Image or any object with public x and y properties. 'furthest away' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. You can use the optional `callback` argument to apply your own filter to the distance checks. If the child is closer then the previous child, it will be sent to `callback` as the first argument, with the distance as the second. The callback should return `true` if it passes your filtering criteria, otherwise it should return `false`. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `object` | any | | The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. | | `callback` | function | <optional> | The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. | | `callbackContext` | object | <optional> | The context in which the function should be called (usually 'this'). | ##### Returns any - The child furthest from the given object, or `null` if no child was found. Inherited From * [Phaser.Group#getFurthestFrom](phaser.group#getFurthestFrom) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2282](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2282)) ### getIndex(child) → {integer} Get the index position of the given child in this group, which should match the child's `z` property. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to get the index for. | ##### Returns integer - The index of the child or -1 if it's not a member of this group. Inherited From * [Phaser.Group#getIndex](phaser.group#getIndex) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1029](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1029)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the displayObjectContainer as a rectangle without any transformations. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.DisplayObjectContainer#getLocalBounds](pixi.displayobjectcontainer#getLocalBounds) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 437](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L437)) ### getRandom(startIndex, length) → {any} Returns a random child from the group. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `startIndex` | integer | <optional> | 0 | Offset from the front of the group (lowest child). | | `length` | integer | <optional> | (to top) | Restriction on the number of values you want to randomly select from. | ##### Returns any - A random child of this Group. Inherited From * [Phaser.Group#getRandom](phaser.group#getRandom) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2350](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2350)) ### getRandomExists(startIndex, endIndex) → {any} Returns a random child from the Group that has `exists` set to `true`. Optionally you can specify a start and end index. For example if this Group had 100 children, and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only the first 50 children in the Group. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `startIndex` | integer | <optional> | 0 | The first child index to start the search from. | | `endIndex` | integer | <optional> | | The last child index to search up to. | ##### Returns any - A random child of this Group that exists. Inherited From * [Phaser.Group#getRandomExists](phaser.group#getRandomExists) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2372](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2372)) ### getTop() → {any} Return the child at the top of this group. The top child is the child displayed (rendered) above every other child. ##### Returns any - The child at the top of the Group. Inherited From * [Phaser.Group#getTop](phaser.group#getTop) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2204](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2204)) ### hasProperty(child, key) → {boolean} Checks if the child has the given property. Will scan up to 4 levels deep only. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to check for the existence of the property on. | | `key` | Array.<string> | An array of strings that make up the property. | ##### Returns boolean - True if the child has the property, otherwise false. Inherited From * [Phaser.Group#hasProperty](phaser.group#hasProperty) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1104](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1104)) ### iterate(key, value, returnType, callback, callbackContext, args) → {any} Iterates over the children of the group performing one of several actions for matched children. A child is considered a match when it has a property, named `key`, whose value is equal to `value` according to a strict equality comparison. The result depends on the `returnType`: * [RETURN\_TOTAL](phaser.group#.RETURN_TOTAL): The callback, if any, is applied to all matching children. The number of matched children is returned. * [RETURN\_NONE](phaser.group#.RETURN_NONE): The callback, if any, is applied to all matching children. No value is returned. * [RETURN\_CHILD](phaser.group#.RETURN_CHILD): The callback, if any, is applied to the *first* matching child and the *first* matched child is returned. If there is no matching child then null is returned. If `args` is specified it must be an array. The matched child will be assigned to the first element and the entire array will be applied to the callback function. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The child property to check, i.e. 'exists', 'alive', 'health' | | `value` | any | | | A child matches if `child[key] === value` is true. | | `returnType` | integer | | | How to iterate the children and what to return. | | `callback` | function | <optional> | null | Optional function that will be called on each matching child. The matched child is supplied as the first argument. | | `callbackContext` | object | <optional> | | The context in which the function should be called (usually 'this'). | | `args` | Array.<any> | <optional> | (none) | The arguments supplied to to the callback; the first array index (argument) will be replaced with the matched child. | ##### Returns any - Returns either an integer (for RETURN\_TOTAL), the first matched child (for RETURN\_CHILD), or null. Inherited From * [Phaser.Group#iterate](phaser.group#iterate) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1976](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1976)) ### moveAll(group, silent) → {[Phaser.Group](phaser.group)} Moves all children from this Group to the Group given. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `group` | [Phaser.Group](phaser.group) | | | The new Group to which the children will be moved to. | | `silent` | boolean | <optional> | false | If true the children will not dispatch the `onAddedToGroup` event for the new Group. | ##### Returns [Phaser.Group](phaser.group) - The Group to which all the children were moved. Inherited From * [Phaser.Group#moveAll](phaser.group#moveAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2479](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2479)) ### moveDown(child) → {any} Moves the given child down one place in this group unless it's already at the bottom. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to move down in the group. | ##### Returns any - The child that was moved. Inherited From * [Phaser.Group#moveDown](phaser.group#moveDown) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 969](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L969)) ### moveUp(child) → {any} Moves the given child up one place in this group unless it's already at the top. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to move up in the group. | ##### Returns any - The child that was moved. Inherited From * [Phaser.Group#moveUp](phaser.group#moveUp) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 945](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L945)) ### multiplyAll(property, amount, checkAlive, checkVisible) Multiplies the given property by the amount on all children in this group. `Group.multiplyAll('x', 2)` will x2 the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to multiply, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Inherited From * [Phaser.Group#multiplyAll](phaser.group#multiplyAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1420](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1420)) ### next() → {any} Advances the group cursor to the next (higher) object in the group. If the cursor is at the end of the group (top child) it is moved the start of the group (bottom child). ##### Returns any - The child the cursor now points to. Inherited From * [Phaser.Group#next](phaser.group#next) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 833](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L833)) ### <internal> postUpdate() The core postUpdate - as called by World. Inherited From * [Phaser.Group#postUpdate](phaser.group#postUpdate) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1656](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1656)) ### <internal> preUpdate() The core preUpdate - as called by World. Inherited From * [Phaser.Group#preUpdate](phaser.group#preUpdate) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1611](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1611)) ### previous() → {any} Moves the group cursor to the previous (lower) child in the group. If the cursor is at the start of the group (bottom child) it is moved to the end (top child). ##### Returns any - The child the cursor now points to. Inherited From * [Phaser.Group#previous](phaser.group#previous) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 862](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L862)) ### remove(child, destroy, silent) → {boolean} Removes the given child from this group. This will dispatch an `onRemovedFromGroup` event from the child (if it has one), and optionally destroy the child. If the group cursor was referring to the removed child it is updated to refer to the next child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | any | | | The child to remove. | | `destroy` | boolean | <optional> | false | If true `destroy` will be invoked on the removed child. | | `silent` | boolean | <optional> | false | If true the the child will not dispatch the `onRemovedFromGroup` event. | ##### Returns boolean - true if the child was removed from this group, otherwise false. Inherited From * [Phaser.Group#remove](phaser.group#remove) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2431](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2431)) ### removeAll(destroy, silent, destroyTexture) Removes all children from this Group, but does not remove the group from its parent. The children can be optionally destroyed as they are removed. You can also optionally also destroy the BaseTexture the Child is using. Be careful if you've more than one Game Object sharing the same BaseTexture. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroy` | boolean | <optional> | false | If true `destroy` will be invoked on each removed child. | | `silent` | boolean | <optional> | false | If true the children will not dispatch their `onRemovedFromGroup` events. | | `destroyTexture` | boolean | <optional> | false | If true, and if the `destroy` argument is also true, the BaseTexture belonging to the Child is also destroyed. Note that if another Game Object is sharing the same BaseTexture it will invalidate it. | Inherited From * [Phaser.Group#removeAll](phaser.group#removeAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2508](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2508)) ### removeBetween(startIndex, endIndex, destroy, silent) Removes all children from this group whose index falls beteen the given startIndex and endIndex values. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `startIndex` | integer | | | The index to start removing children from. | | `endIndex` | integer | <optional> | | The index to stop removing children at. Must be higher than startIndex. If undefined this method will remove all children between startIndex and the end of the group. | | `destroy` | boolean | <optional> | false | If true `destroy` will be invoked on each removed child. | | `silent` | boolean | <optional> | false | If true the children will not dispatch their `onRemovedFromGroup` events. | Inherited From * [Phaser.Group#removeBetween](phaser.group#removeBetween) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2556](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2556)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### removeFromHash(child) → {boolean} Removes a child of this Group from the hash array. This call will return false if the child is not in the hash. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The display object to remove from this Groups hash. Must be a member of this Group and in the hash. | ##### Returns boolean - True if the child was successfully removed from the hash, otherwise false. Inherited From * [Phaser.Group#removeFromHash](phaser.group#removeFromHash) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 464](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L464)) ### replace(oldChild, newChild) → {any} Replaces a child of this Group with the given newChild. The newChild cannot be a member of this Group. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `oldChild` | any | The child in this group that will be replaced. | | `newChild` | any | The child to be inserted into this group. | ##### Returns any - Returns the oldChild that was replaced within this group. Inherited From * [Phaser.Group#replace](phaser.group#replace) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1065](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1065)) ### resetChild(child, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Takes a child and if the `x` and `y` arguments are given it calls `child.reset(x, y)` on it. If the `key` and optionally the `frame` arguments are given, it calls `child.loadTexture(key, frame)` on it. The two operations are separate. For example if you just wish to load a new texture then pass `null` as the x and y values. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | | The child to reset and/or load the texture on. | | `x` | number | <optional> | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was reset: usually a [Phaser.Sprite](phaser.sprite). Inherited From * [Phaser.Group#resetChild](phaser.group#resetChild) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2165](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2165)) ### resetCursor(index) → {any} Sets the group cursor to the first child in the group. If the optional index parameter is given it sets the cursor to the object at that index instead. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `index` | integer | <optional> | 0 | Set the cursor to point to a specific index. | ##### Returns any - The child the cursor now points to. Inherited From * [Phaser.Group#resetCursor](phaser.group#resetCursor) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 806](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L806)) ### resize(width, height) Updates the size of this world. Note that this doesn't modify the world x/y coordinates, just the width and height. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `width` | number | New width of the game world in pixels. | | `height` | number | New height of the game world in pixels. | Source code: [core/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js) ([Line 125](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js#L125)) ### reverse() Reverses all children in this group. This operation applies only to immediate children and does not propagate to subgroups. Inherited From * [Phaser.Group#reverse](phaser.group#reverse) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1015](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1015)) ### sendToBack(child) → {any} Sends the given child to the bottom of this group so it renders below all other children. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to send to the bottom of this group. | ##### Returns any - The child that was moved. Inherited From * [Phaser.Group#sendToBack](phaser.group#sendToBack) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 926](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L926)) ### set(child, key, value, checkAlive, checkVisible, operation, force) → {boolean} Quickly set a property on a single child of this group to a new value. The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | [Phaser.Sprite](phaser.sprite) | | | The child to set the property on. | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be set. | | `checkAlive` | boolean | <optional> | false | If set then the child will only be updated if alive=true. | | `checkVisible` | boolean | <optional> | false | If set then the child will only be updated if visible=true. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | ##### Returns boolean - True if the property was set, false if not. Inherited From * [Phaser.Group#set](phaser.group#set) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1246](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1246)) ### setAll(key, value, checkAlive, checkVisible, operation, force) Quickly set the same property across all children of this group to a new value. This call doesn't descend down children, so if you have a Group inside of this group, the property will be set on the group but not its children. If you need that ability please see `Group.setAllChildren`. The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be set. | | `checkAlive` | boolean | <optional> | false | If set then only children with alive=true will be updated. This includes any Groups that are children. | | `checkVisible` | boolean | <optional> | false | If set then only children with visible=true will be updated. This includes any Groups that are children. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | Inherited From * [Phaser.Group#setAll](phaser.group#setAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1277](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1277)) ### setAllChildren(key, value, checkAlive, checkVisible, operation, force) Quickly set the same property across all children of this group, and any child Groups, to a new value. If this group contains other Groups then the same property is set across their children as well, iterating down until it reaches the bottom. Unlike with `setAll` the property is NOT set on child Groups itself. The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be set. | | `checkAlive` | boolean | <optional> | false | If set then only children with alive=true will be updated. This includes any Groups that are children. | | `checkVisible` | boolean | <optional> | false | If set then only children with visible=true will be updated. This includes any Groups that are children. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | Inherited From * [Phaser.Group#setAllChildren](phaser.group#setAllChildren) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1312](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1312)) ### setBounds(x, y, width, height) Updates the size of this world and sets World.x/y to the given values The Camera bounds and Physics bounds (if set) are also updated to match the new World bounds. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Top left most corner of the world. | | `y` | number | Top left most corner of the world. | | `width` | number | New width of the game world in pixels. | | `height` | number | New height of the game world in pixels. | Source code: [core/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js) ([Line 94](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js#L94)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### setProperty(child, key, value, operation, force) → {boolean} Sets a property to the given value on the child. The operation parameter controls how the value is set. The operations are: * 0: set the existing value to the given value; if force is `true` a new property will be created if needed * 1: will add the given value to the value already present. * 2: will subtract the given value from the value already present. * 3: will multiply the value already present by the given value. * 4: will divide the value already present by the given value. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | any | | | The child to set the property value on. | | `key` | array | | | An array of strings that make up the property that will be set. | | `value` | any | | | The value that will be set. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | ##### Returns boolean - True if the property was set, false if not. Inherited From * [Phaser.Group#setProperty](phaser.group#setProperty) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1139](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1139)) ### shutdown() Destroyer of worlds. Source code: [core/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js) ([Line 158](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js#L158)) ### sort(key, order) Sort the children in the group according to a particular key and ordering. Call this function to sort the group according to a particular key value and order. For example to depth sort Sprites for Zelda-style game you might call `group.sort('y', Phaser.Group.SORT_ASCENDING)` at the bottom of your `State.update()`. Internally this uses a standard JavaScript Array sort, so everything that applies there also applies here, including alphabetical sorting, mixing strings and numbers, and Unicode sorting. See MDN for more details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | <optional> | 'z' | The name of the property to sort on. Defaults to the objects z-depth value. | | `order` | integer | <optional> | Phaser.Group.SORT\_ASCENDING | Order ascending ([SORT\_ASCENDING](phaser.group#.SORT_ASCENDING)) or descending ([SORT\_DESCENDING](phaser.group#.SORT_DESCENDING)). | Inherited From * [Phaser.Group#sort](phaser.group#sort) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1855](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1855)) ### <internal> stateChange() Called whenever the State changes or resets. It resets the world.x and world.y coordinates back to zero, then resets the Camera. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js) ([Line 76](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js#L76)) ### subAll(property, amount, checkAlive, checkVisible) Subtracts the amount from the given property on all children in this group. `Group.subAll('x', 10)` will minus 10 from the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to decrement, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Inherited From * [Phaser.Group#subAll](phaser.group#subAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1403](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1403)) ### swap(child1, child2) Swaps the position of two children in this group. Both children must be in this group, a child cannot be swapped with itself, and unparented children cannot be swapped. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child1` | any | The first child to swap. | | `child2` | any | The second child to swap. | Inherited From * [Phaser.Group#swap](phaser.group#swap) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 891](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L891)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) ### <internal> update() The core update - as called by World. Inherited From * [Phaser.Group#update](phaser.group#update) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1639](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1639)) ### <internal> updateZ() Internal method that re-applies all of the children's Z values. This must be called whenever children ordering is altered so that their `z` indices are correctly updated. Inherited From * [Phaser.Group#updateZ](phaser.group#updateZ) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 663](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L663)) ### wrap(sprite, padding, useBounds, horizontal, vertical) This will take the given game object and check if its x/y coordinates fall outside of the world bounds. If they do it will reposition the object to the opposite side of the world, creating a wrap-around effect. If sprite has a P2 body then the body (sprite.body) should be passed as first parameter to the function. Please understand there are limitations to this method. For example if you have scaled the World then objects won't always be re-positioned correctly, and you'll need to employ your own wrapping function. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `sprite` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.TileSprite](phaser.tilesprite) | [Phaser.Text](phaser.text) | | | The object you wish to wrap around the world bounds. | | `padding` | number | <optional> | 0 | Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true. | | `useBounds` | boolean | <optional> | false | If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive. | | `horizontal` | boolean | <optional> | true | If horizontal is false, wrap will not wrap the object.x coordinates horizontally. | | `vertical` | boolean | <optional> | true | If vertical is false, wrap will not wrap the object.y coordinates vertically. | Source code: [core/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js) ([Line 170](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/World.js#L170)) ### xy(index, x, y) Positions the child found at the given index within this group to the given x and y coordinates. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | integer | The index of the child in the group to set the position of. | | `x` | number | The new x position of the child. | | `y` | number | The new y position of the child. | Inherited From * [Phaser.Group#xy](phaser.group#xy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 993](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L993))
programming_docs
phaser Class: Phaser.Particle Class: Phaser.Particle ====================== Constructor ----------- ### new Particle(game, x, y, key, frame) Create a new `Particle` object. Particles are extended Sprites that are emitted by a particle emitter such as Phaser.Particles.Arcade.Emitter. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | | `x` | number | The x coordinate (in world space) to position the Particle at. | | `y` | number | The y coordinate (in world space) to position the Particle at. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [PIXI.Texture](pixi.texture) | This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. | | `frame` | string | number | If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | Source code: [gameobjects/Particle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Particle.js) ([Line 19](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Particle.js#L19)) Extends ------- * [Phaser.Sprite](phaser.sprite) Public Properties ----------------- ### alive : boolean A useful flag to control if the Game Object is alive or dead. This is set automatically by the Health components `damage` method should the object run out of health. Or you can toggle it via your game code. This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. Inherited From * [Phaser.Component.LifeSpan#alive](phaser.component.lifespan#alive) Default Value * true Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L50)) ### <internal> alphaData :array A reference to the alphaData array owned by the Emitter that emitted this Particle. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/Particle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Particle.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Particle.js#L51)) ### anchor :Point The anchor sets the origin point of the texture. The default is 0,0 this means the texture's origin is the top left Setting than anchor to 0.5,0.5 means the textures origin is centered Setting the anchor to 1,1 would mean the textures origin points will be the bottom right corner Inherited From * [PIXI.Sprite#anchor](pixi.sprite#anchor) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L17)) ### angle : number The angle property is the rotation of the Game Object in *degrees* from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90. If you wish to work in radians instead of degrees you can use the property `rotation` instead. Working in radians is slightly faster as it doesn't have to perform any calculations. Inherited From * [Phaser.Component.Angle#angle](phaser.component.angle#angle) Source code: [gameobjects/components/Angle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js#L29)) ### animations : [Phaser.AnimationManager](phaser.animationmanager) If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. Through it you can create, play, pause and stop animations. Inherited From * [Phaser.Component.Core#animations](phaser.component.core#animations) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 193](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L193)) See * [Phaser.AnimationManager](phaser.animationmanager) ### <internal> autoAlpha : boolean If this Particle automatically changes alpha this is set to true by Particle.setAlphaData. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/Particle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Particle.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Particle.js#L45)) ### autoCull : boolean A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, or you have tested performance and find it acceptable. Inherited From * [Phaser.Component.AutoCull#autoCull](phaser.component.autocull#autoCull) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L28)) ### <internal> autoScale : boolean If this Particle automatically scales this is set to true by Particle.setScaleData. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/Particle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Particle.js) ([Line 27](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Particle.js#L27)) ### blendMode : number The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode. Warning: You cannot have a blend mode and a filter active on the same Sprite. Doing so will render the sprite invisible. Inherited From * [PIXI.Sprite#blendMode](pixi.sprite#blendMode) Default Value * PIXI.blendModes.NORMAL; Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 82](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L82)) ### body : [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | null `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated properties and methods via it. By default Game Objects won't add themselves to any physics system and their `body` property will be `null`. To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`. You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group. Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5, so the physics body is centered on the Game Object. If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics. ##### Type * [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | null Inherited From * [Phaser.Component.PhysicsBody#body](phaser.component.physicsbody#body) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 91](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L91)) ### bottom : number The sum of the y and height properties. This is the same as `y + height - offsetY`. Inherited From * [Phaser.Component.Bounds#bottom](phaser.component.bounds#bottom) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 168](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L168)) ### cameraOffset : [Phaser.Point](phaser.point) The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. Inherited From * [Phaser.Component.FixedToCamera#cameraOffset](phaser.component.fixedtocamera#cameraOffset) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L86)) ### centerX : number The center x coordinate of the Game Object. This is the same as `(x - offsetX) + (width / 2)`. Inherited From * [Phaser.Component.Bounds#centerX](phaser.component.bounds#centerX) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L58)) ### centerY : number The center y coordinate of the Game Object. This is the same as `(y - offsetY) + (height / 2)`. Inherited From * [Phaser.Component.Bounds#centerY](phaser.component.bounds#centerY) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 80](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L80)) ### checkWorldBounds : boolean If this is set to `true` the Game Object checks if it is within the World bounds each frame. When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event. If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event. It also optionally kills the Game Object if `outOfBoundsKill` is `true`. When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame. This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, or you have tested performance and find it acceptable. Inherited From * [Phaser.Component.InWorld#checkWorldBounds](phaser.component.inworld#checkWorldBounds) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L98)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### <internal> components : Object The components this Game Object has installed. Inherited From * [Phaser.Component.Core#components](phaser.component.core#components) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 167](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L167)) ### cropRect : [Phaser.Rectangle](phaser.rectangle) The Rectangle used to crop the texture this Game Object uses. Set this property via `crop`. If you modify this property directly you must call `updateCrop` in order to have the change take effect. Inherited From * [Phaser.Component.Crop#cropRect](phaser.component.crop#cropRect) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L24)) ### damage Damages the Game Object. This removes the given amount of health from the `health` property. If health is taken below or is equal to zero then the `kill` method is called. Inherited From * [Phaser.Component.Health#damage](phaser.component.health#damage) Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L46)) ### data : Object An empty Object that belongs to this Game Object. This value isn't ever used internally by Phaser, but may be used by your own code, or by Phaser Plugins, to store data that needs to be associated with the Game Object, without polluting the Game Object directly. Inherited From * [Phaser.Component.Core#data](phaser.component.core#data) Default Value * {} Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 160](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L160)) ### debug : boolean A debug flag designed for use with `Game.enableStep`. Inherited From * [Phaser.Component.Core#debug](phaser.component.core#debug) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 218](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L218)) ### [readonly] deltaX : number Returns the delta x value. The difference between world.x now and in the previous frame. The value will be positive if the Game Object has moved to the right or negative if to the left. Inherited From * [Phaser.Component.Delta#deltaX](phaser.component.delta#deltaX) Source code: [gameobjects/components/Delta.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js#L24)) ### [readonly] deltaY : number Returns the delta y value. The difference between world.y now and in the previous frame. The value will be positive if the Game Object has moved down or negative if up. Inherited From * [Phaser.Component.Delta#deltaY](phaser.component.delta#deltaY) Source code: [gameobjects/components/Delta.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js#L42)) ### [readonly] deltaZ : number Returns the delta z value. The difference between rotation now and in the previous frame. The delta value. Inherited From * [Phaser.Component.Delta#deltaZ](phaser.component.delta#deltaZ) Source code: [gameobjects/components/Delta.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js#L58)) ### [readonly] destroyPhase : boolean As a Game Object runs through its destroy method this flag is set to true, and can be checked in any sub-systems or plugins it is being destroyed from. Inherited From * [Phaser.Component.Destroy#destroyPhase](phaser.component.destroy#destroyPhase) Source code: [gameobjects/components/Destroy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js#L22)) ### events : [Phaser.Events](phaser.events) All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this Game Object, or any of its components. Inherited From * [Phaser.Component.Core#events](phaser.component.core#events) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 185](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L185)) See * [Phaser.Events](phaser.events) ### exists : boolean Controls if this Sprite is processed by the core Phaser game loops and Group loops. Inherited From * [PIXI.Sprite#exists](pixi.sprite#exists) Default Value * true Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 103](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L103)) ### fixedToCamera : boolean A Game Object that is "fixed" to the camera uses its x/y coordinates as offsets from the top left of the camera during rendering. The values are adjusted at the rendering stage, overriding the Game Objects actual world position. The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times regardless where in the world the camera is. The offsets are stored in the `cameraOffset` property. Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. Inherited From * [Phaser.Component.FixedToCamera#fixedToCamera](phaser.component.fixedtocamera#fixedToCamera) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 56](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L56)) ### frame : integer Gets or sets the current frame index of the texture being used to render this Game Object. To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use, for example: `player.frame = 4`. If the frame index given doesn't exist it will revert to the first frame found in the texture. If you are using a texture atlas then you should use the `frameName` property instead. If you wish to fully replace the texture being used see `loadTexture`. Inherited From * [Phaser.Component.LoadTexture#frame](phaser.component.loadtexture#frame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 254](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L254)) ### frameName : string Gets or sets the current frame name of the texture being used to render this Game Object. To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use, for example: `player.frameName = "idle"`. If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning. If you are using a sprite sheet then you should use the `frame` property instead. If you wish to fully replace the texture being used see `loadTexture`. Inherited From * [Phaser.Component.LoadTexture#frameName](phaser.component.loadtexture#frameName) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 279](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L279)) ### [readonly] fresh : boolean A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. This property is mostly used internally by the physics systems, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#fresh](phaser.component.core#fresh) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 248](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L248)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Inherited From * [Phaser.Component.Core#game](phaser.component.core#game) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 142](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L142)) ### heal Heal the Game Object. This adds the given amount of health to the `health` property. Inherited From * [Phaser.Component.Health#heal](phaser.component.health#heal) Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 90](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L90)) ### health : number The Game Objects health value. This is a handy property for setting and manipulating health on a Game Object. It can be used in combination with the `damage` method or modified directly. Inherited From * [Phaser.Component.Health#health](phaser.component.health#health) Default Value * 1 Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L26)) ### height : number The height of the sprite, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.Sprite#height](pixi.sprite#height) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 144](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L144)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### [readonly] inCamera : boolean Checks if the Game Objects bounds intersect with the Game Camera bounds. Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. Inherited From * [Phaser.Component.AutoCull#inCamera](phaser.component.autocull#inCamera) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L37)) ### input : [Phaser.InputHandler](phaser.inputhandler) | null The Input Handler for this Game Object. By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`. After you have done this, this property will be a reference to the Phaser InputHandler. ##### Type * [Phaser.InputHandler](phaser.inputhandler) | null Inherited From * [Phaser.Component.InputEnabled#input](phaser.component.inputenabled#input) Source code: [gameobjects/components/InputEnabled.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js#L24)) ### inputEnabled : boolean By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created for this Game Object and it will then start to process click / touch events and more. You can then access the Input Handler via `this.input`. Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`. If you set this property to false it will stop the Input Handler from processing any more input events. If you want to *temporarily* disable input for a Game Object, then it's better to set `input.enabled = false`, as it won't reset any of the Input Handlers internal properties. You can then toggle this back on as needed. Inherited From * [Phaser.Component.InputEnabled#inputEnabled](phaser.component.inputenabled#inputEnabled) Source code: [gameobjects/components/InputEnabled.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js#L42)) ### [readonly] inWorld : boolean Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds. Inherited From * [Phaser.Component.InWorld#inWorld](phaser.component.inworld#inWorld) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 129](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L129)) ### key : string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) The key of the image or texture used by this Game Object during rendering. If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. ##### Type * string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) Inherited From * [Phaser.Component.Core#key](phaser.component.core#key) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 203](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L203)) ### left : number The left coordinate of the Game Object. This is the same as `x - offsetX`. Inherited From * [Phaser.Component.Bounds#left](phaser.component.bounds#left) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 102](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L102)) ### lifespan : number The lifespan allows you to give a Game Object a lifespan in milliseconds. Once the Game Object is 'born' you can set this to a positive value. It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. When it reaches zero it will call the `kill` method. Very handy for particles, bullets, collectibles, or any other short-lived entity. Inherited From * [Phaser.Component.LifeSpan#lifespan](phaser.component.lifespan#lifespan) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 65](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L65)) ### maxHealth : number The Game Objects maximum health value. This works in combination with the `heal` method to ensure the health value never exceeds the maximum. Inherited From * [Phaser.Component.Health#maxHealth](phaser.component.health#maxHealth) Default Value * 100 Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 35](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L35)) ### name : string A user defined name given to this Game Object. This value isn't ever used internally by Phaser, it is meant as a game level property. Inherited From * [Phaser.Component.Core#name](phaser.component.core#name) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 150](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L150)) ### [readonly] offsetX : number The amount the Game Object is visually offset from its x coordinate. This is the same as `width * anchor.x`. It will only be > 0 if anchor.x is not equal to zero. Inherited From * [Phaser.Component.Bounds#offsetX](phaser.component.bounds#offsetX) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L24)) ### [readonly] offsetY : number The amount the Game Object is visually offset from its y coordinate. This is the same as `height * anchor.y`. It will only be > 0 if anchor.y is not equal to zero. Inherited From * [Phaser.Component.Bounds#offsetY](phaser.component.bounds#offsetY) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L42)) ### outOfBoundsKill : boolean If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false. Inherited From * [Phaser.Component.InWorld#outOfBoundsKill](phaser.component.inworld#outOfBoundsKill) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 106](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L106)) ### outOfCameraBoundsKill : boolean If this and the `autoCull` property are both set to `true`, then the `kill` method is called as soon as the Game Object leaves the camera bounds. Inherited From * [Phaser.Component.InWorld#outOfCameraBoundsKill](phaser.component.inworld#outOfCameraBoundsKill) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 115](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L115)) ### pendingDestroy : boolean A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. You can set it directly to allow you to flag an object to be destroyed on its next update. This is extremely useful if you wish to destroy an object from within one of its own callbacks such as with Buttons or other Input events. Inherited From * [Phaser.Component.Core#pendingDestroy](phaser.component.core#pendingDestroy) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 259](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L259)) ### [readonly] physicsType : number The const physics body type of this object. Inherited From * [Phaser.Sprite#physicsType](phaser.sprite#physicsType) Source code: [gameobjects/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Sprite.js) ([Line 61](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Sprite.js#L61)) ### [readonly] previousPosition : [Phaser.Point](phaser.point) The position the Game Object was located in the previous frame. Inherited From * [Phaser.Component.Core#previousPosition](phaser.component.core#previousPosition) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 225](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L225)) ### [readonly] previousRotation : number The rotation the Game Object was in set to in the previous frame. Value is in radians. Inherited From * [Phaser.Component.Core#previousRotation](phaser.component.core#previousRotation) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L232)) ### [readonly] renderOrderID : number The render order ID is used internally by the renderer and Input Manager and should not be modified. This property is mostly used internally by the renderers, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#renderOrderID](phaser.component.core#renderOrderID) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 240](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L240)) ### right : number The right coordinate of the Game Object. This is the same as `x + width - offsetX`. Inherited From * [Phaser.Component.Bounds#right](phaser.component.bounds#right) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L124)) ### <internal> scaleData :array A reference to the scaleData array owned by the Emitter that emitted this Particle. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/Particle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Particle.js) ([Line 33](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Particle.js#L33)) ### scaleMax : [Phaser.Point](phaser.point) The maximum scale this Game Object will scale up to. It allows you to prevent a parent from scaling this Game Object higher than the given value. Set it to `null` to remove the limit. Inherited From * [Phaser.Component.ScaleMinMax#scaleMax](phaser.component.scaleminmax#scaleMax) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L46)) ### scaleMin : [Phaser.Point](phaser.point) The minimum scale this Game Object will scale down to. It allows you to prevent a parent from scaling this Game Object lower than the given value. Set it to `null` to remove the limit. Inherited From * [Phaser.Component.ScaleMinMax#scaleMin](phaser.component.scaleminmax#scaleMin) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 36](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L36)) ### setHealth Sets the health property of the Game Object to the given amount. Will never exceed the `maxHealth` value. Inherited From * [Phaser.Component.Health#setHealth](phaser.component.health#setHealth) Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 70](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L70)) ### shader : [PIXI.AbstractFilter](pixi.abstractfilter) The shader that will be used to render this Sprite. Set to null to remove a current shader. Inherited From * [PIXI.Sprite#shader](pixi.sprite#shader) Default Value * null Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L93)) ### smoothed : boolean Enable or disable texture smoothing for this Game Object. It only takes effect if the Game Object is using an image based texture. Smoothing is enabled by default. Inherited From * [Phaser.Component.Smoothed#smoothed](phaser.component.smoothed#smoothed) Source code: [gameobjects/components/Smoothed.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Smoothed.js) ([Line 25](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Smoothed.js#L25)) ### texture : [PIXI.Texture](pixi.texture) The texture that the sprite is using Inherited From * [PIXI.Sprite#texture](pixi.sprite#texture) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L28)) ### tint : number The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. Inherited From * [PIXI.Sprite#tint](pixi.sprite#tint) Default Value * 0xFFFFFF Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L54)) ### tintedTexture :Canvas A canvas that contains the tinted version of the Sprite (in Canvas mode, WebGL doesn't populate this) Inherited From * [PIXI.Sprite#tintedTexture](pixi.sprite#tintedTexture) Default Value * null Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 73](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L73)) ### top : number The y coordinate of the Game Object. This is the same as `y - offsetY`. Inherited From * [Phaser.Component.Bounds#top](phaser.component.bounds#top) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 146](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L146)) ### transformCallback : Function The callback that will apply any scale limiting to the worldTransform. Inherited From * [Phaser.Component.ScaleMinMax#transformCallback](phaser.component.scaleminmax#transformCallback) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L20)) ### transformCallbackContext : Object The context under which `transformCallback` is called. Inherited From * [Phaser.Component.ScaleMinMax#transformCallbackContext](phaser.component.scaleminmax#transformCallbackContext) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L26)) ### [readonly] type : number The const type of this object. Inherited From * [Phaser.Sprite#type](phaser.sprite#type) Source code: [gameobjects/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Sprite.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Sprite.js#L55)) ### width : number The width of the sprite, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.Sprite#width](pixi.sprite#width) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 125](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L125)) ### world : [Phaser.Point](phaser.point) The world coordinates of this Game Object in pixels. Depending on where in the display list this Game Object is placed this value can differ from `position`, which contains the x/y coordinates relative to the Game Objects parent. Inherited From * [Phaser.Component.Core#world](phaser.component.core#world) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 211](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L211)) ### x : number The position of the Game Object on the x axis relative to the local coordinates of the parent. Inherited From * [Phaser.Component.PhysicsBody#x](phaser.component.physicsbody#x) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L98)) ### y : number The position of the Game Object on the y axis relative to the local coordinates of the parent. Inherited From * [Phaser.Component.PhysicsBody#y](phaser.component.physicsbody#y) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L124)) ### [readonly] z : number The z depth of this Game Object within its parent Group. No two objects in a Group can have the same z value. This value is adjusted automatically whenever the Group hierarchy changes. If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. Inherited From * [Phaser.Component.Core#z](phaser.component.core#z) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 177](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L177)) Public Methods -------------- ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### alignIn(container, position, offsetX, offsetY) → {Object} Aligns this Game Object within another Game Object, or Rectangle, known as the 'container', to one of 9 possible positions. The container must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the container. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the container, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `container` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Inherited From * [Phaser.Component.Bounds#alignIn](phaser.component.bounds#alignIn) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 223](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L223)) ### alignTo(parent, position, offsetX, offsetY) → {Object} Aligns this Game Object to the side of another Game Object, or Rectangle, known as the 'parent', in one of 11 possible positions. The parent must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the parent. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the parent, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Inherited From * [Phaser.Component.Bounds#alignTo](phaser.component.bounds#alignTo) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 321](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L321)) ### bringToTop() → {PIXI.DisplayObject} Brings this Game Object to the top of its parents display list. Visually this means it will render over the top of any old child in the same Group. If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#bringToTop](phaser.component.bringtotop#bringToTop) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L24)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### crop(rect, copy) Crop allows you to crop the texture being used to display this Game Object. Setting a crop rectangle modifies the core texture frame. The Game Object width and height properties will be adjusted accordingly. Cropping takes place from the top-left and can be modified in real-time either by providing an updated rectangle object to this method, or by modifying `cropRect` property directly and then calling `updateCrop`. The rectangle object given to this method can be either a `Phaser.Rectangle` or any other object so long as it has public `x`, `y`, `width`, `height`, `right` and `bottom` properties. A reference to the rectangle is stored in `cropRect` unless the `copy` parameter is `true`, in which case the values are duplicated to a local object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `rect` | [Phaser.Rectangle](phaser.rectangle) | | | The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle. | | `copy` | boolean | <optional> | false | If false `cropRect` will be stored as a reference to the given rect. If true it will copy the rect values into a local Phaser Rectangle object stored in cropRect. | Inherited From * [Phaser.Component.Crop#crop](phaser.component.crop#crop) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L49)) ### destroy(destroyChildren, destroyTexture) Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present and nulls its reference to `game`, freeing it up for garbage collection. If this Game Object has the Events component it will also dispatch the `onDestroy` event. You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've more than one Game Object sharing the same BaseTexture. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroyChildren` | boolean | <optional> | true | Should every child of this object have its destroy method called as well? | | `destroyTexture` | boolean | <optional> | false | Destroy the BaseTexture this Game Object is using? Note that if another Game Object is sharing the same BaseTexture it will invalidate it. | Inherited From * [Phaser.Component.Destroy#destroy](phaser.component.destroy#destroy) Source code: [gameobjects/components/Destroy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js#L37)) ### getBounds(matrix) → {Rectangle} Returns the bounds of the Sprite as a rectangle. The bounds calculation takes the worldTransform into account. It is important to note that the transform is not updated when you call this method. So if this Sprite is the child of a Display Object which has had its transform updated since the last render pass, those changes will not yet have been applied to this Sprites worldTransform. If you need to ensure that all parent transforms are factored into this getBounds operation then you should call `updateTransform` on the root most object in this Sprites display list first. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `matrix` | Matrix | the transformation matrix of the sprite | ##### Returns Rectangle - the framing rectangle Inherited From * [PIXI.Sprite#getBounds](pixi.sprite#getBounds) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 199](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L199)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the Sprite as a rectangle. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.Sprite#getLocalBounds](pixi.sprite#getLocalBounds) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 315](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L315)) ### kill() → {PIXI.DisplayObject} Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false. It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal. Note that killing a Game Object is a way for you to quickly recycle it in an object pool, it doesn't destroy the object or free it up from memory. If you don't need this Game Object any more you should call `destroy` instead. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.LifeSpan#kill](phaser.component.lifespan#kill) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 113](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L113)) ### loadTexture(key, frame, stopAnimation) Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache. If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead. You should only use `loadTexture` if you want to replace the base texture entirely. Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU. You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite. Doing this then sets the key to be the `frame` argument (the frame is set to zero). This allows you to create sprites using `load.image` during development, and then change them to use a Texture Atlas later in development by simply searching your code for 'PENDING\_ATLAS' and swapping it to be the key of the atlas data. Note: You cannot use a RenderTexture as a texture for a TileSprite. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | | `stopAnimation` | boolean | <optional> | true | If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing. | Inherited From * [Phaser.Component.LoadTexture#loadTexture](phaser.component.loadtexture#loadTexture) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L51)) ### moveDown() → {PIXI.DisplayObject} Moves this Game Object down one place in its parents display list. This call has no effect if the Game Object is already at the bottom of the display list. If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#moveDown](phaser.component.bringtotop#moveDown) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L87)) ### moveUp() → {PIXI.DisplayObject} Moves this Game Object up one place in its parents display list. This call has no effect if the Game Object is already at the top of the display list. If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#moveUp](phaser.component.bringtotop#moveUp) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 66](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L66)) ### onEmit() Called by the Emitter when this particle is emitted. Left empty for you to over-ride as required. Source code: [gameobjects/Particle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Particle.js) ([Line 102](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Particle.js#L102)) ### overlap(displayObject) → {boolean} Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object, which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result. This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result. Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency. It should be fine for low-volume testing where physics isn't required. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `displayObject` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.TileSprite](phaser.tilesprite) | [Phaser.Button](phaser.button) | PIXI.DisplayObject | The display object to check against. | ##### Returns boolean - True if the bounds of this Game Object intersects at any point with the bounds of the given display object. Inherited From * [Phaser.Component.Overlap#overlap](phaser.component.overlap#overlap) Source code: [gameobjects/components/Overlap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Overlap.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Overlap.js#L29)) ### play(name, frameRate, loop, killOnComplete) → {[Phaser.Animation](phaser.animation)} Plays an Animation. The animation should have previously been created via `animations.add`. If the animation is already playing calling this again won't do anything. If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `name` | string | | | The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'. | | `frameRate` | number | <optional> | null | The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. | | `loop` | boolean | <optional> | false | Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. | | `killOnComplete` | boolean | <optional> | false | If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. | ##### Returns [Phaser.Animation](phaser.animation) - A reference to playing Animation. Inherited From * [Phaser.Component.Animation#play](phaser.component.animation#play) Source code: [gameobjects/components/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Animation.js) ([Line 31](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Animation.js#L31)) ### <internal> postUpdate() Internal method called by the World postUpdate cycle. Inherited From * [Phaser.Component.Core#postUpdate](phaser.component.core#postUpdate) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 338](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L338)) ### preUpdate() → {boolean} Automatically called by World.preUpdate. ##### Returns boolean - True if the Sprite was rendered, otherwise false. Inherited From * [Phaser.Sprite#preUpdate](phaser.sprite#preUpdate) Source code: [gameobjects/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Sprite.js) ([Line 107](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Sprite.js#L107)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### reset(x, y, health) → {[Phaser.Particle](phaser.particle)} Resets the Particle. This places the Particle at the given x/y world coordinates and then sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state and health values. If the Particle has a physics body that too is reset. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate (in world space) to position the Particle at. | | `y` | number | | | The y coordinate (in world space) to position the Particle at. | | `health` | number | <optional> | 1 | The health to give the Particle. | ##### Returns [Phaser.Particle](phaser.particle) - This instance. Source code: [gameobjects/Particle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Particle.js) ([Line 141](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Particle.js#L141)) ### resetFrame() Resets the texture frame dimensions that the Game Object uses for rendering. Inherited From * [Phaser.Component.LoadTexture#resetFrame](phaser.component.loadtexture#resetFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L232)) ### resizeFrame(parent, width, height) Resizes the Frame dimensions that the Game Object uses for rendering. You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData it can be useful to adjust the dimensions directly in this way. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `parent` | object | The parent texture object that caused the resize, i.e. a Phaser.Video object. | | `width` | integer | The new width of the texture. | | `height` | integer | The new height of the texture. | Inherited From * [Phaser.Component.LoadTexture#resizeFrame](phaser.component.loadtexture#resizeFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 220](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L220)) ### revive(health) → {PIXI.DisplayObject} Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `health` | number | <optional> | 100 | The health to give the Game Object. Only set if the GameObject has the Health component. | ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.LifeSpan#revive](phaser.component.lifespan#revive) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L78)) ### sendToBack() → {PIXI.DisplayObject} Sends this Game Object to the bottom of its parents display list. Visually this means it will render below all other children in the same Group. If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#sendToBack](phaser.component.bringtotop#sendToBack) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L45)) ### setAlphaData() Called by the Emitter if autoAlpha has been enabled. Passes over the alpha ease data and resets the alpha counter. Source code: [gameobjects/Particle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Particle.js) ([Line 111](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Particle.js#L111)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### setFrame(frame) Sets the texture frame the Game Object uses for rendering. This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `frame` | [Phaser.Frame](phaser.frame) | The Frame to be used by the texture. | Inherited From * [Phaser.Component.LoadTexture#setFrame](phaser.component.loadtexture#setFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 155](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L155)) ### setScaleData() Called by the Emitter if autoScale has been enabled. Passes over the scale ease data and resets the scale counter. Source code: [gameobjects/Particle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Particle.js) ([Line 126](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Particle.js#L126)) ### setScaleMinMax(minX, minY, maxX, maxY) Sets the scaleMin and scaleMax values. These values are used to limit how far this Game Object will scale based on its parent. For example if this Game Object has a `minScale` value of 1 and its parent has a `scale` value of 0.5, the 0.5 will be ignored and the scale value of 1 will be used, as the parents scale is lower than the minimum scale this Game Object should adhere to. By setting these values you can carefully control how Game Objects deal with responsive scaling. If only one parameter is given then that value will be used for both scaleMin and scaleMax: `setScaleMinMax(1)` = scaleMin.x, scaleMin.y, scaleMax.x and scaleMax.y all = 1 If only two parameters are given the first is set as scaleMin.x and y and the second as scaleMax.x and y: `setScaleMinMax(0.5, 2)` = scaleMin.x and y = 0.5 and scaleMax.x and y = 2 If you wish to set `scaleMin` with different values for x and y then either modify Game Object.scaleMin directly, or pass `null` for the `maxX` and `maxY` parameters. Call `setScaleMinMax(null)` to clear all previously set values. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `minX` | number | null | The minimum horizontal scale value this Game Object can scale down to. | | `minY` | number | null | The minimum vertical scale value this Game Object can scale down to. | | `maxX` | number | null | The maximum horizontal scale value this Game Object can scale up to. | | `maxY` | number | null | The maximum vertical scale value this Game Object can scale up to. | Inherited From * [Phaser.Component.ScaleMinMax#setScaleMinMax](phaser.component.scaleminmax#setScaleMinMax) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 110](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L110)) ### setTexture(texture, destroy) Sets the texture of the sprite. Be warned that this doesn't remove or destroy the previous texture this Sprite was using. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `texture` | [PIXI.Texture](pixi.texture) | | | The PIXI texture that is displayed by the sprite | | `destroy` | Boolean | <optional> | false | Call Texture.destroy on the current texture before replacing it with the new one? | Inherited From * [PIXI.Sprite#setTexture](pixi.sprite#setTexture) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 163](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L163)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) ### update() Updates the Particle scale or alpha if autoScale and autoAlpha are set. Source code: [gameobjects/Particle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Particle.js) ([Line 64](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Particle.js#L64)) ### updateCrop() If you have set a crop rectangle on this Game Object via `crop` and since modified the `cropRect` property, or the rectangle it references, then you need to update the crop frame by calling this method. Inherited From * [Phaser.Component.Crop#updateCrop](phaser.component.crop#updateCrop) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L86))
programming_docs
phaser Class: PIXI.Rope Class: PIXI.Rope ================ Constructor ----------- ### new Rope(texture, points) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `texture` | [PIXI.Texture](pixi.texture) | * The texture to use on the rope. | | `points` | Array | * An array of {PIXI.Point}. | Source code: [pixi/extras/Rope.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Rope.js) ([Line 6](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Rope.js#L6)) Extends ------- * [PIXI.Strip](pixi.strip) Public Properties ----------------- ### blendMode : number The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode. Inherited From * [PIXI.Strip#blendMode](pixi.strip#blendMode) Default Value * PIXI.blendModes.NORMAL; Source code: [pixi/extras/Strip.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js#L51)) ### canvasPadding : number Triangles in canvas mode are automatically antialiased, use this value to force triangles to overlap a bit with each other. Inherited From * [PIXI.Strip#canvasPadding](pixi.strip#canvasPadding) Source code: [pixi/extras/Strip.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js) ([Line 60](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js#L60)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### dirty : boolean Whether the strip is dirty or not Inherited From * [PIXI.Strip#dirty](pixi.strip#dirty) Source code: [pixi/extras/Strip.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js) ([Line 43](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js#L43)) ### height : number The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#height](pixi.displayobjectcontainer#height) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 600](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L600)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### texture : [PIXI.Texture](pixi.texture) The texture of the strip Inherited From * [PIXI.Strip#texture](pixi.strip#texture) Source code: [pixi/extras/Strip.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js#L20)) ### width : number The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#width](pixi.displayobjectcontainer#width) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 571](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L571)) Public Methods -------------- ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### getBounds(matrix) → {Rectangle} Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `matrix` | Matrix | the transformation matrix of the sprite | ##### Returns Rectangle - the framing rectangle Inherited From * [PIXI.Strip#getBounds](pixi.strip#getBounds) Source code: [pixi/extras/Strip.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js) ([Line 405](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js#L405)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the displayObjectContainer as a rectangle without any transformations. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.DisplayObjectContainer#getLocalBounds](pixi.displayobjectcontainer#getLocalBounds) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 437](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L437)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) phaser Class: Phaser.Easing Class: Phaser.Easing ==================== Constructor ----------- ### new Easing() A collection of easing methods defining ease-in and ease-out curves. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 14](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L14)) Classes ------- [Back](phaser.easing.back) [Bounce](phaser.easing.bounce) [Circular](phaser.easing.circular) [Cubic](phaser.easing.cubic) [Elastic](phaser.easing.elastic) [Exponential](phaser.easing.exponential) [Linear](phaser.easing.linear) [Quadratic](phaser.easing.quadratic) [Quartic](phaser.easing.quartic) [Quintic](phaser.easing.quintic) [Sinusoidal](phaser.easing.sinusoidal) phaser Class: Phaser.LinkedList Class: Phaser.LinkedList ======================== Constructor ----------- ### new LinkedList() A basic Linked List data structure. This implementation *modifies* the `prev` and `next` properties of each item added: * The `prev` and `next` properties must be writable and should not be used for any other purpose. * Items *cannot* be added to multiple LinkedLists at the same time. * Only objects can be added. Source code: [utils/LinkedList.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/LinkedList.js) ([Line 18](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/LinkedList.js#L18)) Public Properties ----------------- ### first : Object First element in the list. Source code: [utils/LinkedList.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/LinkedList.js) ([Line 39](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/LinkedList.js#L39)) ### last : Object Last element in the list. Source code: [utils/LinkedList.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/LinkedList.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/LinkedList.js#L46)) ### next : Object Next element in the list. Source code: [utils/LinkedList.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/LinkedList.js) ([Line 25](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/LinkedList.js#L25)) ### prev : Object Previous element in the list. Source code: [utils/LinkedList.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/LinkedList.js) ([Line 32](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/LinkedList.js#L32)) ### total : integer Number of elements in the list. Source code: [utils/LinkedList.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/LinkedList.js) ([Line 53](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/LinkedList.js#L53)) Public Methods -------------- ### add(item) → {object} Adds a new element to this linked list. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `item` | object | The element to add to this list. Can be a Phaser.Sprite or any other object you need to quickly iterate through. | ##### Returns object - The item that was added. Source code: [utils/LinkedList.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/LinkedList.js) ([Line 59](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/LinkedList.js#L59)) ### callAll(callback) Calls a function on all members of this list, using the member as the context for the callback. The function must exist on the member. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `callback` | function | The function to call. | Source code: [utils/LinkedList.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/LinkedList.js) ([Line 156](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/LinkedList.js#L156)) ### remove(item) Removes the given element from this linked list if it exists. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `item` | object | The item to be removed from the list. | Source code: [utils/LinkedList.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/LinkedList.js) ([Line 107](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/LinkedList.js#L107)) ### reset() Resets the first, last, next and previous node pointers in this list. Source code: [utils/LinkedList.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/LinkedList.js) ([Line 92](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/LinkedList.js#L92)) phaser Class: Phaser.Tween Class: Phaser.Tween =================== Constructor ----------- ### new Tween(target, game, manager) A Tween allows you to alter one or more properties of a target object over a defined period of time. This can be used for things such as alpha fading Sprites, scaling them or motion. Use `Tween.to` or `Tween.from` to set-up the tween values. You can create multiple tweens on the same object by calling Tween.to multiple times on the same Tween. Additional tweens specified in this way become "child" tweens and are played through in sequence. You can use Tween.timeScale and Tween.reverse to control the playback of this Tween and all of its children. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `target` | object | The target object, such as a Phaser.Sprite or Phaser.Sprite.scale. | | `game` | [Phaser.Game](phaser.game) | Current game instance. | | `manager` | [Phaser.TweenManager](phaser.tweenmanager) | The TweenManager responsible for looking after this Tween. | Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L20)) Public Properties ----------------- ### chainedTween : [Phaser.Tween](phaser.tween) If this Tween is chained to another this holds a reference to it. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 130](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L130)) ### [readonly] current : number The current Tween child being run. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 120](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L120)) ### frameBased : boolean Is this Tween frame or time based? A frame based tween will use the physics elapsed timer when updating. This means it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should be given in frames. If the Tween uses a time based update (which is the default) then the duration is given in milliseconds. In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween has actually been through. For very short tweens you may wish to experiment with a frame based update instead. The default value is whatever you've set in TweenManager.frameBased. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 152](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L152)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 25](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L25)) ### isPaused : boolean Is this Tween paused or not? Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 136](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L136)) ### isRunning : boolean If the tween is running this is set to true, otherwise false. Tweens that are in a delayed state or waiting to start are considered as being running. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 113](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L113)) ### manager : [Phaser.TweenManager](phaser.tweenmanager) Reference to the TweenManager responsible for updating this Tween. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 35](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L35)) ### onChildComplete : [Phaser.Signal](phaser.signal) The onChildComplete event is fired when the Tween or any of its children completes. Fires every time a child completes unless a child is set to repeat forever. It will be sent 2 parameters: the target object and this tween. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 100](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L100)) ### onComplete : [Phaser.Signal](phaser.signal) The onComplete event is fired when the Tween and all of its children completes. Does not fire if the Tween is set to loop or repeatAll(-1). It will be sent 2 parameters: the target object and this tween. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 107](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L107)) ### onLoop : [Phaser.Signal](phaser.signal) The onLoop event is fired if the Tween, or any child tweens loop. It will be sent 2 parameters: the target object and this tween. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L85)) ### onRepeat : [Phaser.Signal](phaser.signal) The onRepeat event is fired if the Tween and all of its children repeats. If this tween has no children this will never be fired. It will be sent 2 parameters: the target object and this tween. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 92](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L92)) ### onStart : [Phaser.Signal](phaser.signal) The onStart event is fired when the Tween begins. If there is a delay before the tween starts then onStart fires after the delay is finished. It will be sent 2 parameters: the target object and this tween. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 77](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L77)) ### [readonly] pendingDelete : boolean True if this Tween is ready to be deleted by the TweenManager. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 70](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L70)) ### properties : Object Target property cache used when building the child data values. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 125](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L125)) ### repeatCounter : number If the Tween and any child tweens are set to repeat this contains the current repeat count. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 63](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L63)) ### reverse : boolean If set to `true` the current tween will play in reverse. If the tween hasn't yet started this has no effect. If there are child tweens then all child tweens will play in reverse from the current point. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L49)) ### target : Object The target object, such as a Phaser.Sprite or property like Phaser.Sprite.scale. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L30)) ### timeline : Array An Array of TweenData objects that comprise the different parts of this Tween. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 40](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L40)) ### timeScale : number The speed at which the tweens will run. A value of 1 means it will match the game frame rate. 0.5 will run at half the frame rate. 2 at double the frame rate, etc. If a tweens duration is 1 second but timeScale is 0.5 then it will take 2 seconds to complete. Default Value * 1 Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L58)) ### totalDuration : [Phaser.TweenData](phaser.tweendata) Gets the total duration of this Tween, including all child tweens, in milliseconds. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 893](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L893)) Public Methods -------------- ### chain(tweens) → {[Phaser.Tween](phaser.tween)} This method allows you to chain tweens together. Any tween chained to this tween will have its `Tween.start` method called as soon as this tween completes. If this tween never completes (i.e. repeatAll or loop is set) then the chain will never progress. Note that `Tween.onComplete` will fire when *this* tween completes, not when the whole chain completes. For that you should listen to `onComplete` on the final tween in your chain. If you pass multiple tweens to this method they will be joined into a single long chain. For example if this is Tween A and you pass in B, C and D then B will be chained to A, C will be chained to B and D will be chained to C. Any previously chained tweens that may have been set will be overwritten. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `tweens` | [Phaser.Tween](phaser.tween) | <repeatable> | One or more tweens that will be chained to this one. | ##### Returns [Phaser.Tween](phaser.tween) - This tween. Useful for method chaining. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 566](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L566)) ### delay(duration, index) → {[Phaser.Tween](phaser.tween)} Sets the delay in milliseconds before this tween will start. If there are child tweens it sets the delay before the first child starts. The delay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to delay. If you have child tweens and pass -1 as the index value it sets the delay across all of them. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `duration` | number | | | The amount of time in ms that the Tween should wait until it begins once started is called. Set to zero to remove any active delay. | | `index` | number | <optional> | 0 | If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children. | ##### Returns [Phaser.Tween](phaser.tween) - This tween. Useful for method chaining. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 408](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L408)) ### easing(ease, index) → {[Phaser.Tween](phaser.tween)} Set easing function this tween will use, i.e. Phaser.Easing.Linear.None. The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. If you have child tweens and pass -1 as the index value it sets the easing function defined here across all of them. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `ease` | function | string | | | The easing function this tween will use, i.e. Phaser.Easing.Linear.None. | | `index` | number | <optional> | 0 | If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the easing function on all children. | ##### Returns [Phaser.Tween](phaser.tween) - This tween. Useful for method chaining. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 504](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L504)) ### from(properties, duration, ease, autoStart, delay, repeat, yoyo) → {[Phaser.Tween](phaser.tween)} Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value. For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`. The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `properties` | object | | | An object containing the properties you want to tween., such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. | | `duration` | number | <optional> | 1000 | Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse. | | `ease` | function | string | <optional> | null | Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden. | | `autoStart` | boolean | <optional> | false | Set to `true` to allow this tween to start automatically. Otherwise call Tween.start(). | | `delay` | number | <optional> | 0 | Delay before this tween will start in milliseconds. Defaults to 0, no delay. | | `repeat` | number | <optional> | 0 | Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens. | | `yoyo` | boolean | <optional> | false | A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. | ##### Returns [Phaser.Tween](phaser.tween) - This Tween object. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 237](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L237)) ### generateData(frameRate, data) → {array} This will generate an array populated with the tweened object values from start to end. It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from. It ignores delay and repeat counts and any chained tweens, but does include child tweens. Just one play through of the tween data is returned, including yoyo if set. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `frameRate` | number | <optional> | 60 | The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates. | | `data` | array | <optional> | | If given the generated data will be appended to this array, otherwise a new array will be returned. | ##### Returns array - An array of tweened values. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 840](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L840)) ### interpolation(interpolation, context, index) → {[Phaser.Tween](phaser.tween)} Sets the interpolation function the tween will use. By default it uses Phaser.Math.linearInterpolation. Also available: Phaser.Math.bezierInterpolation and Phaser.Math.catmullRomInterpolation. The interpolation function is only used if the target properties is an array. If you have child tweens and pass -1 as the index value and it will set the interpolation function across all of them. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `interpolation` | function | | | The interpolation function to use (Phaser.Math.linearInterpolation by default) | | `context` | object | <optional> | | The context under which the interpolation function will be run. | | `index` | number | <optional> | 0 | If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the interpolation function on all children. | ##### Returns [Phaser.Tween](phaser.tween) - This tween. Useful for method chaining. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 526](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L526)) ### loop(value) → {[Phaser.Tween](phaser.tween)} Enables the looping of this tween. The tween will loop forever, and onComplete will never fire. If `value` is `true` then this is the same as setting `Tween.repeatAll(-1)`. If `value` is `false` it is the same as setting `Tween.repeatAll(0)` and will reset the `repeatCounter` to zero. Usage: game.add.tween(p).to({ x: 700 }, 1000, Phaser.Easing.Linear.None, true) .to({ y: 300 }, 1000, Phaser.Easing.Linear.None) .to({ x: 0 }, 1000, Phaser.Easing.Linear.None) .to({ y: 0 }, 1000, Phaser.Easing.Linear.None) .loop(); ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `value` | boolean | <optional> | true | If `true` this tween will loop once it reaches the end. Set to `false` to remove an active loop. | ##### Returns [Phaser.Tween](phaser.tween) - This tween. Useful for method chaining. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 600](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L600)) ### onUpdateCallback(callback, callbackContext) → {[Phaser.Tween](phaser.tween)} Sets a callback to be fired each time this tween updates. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `callback` | function | The callback to invoke each time this tween is updated. Set to `null` to remove an already active callback. | | `callbackContext` | object | The context in which to call the onUpdate callback. | ##### Returns [Phaser.Tween](phaser.tween) - This tween. Useful for method chaining. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 626](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L626)) ### pause() Pauses the tween. Resume playback with Tween.resume. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 643](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L643)) ### repeat(total, repeat, index) → {[Phaser.Tween](phaser.tween)} Sets the number of times this tween will repeat. If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to repeat. If you have child tweens and pass -1 as the index value it sets the number of times they'll repeat across all of them. If you wish to define how many times this Tween and all children will repeat see Tween.repeatAll. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `total` | number | | | How many times a tween should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever. | | `repeat` | number | <optional> | 0 | This is the amount of time to pause (in ms) before the repeat will start. | | `index` | number | <optional> | 0 | If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeat value on all the children. | ##### Returns [Phaser.Tween](phaser.tween) - This tween. Useful for method chaining. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 425](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L425)) ### repeatAll(total) → {[Phaser.Tween](phaser.tween)} Set how many times this tween and all of its children will repeat. A tween (A) with 3 children (B,C,D) with a `repeatAll` value of 2 would play as: ABCDABCD before completing. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `total` | number | <optional> | 0 | How many times this tween and all children should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever. | ##### Returns [Phaser.Tween](phaser.tween) - This tween. Useful for method chaining. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 548](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L548)) ### repeatDelay(duration, index) → {[Phaser.Tween](phaser.tween)} Sets the delay in milliseconds before this tween will repeat itself. The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on. If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `duration` | number | | | The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active repeatDelay. | | `index` | number | <optional> | 0 | If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeatDelay on all the children. | ##### Returns [Phaser.Tween](phaser.tween) - This tween. Useful for method chaining. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 447](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L447)) ### resume() Resumes a paused tween. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 675](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L675)) ### start(index) → {[Phaser.Tween](phaser.tween)} Starts the tween running. Can also be called by the autoStart parameter of `Tween.to` or `Tween.from`. This sets the `Tween.isRunning` property to `true` and dispatches a `Tween.onStart` signal. If the Tween has a delay set then nothing will start tweening until the delay has expired. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `index` | number | <optional> | 0 | If this Tween contains child tweens you can specify which one to start from. The default is zero, i.e. the first tween created. | ##### Returns [Phaser.Tween](phaser.tween) - This tween. Useful for method chaining. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 284](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L284)) ### stop(complete) → {[Phaser.Tween](phaser.tween)} Stops the tween if running and flags it for deletion from the TweenManager. If called directly the `Tween.onComplete` signal is not dispatched and no chained tweens are started unless the complete parameter is set to `true`. If you just wish to pause a tween then use Tween.pause instead. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `complete` | boolean | <optional> | false | Set to `true` to dispatch the Tween.onComplete signal. | ##### Returns [Phaser.Tween](phaser.tween) - This tween. Useful for method chaining. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 340](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L340)) ### to(properties, duration, ease, autoStart, delay, repeat, yoyo) → {[Phaser.Tween](phaser.tween)} Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given. For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`. The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `properties` | object | | | An object containing the properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. | | `duration` | number | <optional> | 1000 | Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse. | | `ease` | function | string | <optional> | null | Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden. | | `autoStart` | boolean | <optional> | false | Set to `true` to allow this tween to start automatically. Otherwise call Tween.start(). | | `delay` | number | <optional> | 0 | Delay before this tween will start in milliseconds. Defaults to 0, no delay. | | `repeat` | number | <optional> | 0 | Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens. | | `yoyo` | boolean | <optional> | false | A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. | ##### Returns [Phaser.Tween](phaser.tween) - This Tween object. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 190](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L190)) ### update(time) → {boolean} Core tween update function called by the TweenManager. Does not need to be invoked directly. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `time` | number | A timestamp passed in by the TweenManager. | ##### Returns boolean - false if the tween and all child tweens have completed and should be deleted from the manager, otherwise true (still active). Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 717](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L717)) ### updateTweenData(property, value, index) → {[Phaser.Tween](phaser.tween)} Updates either a single TweenData or all TweenData objects properties to the given value. Used internally by methods like Tween.delay, Tween.yoyo, etc. but can also be called directly if you know which property you want to tweak. The property is not checked, so if you pass an invalid one you'll generate a run-time error. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `property` | string | | | The property to update. | | `value` | number | function | | | The value to set the property to. | | `index` | number | <optional> | 0 | If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children. | ##### Returns [Phaser.Tween](phaser.tween) - This tween. Useful for method chaining. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 375](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L375)) ### yoyo(enable, yoyoDelay, index) → {[Phaser.Tween](phaser.tween)} A Tween that has yoyo set to true will run through from its starting values to its end values and then play back in reverse from end to start. Used in combination with repeat you can create endless loops. If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to yoyo. If you have child tweens and pass -1 as the index value it sets the yoyo property across all of them. If you wish to yoyo this Tween and all of its children then see Tween.yoyoAll. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `enable` | boolean | | | Set to true to yoyo this tween, or false to disable an already active yoyo. | | `yoyoDelay` | number | <optional> | 0 | This is the amount of time to pause (in ms) before the yoyo will start. | | `index` | number | <optional> | 0 | If this tween has more than one child this allows you to target a specific child. If set to -1 it will set yoyo on all the children. | ##### Returns [Phaser.Tween](phaser.tween) - This tween. Useful for method chaining. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 464](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L464)) ### yoyoDelay(duration, index) → {[Phaser.Tween](phaser.tween)} Sets the delay in milliseconds before this tween will run a yoyo (only applies if yoyo is enabled). The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on. If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `duration` | number | | | The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active yoyoDelay. | | `index` | number | <optional> | 0 | If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the yoyoDelay on all the children. | ##### Returns [Phaser.Tween](phaser.tween) - This tween. Useful for method chaining. Source code: [tween/Tween.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js) ([Line 487](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Tween.js#L487))
programming_docs
phaser Class: Phaser.Component.Crop Class: Phaser.Component.Crop ============================ Constructor ----------- ### new Crop() The Crop component provides the ability to crop a texture based Game Object to a defined rectangle, which can be updated in real-time. Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 13](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L13)) Public Properties ----------------- ### cropRect : [Phaser.Rectangle](phaser.rectangle) The Rectangle used to crop the texture this Game Object uses. Set this property via `crop`. If you modify this property directly you must call `updateCrop` in order to have the change take effect. Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L24)) Public Methods -------------- ### crop(rect, copy) Crop allows you to crop the texture being used to display this Game Object. Setting a crop rectangle modifies the core texture frame. The Game Object width and height properties will be adjusted accordingly. Cropping takes place from the top-left and can be modified in real-time either by providing an updated rectangle object to this method, or by modifying `cropRect` property directly and then calling `updateCrop`. The rectangle object given to this method can be either a `Phaser.Rectangle` or any other object so long as it has public `x`, `y`, `width`, `height`, `right` and `bottom` properties. A reference to the rectangle is stored in `cropRect` unless the `copy` parameter is `true`, in which case the values are duplicated to a local object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `rect` | [Phaser.Rectangle](phaser.rectangle) | | | The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle. | | `copy` | boolean | <optional> | false | If false `cropRect` will be stored as a reference to the given rect. If true it will copy the rect values into a local Phaser Rectangle object stored in cropRect. | Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L49)) ### updateCrop() If you have set a crop rectangle on this Game Object via `crop` and since modified the `cropRect` property, or the rectangle it references, then you need to update the crop frame by calling this method. Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L86)) phaser Class: Phaser.DeviceButton Class: Phaser.DeviceButton ========================== Constructor ----------- ### new DeviceButton(parent, buttonCode) DeviceButtons belong to both `Phaser.Pointer` and `Phaser.SinglePad` (Gamepad) instances. For Pointers they represent the various buttons that can exist on mice and pens, such as the left button, right button, middle button and advanced buttons like back and forward. Access them via `Pointer.leftbutton`, `Pointer.rightButton` and so on. On Gamepads they represent all buttons on the pad: from shoulder buttons to action buttons. At the time of writing this there are device limitations you should be aware of: * On Windows, if you install a mouse driver, and its utility software allows you to customize button actions (e.g., IntelliPoint and SetPoint), the middle (wheel) button, the 4th button, and the 5th button might not be set, even when they are pressed. * On Linux (GTK), the 4th button and the 5th button are not supported. * On Mac OS X 10.5 there is no platform API for implementing any advanced buttons. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `parent` | [Phaser.Pointer](phaser.pointer) | [Phaser.SinglePad](phaser.singlepad) | A reference to the parent of this button. Either a Pointer or a Gamepad. | | `buttonCode` | number | The button code this DeviceButton is responsible for. | Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 31](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L31)) Public Properties ----------------- ### altKey : boolean True if the alt key was held down when this button was last pressed or released. Not supported on Gamepads. Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L87)) ### buttonCode : number The buttoncode of this button if a Gamepad, or the DOM button event value if a Pointer. Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 114](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L114)) ### ctrlKey : boolean True if the control key was held down when this button was last pressed or released. Not supported on Gamepads. Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 103](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L103)) ### [readonly] duration : number How long the button has been held down for in milliseconds. If not currently down it returns -1. Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 300](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L300)) ### event : Object The DOM event that caused the change in button state. Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 47](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L47)) ### game : [Phaser.Game](phaser.game) A reference to the currently running game. Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 41](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L41)) ### isDown : boolean The "down" state of the button. Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 53](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L53)) ### isUp : boolean The "up" state of the button. Default Value * true Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 59](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L59)) ### onDown : [Phaser.Signal](phaser.signal) This Signal is dispatched every time this DeviceButton is pressed down. It is only dispatched once (until the button is released again). When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 122](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L122)) ### onFloat : [Phaser.Signal](phaser.signal) Gamepad only. This Signal is dispatched every time this DeviceButton changes floating value (between, but not exactly, 0 and 1). When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 138](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L138)) ### onUp : [Phaser.Signal](phaser.signal) This Signal is dispatched every time this DeviceButton is released from a down state. It is only dispatched once (until the button is pressed again). When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 130](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L130)) ### parent : [Phaser.Pointer](phaser.pointer) | [Phaser.SinglePad](phaser.singlepad) A reference to the Pointer or Gamepad that owns this button. ##### Type * [Phaser.Pointer](phaser.pointer) | [Phaser.SinglePad](phaser.singlepad) Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 36](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L36)) ### repeats : number Gamepad only. If a button is held down this holds down the number of times the button has 'repeated'. Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 79](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L79)) ### shiftKey : boolean True if the shift key was held down when this button was last pressed or released. Not supported on Gamepads. Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 95](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L95)) ### timeDown : number The timestamp when the button was last pressed down. Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 65](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L65)) ### timeUp : number The timestamp when the button was last released. Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 71](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L71)) ### value : number Button value. Mainly useful for checking analog buttons (like shoulder triggers) on Gamepads. Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 109](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L109)) Public Methods -------------- ### destroy() Destroys this DeviceButton, this disposes of the onDown, onUp and onFloat signals and clears the parent and game references. Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 279](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L279)) ### justPressed(duration) → {boolean} Returns the "just pressed" state of this button. Just pressed is considered true if the button was pressed down within the duration given (default 250ms). ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `duration` | number | <optional> | 250 | The duration in ms below which the button is considered as being just pressed. | ##### Returns boolean - True if the button is just pressed otherwise false. Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 228](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L228)) ### justReleased(duration) → {boolean} Returns the "just released" state of this button. Just released is considered as being true if the button was released within the duration given (default 250ms). ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `duration` | number | <optional> | 250 | The duration in ms below which the button is considered as being just released. | ##### Returns boolean - True if the button is just released otherwise false. Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 244](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L244)) ### <internal> padFloat(value) Called automatically by Phaser.SinglePad. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `value` | number | Button value | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L213)) ### reset() Resets this DeviceButton, changing it to an isUp state and resetting the duration and repeats counters. Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 260](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L260)) ### <internal> start(event, value) Called automatically by Phaser.Pointer and Phaser.SinglePad. Handles the button down state. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `event` | object | <optional> | The DOM event that triggered the button change. | | `value` | number | <optional> | The button value. Only get for Gamepads. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 144](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L144)) ### <internal> stop(event, value) Called automatically by Phaser.Pointer and Phaser.SinglePad. Handles the button up state. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `event` | object | <optional> | The DOM event that triggered the button change. | | `value` | number | <optional> | The button value. Only get for Gamepads. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/DeviceButton.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js) ([Line 179](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/DeviceButton.js#L179)) phaser Class: Phaser.Physics.P2.RotationalSpring Class: Phaser.Physics.P2.RotationalSpring ========================================= Constructor ----------- ### new RotationalSpring(world, bodyA, bodyB, restAngle, stiffness, damping) Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `world` | [Phaser.Physics.P2](phaser.physics.p2) | | | A reference to the P2 World. | | `bodyA` | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | First connected body. | | `bodyB` | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | Second connected body. | | `restAngle` | number | <optional> | | The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. | | `stiffness` | number | <optional> | 100 | Stiffness of the spring. A number >= 0. | | `damping` | number | <optional> | 1 | Damping of the spring. A number >= 0. | Source code: [physics/p2/RotationalSpring.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/RotationalSpring.js) ([Line 19](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/RotationalSpring.js#L19)) Public Properties ----------------- ### data :p2.RotationalSpring The actual p2 spring object. Source code: [physics/p2/RotationalSpring.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/RotationalSpring.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/RotationalSpring.js#L49)) ### game : [Phaser.Game](phaser.game) Local reference to game. Source code: [physics/p2/RotationalSpring.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/RotationalSpring.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/RotationalSpring.js#L24)) ### world : [Phaser.Physics.P2](phaser.physics.p2) Local reference to P2 World. Source code: [physics/p2/RotationalSpring.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/RotationalSpring.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/RotationalSpring.js#L29)) phaser Class: Phaser.Device Class: Phaser.Device ==================== Constructor ----------- ### <internal> new Device() It is not possible to instantiate the Device class manually. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L30)) Public Properties ----------------- ### <static, nullable> onInitialized : [Phaser.Signal](phaser.signal) This signal is dispatched after device initialization occurs but before any of the ready callbacks (see [whenReady](phaser.device#.whenReady)) have been invoked. Local "patching" for a particular device can/should be done in this event. *Note*: This signal is removed after the device has been readied; if a handler has not been added *before* `new Phaser.Game(..)` it is probably too late. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 544](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L544)) ### android : boolean Is running on android? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 118](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L118)) ### arora : boolean Set to true if running in Arora. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 257](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L257)) ### audioData : boolean Are Audio tags available? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 367](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L367)) ### cancelFullscreen : string If the browser supports the Full Screen API this holds the call you need to use to cancel it. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 518](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L518)) ### canvas : boolean Is canvas available? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 156](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L156)) ### canvasBitBltShift : boolean True if canvas supports a 'copy' bitblt onto itself when the source and destination regions overlap. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 162](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L162)) ### chrome : boolean Set to true if running in Chrome. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 263](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L263)) ### chromeOS : boolean Is running on chromeOS? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L124)) ### chromeVersion : number If running in Chrome this will contain the major version number. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 269](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L269)) ### cocoonJS : boolean Is the game running under CocoonJS? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 70](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L70)) ### cocoonJSApp : boolean Is this game running with CocoonJS.App? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 76](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L76)) ### cordova : boolean Is the game running under Apache Cordova? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 82](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L82)) ### crosswalk : boolean Is the game running under the Intel Crosswalk XDK? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L112)) ### css3D : boolean Is css3D available? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 198](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L198)) ### desktop : boolean Is running on a desktop? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 52](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L52)) ### <internal> deviceReadyAt : integer The time the device became ready. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L37)) ### dolby : boolean Can this device play EC-3 Dolby Digital Plus files? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 416](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L416)) ### edge : boolean Set to true if running in Microsoft Edge browser. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 317](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L317)) ### ejecta : boolean Is the game running under Ejecta? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 106](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L106)) ### electron : boolean Is the game running under GitHub Electron? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 100](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L100)) ### epiphany : boolean Set to true if running in Epiphany. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 275](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L275)) ### file : boolean Is file available? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 174](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L174)) ### fileSystem : boolean Is fileSystem available? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 180](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L180)) ### firefox : boolean Set to true if running in Firefox. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 281](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L281)) ### firefoxVersion : number If running in Firefox this will contain the major version number. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 287](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L287)) ### fullscreen : boolean Does the browser support the Full Screen API? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 506](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L506)) ### fullscreenKeyboard : boolean Does the browser support access to the Keyboard during Full Screen mode? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 524](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L524)) ### getUserMedia : boolean Does the device support the getUserMedia API? Default Value * true Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 222](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L222)) ### h264Video : boolean Can this device play h264 mp4 video files? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 430](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L430)) ### hlsVideo : boolean Can this device play hls video files? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 454](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L454)) ### ie : boolean Set to true if running in Internet Explorer. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 293](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L293)) ### ieVersion : number If running in Internet Explorer this will contain the major version number. Beyond IE10 you should use Device.trident and Device.tridentVersion. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 299](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L299)) ### <internal> initialized : boolean The time as which initialization has completed. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 44](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L44)) ### iOS : boolean Is running on iOS? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L58)) ### iOSVersion : number If running in iOS this will contain the major version number. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 64](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L64)) ### iPad : boolean Is running on iPad? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 474](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L474)) ### iPhone : boolean Is running on iPhone? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 462](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L462)) ### iPhone4 : boolean Is running on iPhone4? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 468](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L468)) ### linux : boolean Is running on linux? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 130](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L130)) ### LITTLE\_ENDIAN : boolean Same value as `littleEndian`. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 494](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L494)) ### littleEndian : boolean Is the device big or little endian? (only detected if the browser supports TypedArrays) Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 488](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L488)) ### localStorage : boolean Is localStorage available? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 186](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L186)) ### m4a : boolean Can this device play m4a files? True if this device can play m4a files. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 404](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L404)) ### macOS : boolean Is running on macOS? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 136](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L136)) ### midori : boolean Set to true if running in Midori. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 329](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L329)) ### mobileSafari : boolean Set to true if running in Mobile Safari. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 323](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L323)) ### mp3 : boolean Can this device play mp3 files? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 391](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L391)) ### mp4Video : boolean Can this device play h264 mp4 video files? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 436](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L436)) ### mspointer : boolean Is mspointer available? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 242](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L242)) ### node : boolean Is the game running under Node.js? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 88](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L88)) ### nodeWebkit : boolean Is the game running under Node-Webkit? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 94](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L94)) ### ogg : boolean Can this device play ogg files? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 379](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L379)) ### oggVideo : boolean Can this device play ogg video files? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 424](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L424)) ### opera : boolean Set to true if running in Opera. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 335](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L335)) ### opus : boolean Can this device play opus files? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 385](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L385)) ### pixelRatio : number PixelRatio of the host device? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 482](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L482)) ### pointerLock : boolean Is Pointer Lock available? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 204](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L204)) ### quirksMode : boolean Is the browser running in strict mode (false) or quirks mode? (true) Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 228](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L228)) ### requestFullscreen : string If the browser supports the Full Screen API this holds the call you need to use to activate it. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 512](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L512)) ### safari : boolean Set to true if running in Safari. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 341](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L341)) ### safariVersion : number If running in Safari this will contain the major version number. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 347](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L347)) ### silk : boolean Set to true if running in the Silk browser (as used on the Amazon Kindle) Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 359](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L359)) ### support32bit : boolean Does the device context support 32bit pixel manipulation using array buffer views? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 500](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L500)) ### touch : boolean Is touch available? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 236](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L236)) ### trident : boolean Set to true if running a Trident version of Internet Explorer (IE11+) Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 305](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L305)) ### tridentVersion : number If running in Internet Explorer 11 this will contain the major version number. See <http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx> Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 311](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L311)) ### typedArray : boolean Does the browser support TypedArrays? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 210](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L210)) ### vibration : boolean Does the device support the Vibration API? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 216](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L216)) ### vp9Video : boolean Can this device play vp9 video files? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 448](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L448)) ### wav : boolean Can this device play wav files? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 397](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L397)) ### webApp : boolean Set to true if running as a WebApp, i.e. within a WebView Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 353](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L353)) ### webAudio : boolean Is the WebAudio API available? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 373](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L373)) ### webGL : boolean Is webGL available? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 168](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L168)) ### webm : boolean Can this device play webm files? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 410](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L410)) ### webmVideo : boolean Can this device play webm video files? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 442](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L442)) ### <internal> wheelEvent ##### Properties: | Name | Type | Argument | Description | | --- | --- | --- | --- | | `wheelType` | string | <nullable> | The newest type of Wheel/Scroll event supported: 'wheel', 'mousewheel', 'DOMMouseScroll' | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 249](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L249)) ### windows : boolean Is running on windows? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 142](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L142)) ### windowsPhone : boolean Is running on a Windows Phone? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 148](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L148)) ### worker : boolean Is worker available? Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 192](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L192)) Public Methods -------------- ### <static> whenReady(handler, context, nonPrimer) Add a device-ready handler and ensure the device ready sequence is started. Phaser.Device will *not* activate or initialize until at least one `whenReady` handler is added, which is normally done automatically be calling `new Phaser.Game(..)`. The handler is invoked when the device is considered "ready", which may be immediately if the device is already "ready". See [deviceReadyAt](phaser.device#deviceReadyAt). ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `handler` | function | | | Callback to invoke when the device is ready. It is invoked with the given context the Phaser.Device object is supplied as the first argument. | | `context` | object | <optional> | | Context in which to invoke the handler | | `nonPrimer` | boolean | <optional> | false | If true the device ready check will not be started. | Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 560](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L560)) ### canPlayAudio(type) → {boolean} Check whether the host environment can play audio. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `type` | string | One of 'mp3, 'ogg', 'm4a', 'wav', 'webm' or 'opus'. | ##### Returns boolean - True if the given file type is supported by the browser, otherwise false. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 1250](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L1250)) ### canPlayVideo(type) → {boolean} Check whether the host environment can play video files. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `type` | string | One of 'mp4, 'ogg', 'webm' or 'mpeg'. | ##### Returns boolean - True if the given file type is supported by the browser, otherwise false. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 1293](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L1293)) ### isAndroidStockBrowser() Detect if the host is a an Android Stock browser. This is available before the device "ready" event. Authors might want to scale down on effects and switch to the CANVAS rendering method on those devices. Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 1359](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L1359)) ##### Example ``` var defaultRenderingMode = Phaser.Device.isAndroidStockBrowser() ? Phaser.CANVAS : Phaser.AUTO; ``` ### isConsoleOpen() Check whether the console is open. Note that this only works in Firefox with Firebug and earlier versions of Chrome. It used to work in Chrome, but then they removed the ability: <http://src.chromium.org/viewvc/blink?view=revision&revision=151136> Source code: [utils/Device.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js) ([Line 1324](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Device.js#L1324))
programming_docs
phaser Class: PIXI.TilingSprite Class: PIXI.TilingSprite ======================== Constructor ----------- ### new TilingSprite(texture, width, height) A tiling sprite is a fast way of rendering a tiling image ##### Parameters | Name | Type | Description | | --- | --- | --- | | `texture` | [PIXI.Texture](pixi.texture) | the texture of the tiling sprite | | `width` | Number | the width of the tiling sprite | | `height` | Number | the height of the tiling sprite | Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 5](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L5)) Extends ------- * [PIXI.Sprite](pixi.sprite) Public Properties ----------------- ### anchor :Point The anchor sets the origin point of the texture. The default is 0,0 this means the texture's origin is the top left Setting than anchor to 0.5,0.5 means the textures origin is centered Setting the anchor to 1,1 would mean the textures origin points will be the bottom right corner Inherited From * [PIXI.Sprite#anchor](pixi.sprite#anchor) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L17)) ### blendMode : number The blend mode to be applied to the sprite Default Value * PIXI.blendModes.NORMAL; Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L86)) ### canvasBuffer :PIXICanvasBuffer The CanvasBuffer object that the tiled texture is drawn to. Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 95](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L95)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### exists : boolean Controls if this Sprite is processed by the core Phaser game loops and Group loops. Inherited From * [PIXI.Sprite#exists](pixi.sprite#exists) Default Value * true Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 103](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L103)) ### height : number The height of the tiling sprite Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 27](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L27)) ### height : number The height of the TilingSprite, setting this will actually modify the scale to achieve the value set Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 535](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L535)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### refreshTexture : boolean If true the TilingSprite will run generateTexture on its **next** render pass. This is set by the likes of Phaser.LoadTexture.setFrame. Default Value * true Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 119](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L119)) ### renderable : boolean Whether this sprite is renderable or not Default Value * true Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 59](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L59)) ### shader : [PIXI.AbstractFilter](pixi.abstractfilter) The shader that will be used to render this Sprite. Set to null to remove a current shader. Inherited From * [PIXI.Sprite#shader](pixi.sprite#shader) Default Value * null Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L93)) ### texture : [PIXI.Texture](pixi.texture) The texture that the sprite is using Inherited From * [PIXI.Sprite#texture](pixi.sprite#texture) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L28)) ### textureDebug : boolean If enabled a green rectangle will be drawn behind the generated tiling texture, allowing you to visually debug the texture being used. Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 77](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L77)) ### tilePattern :PIXITexture The Context fill pattern that is used to draw the TilingSprite in Canvas mode only (will be null in WebGL). Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 111](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L111)) ### tilePosition :Point The offset position of the image that is being tiled Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L51)) ### tileScale :Point The scaling of the image that is being tiled Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 35](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L35)) ### tileScaleOffset :Point A point that represents the scale of the texture object Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 43](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L43)) ### tilingTexture :PIXITexture An internal Texture object that holds the tiling texture that was generated from TilingSprite.texture. Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 103](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L103)) ### tint : number The tint applied to the sprite. This is a hex value Default Value * 0xFFFFFF Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 68](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L68)) ### tintedTexture :Canvas A canvas that contains the tinted version of the Sprite (in Canvas mode, WebGL doesn't populate this) Inherited From * [PIXI.Sprite#tintedTexture](pixi.sprite#tintedTexture) Default Value * null Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 73](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L73)) ### width : number The width of the sprite, setting this will actually modify the scale to achieve the value set Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 517](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L517)) ### width : number The width of the tiling sprite Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 19](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L19)) Public Methods -------------- ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### generateTilingTexture(forcePowerOfTwo, renderSession) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `forcePowerOfTwo` | Boolean | Whether we want to force the texture to be a power of two | | `renderSession` | RenderSession | - | Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 332](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L332)) ### getBounds() → {Rectangle} Returns the framing rectangle of the sprite as a PIXI.Rectangle object ##### Returns Rectangle - the framing rectangle Source code: [pixi/extras/TilingSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js) ([Line 417](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/TilingSprite.js#L417)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the Sprite as a rectangle. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.Sprite#getLocalBounds](pixi.sprite#getLocalBounds) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 315](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L315)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### setTexture(texture, destroy) Sets the texture of the sprite. Be warned that this doesn't remove or destroy the previous texture this Sprite was using. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `texture` | [PIXI.Texture](pixi.texture) | | | The PIXI texture that is displayed by the sprite | | `destroy` | Boolean | <optional> | false | Call Texture.destroy on the current texture before replacing it with the new one? | Inherited From * [PIXI.Sprite#setTexture](pixi.sprite#setTexture) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 163](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L163)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) phaser Class: Phaser.SpriteBatch Class: Phaser.SpriteBatch ========================= Constructor ----------- ### new SpriteBatch(game, parent, name, addToStage) The SpriteBatch class is a really fast version of the DisplayObjectContainer built purely for speed, so use when you need a lot of sprites or particles. It's worth mentioning that by default sprite batches are used through-out the renderer, so you only really need to use a SpriteBatch if you have over 1000 sprites that all share the same texture (or texture atlas). It's also useful if running in Canvas mode and you have a lot of un-rotated or un-scaled Sprites as it skips all of the Canvas setTransform calls, which helps performance, especially on mobile devices. Please note that any Sprite that is part of a SpriteBatch will not have its bounds updated, so will fail checks such as outOfBounds. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | | A reference to the currently running game. | | `parent` | [Phaser.Group](phaser.group) | [Phaser.Sprite](phaser.sprite) | null | | | The parent Group, DisplayObject or DisplayObjectContainer that this Group will be added to. If `undefined` or `null` it will use game.world. | | `name` | string | <optional> | group | A name for this Group. Not used internally but useful for debugging. | | `addToStage` | boolean | <optional> | false | If set to true this Group will be added directly to the Game.Stage instead of Game.World. | Source code: [gameobjects/SpriteBatch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/SpriteBatch.js) ([Line 23](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/SpriteBatch.js#L23)) Extends ------- * [Phaser.Group](phaser.group) Public Properties ----------------- ### alive : boolean The alive property is useful for Groups that are children of other Groups and need to be included/excluded in checks like forEachAlive. Inherited From * [Phaser.Group#alive](phaser.group#alive) Default Value * true Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L93)) ### alpha : number The alpha value of the group container. Inherited From * [Phaser.Group#alpha](phaser.group#alpha) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 3003](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L3003)) ### angle : number The angle of rotation of the group container, in degrees. This adjusts the group itself by modifying its local rotation transform. This has no impact on the rotation/angle properties of the children, but it will update their worldTransform and on-screen orientation and position. Inherited From * [Phaser.Group#angle](phaser.group#angle) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2682](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2682)) ### bottom : number The bottom coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#bottom](phaser.group#bottom) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2845](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2845)) ### cameraOffset : [Phaser.Point](phaser.point) If this object is [fixedToCamera](phaser.group#fixedToCamera) then this stores the x/y position offset relative to the top-left of the camera view. If the parent of this Group is also `fixedToCamera` then the offset here is in addition to that and should typically be disabled. Inherited From * [Phaser.Group#cameraOffset](phaser.group#cameraOffset) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 272](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L272)) ### centerX : number The center x coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#centerX](phaser.group#centerX) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2705](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2705)) ### centerY : number The center y coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#centerY](phaser.group#centerY) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2733](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2733)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### classType : Object The type of objects that will be created when using [create](phaser.group#create) or [createMultiple](phaser.group#createMultiple). Any object may be used but it should extend either Sprite or Image and accept the same constructor arguments: when a new object is created it is passed the following parameters to its constructor: `(game, x, y, key, frame)`. Inherited From * [Phaser.Group#classType](phaser.group#classType) Default Value * [Phaser.Sprite](phaser.sprite) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 130](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L130)) ### cursor : [DisplayObject](global#DisplayObject) The current display object that the group cursor is pointing to, if any. (Can be set manually.) The cursor is a way to iterate through the children in a Group using [next](phaser.group#next) and [previous](phaser.group#previous). Inherited From * [Phaser.Group#cursor](phaser.group#cursor) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 138](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L138)) ### [readonly] cursorIndex : integer The current index of the Group cursor. Advance it with Group.next. Inherited From * [Phaser.Group#cursorIndex](phaser.group#cursorIndex) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 255](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L255)) ### enableBody : boolean If true all Sprites created by, or added to this group, will have a physics body enabled on them. If there are children already in the Group at the time you set this property, they are not changed. The default body type is controlled with [physicsBodyType](phaser.group#physicsBodyType). Inherited From * [Phaser.Group#enableBody](phaser.group#enableBody) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 208](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L208)) ### enableBodyDebug : boolean If true when a physics body is created (via [enableBody](phaser.group#enableBody)) it will create a physics debug object as well. This only works for P2 bodies. Inherited From * [Phaser.Group#enableBodyDebug](phaser.group#enableBodyDebug) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L217)) ### exists : boolean If exists is true the group is updated, otherwise it is skipped. Inherited From * [Phaser.Group#exists](phaser.group#exists) Default Value * true Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 100](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L100)) ### fixedToCamera : boolean A Group that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Group.cameraOffset. Note that the cameraOffset values are in addition to any parent in the display list. So if this Group was in a Group that has x: 200, then this will be added to the cameraOffset.x Inherited From * [Phaser.Group#fixedToCamera](phaser.group#fixedToCamera) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 265](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L265)) ### <internal> game : [Phaser.Game](phaser.game) A reference to the currently running Game. Inherited From * [Phaser.Group#game](phaser.group#game) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L38)) ### hash :array The hash array is an array belonging to this Group into which you can add any of its children via Group.addToHash and Group.removeFromHash. Only children of this Group can be added to and removed from the hash. This hash is used automatically by Phaser Arcade Physics in order to perform non z-index based destructive sorting. However if you don't use Arcade Physics, or this isn't a physics enabled Group, then you can use the hash to perform your own sorting and filtering of Group children without touching their z-index (and therefore display draw order) Inherited From * [Phaser.Group#hash](phaser.group#hash) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 285](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L285)) ### height : number The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#height](pixi.displayobjectcontainer#height) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 600](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L600)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### ignoreDestroy : boolean A group with `ignoreDestroy` set to `true` ignores all calls to its `destroy` method. Inherited From * [Phaser.Group#ignoreDestroy](phaser.group#ignoreDestroy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 107](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L107)) ### inputEnableChildren : boolean A Group with `inputEnableChildren` set to `true` will automatically call `inputEnabled = true` on any children *added* to, or *created by*, this Group. If there are children already in the Group at the time you set this property, they are not changed. Inherited From * [Phaser.Group#inputEnableChildren](phaser.group#inputEnableChildren) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 149](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L149)) ### left : number The left coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#left](phaser.group#left) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2761](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2761)) ### [readonly] length : integer Total number of children in this group, regardless of exists/alive status. Inherited From * [Phaser.Group#length](phaser.group#length) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2665](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2665)) ### name : string A name for this group. Not used internally but useful for debugging. Inherited From * [Phaser.Group#name](phaser.group#name) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L49)) ### onChildInputDown : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputDown signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and a reference to the Pointer that caused it. Inherited From * [Phaser.Group#onChildInputDown](phaser.group#onChildInputDown) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 161](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L161)) ### onChildInputOut : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputOut signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and a reference to the Pointer that caused it. Inherited From * [Phaser.Group#onChildInputOut](phaser.group#onChildInputOut) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 198](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L198)) ### onChildInputOver : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputOver signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and a reference to the Pointer that caused it. Inherited From * [Phaser.Group#onChildInputOver](phaser.group#onChildInputOver) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 186](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L186)) ### onChildInputUp : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputUp signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 3 arguments: A reference to the Sprite that triggered the signal, a reference to the Pointer that caused it, and a boolean value `isOver` that tells you if the Pointer is still over the Sprite or not. Inherited From * [Phaser.Group#onChildInputUp](phaser.group#onChildInputUp) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 174](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L174)) ### onDestroy : [Phaser.Signal](phaser.signal) This signal is dispatched when the group is destroyed. Inherited From * [Phaser.Group#onDestroy](phaser.group#onDestroy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 249](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L249)) ### pendingDestroy : boolean A Group is that has `pendingDestroy` set to `true` is flagged to have its destroy method called on the next logic update. You can set it directly to flag the Group to be destroyed on its next update. This is extremely useful if you wish to destroy a Group from within one of its own callbacks or a callback of one of its children. Inherited From * [Phaser.Group#pendingDestroy](phaser.group#pendingDestroy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 119](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L119)) ### physicsBodyType : integer If [enableBody](phaser.group#enableBody) is true this is the type of physics body that is created on new Sprites. The valid values are [Phaser.Physics.ARCADE](phaser.physics#.ARCADE), [Phaser.Physics.P2JS](phaser.physics#.P2JS), [Phaser.Physics.NINJA](phaser.physics#.NINJA), etc. Inherited From * [Phaser.Group#physicsBodyType](phaser.group#physicsBodyType) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 225](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L225)) ### physicsSortDirection : integer If this Group contains Arcade Physics Sprites you can set a custom sort direction via this property. It should be set to one of the Phaser.Physics.Arcade sort direction constants: Phaser.Physics.Arcade.SORT\_NONE Phaser.Physics.Arcade.LEFT\_RIGHT Phaser.Physics.Arcade.RIGHT\_LEFT Phaser.Physics.Arcade.TOP\_BOTTOM Phaser.Physics.Arcade.BOTTOM\_TOP If set to `null` the Group will use whatever Phaser.Physics.Arcade.sortDirection is set to. This is the default behavior. Inherited From * [Phaser.Group#physicsSortDirection](phaser.group#physicsSortDirection) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 243](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L243)) ### [readonly] physicsType : number The const physics body type of this object. Inherited From * [Phaser.Group#physicsType](phaser.group#physicsType) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L86)) ### right : number The right coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#right](phaser.group#right) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2789](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2789)) ### rotation : number The angle of rotation of the group container, in radians. This will adjust the group container itself by modifying its rotation. This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position. Inherited From * [Phaser.Group#rotation](phaser.group#rotation) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2987](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2987)) ### top : number The top coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#top](phaser.group#top) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2817](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2817)) ### [readonly] total : integer Total number of existing children in the group. Inherited From * [Phaser.Group#total](phaser.group#total) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2648](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2648)) ### <internal> type : number Internal Phaser Type value. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/SpriteBatch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/SpriteBatch.js) ([Line 35](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/SpriteBatch.js#L35)) ### visible : boolean The visible state of the group. Non-visible Groups and all of their children are not rendered. Inherited From * [Phaser.Group#visible](phaser.group#visible) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2996](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2996)) ### width : number The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#width](pixi.displayobjectcontainer#width) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 571](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L571)) ### x : number The x coordinate of the group container. You can adjust the group container itself by modifying its coordinates. This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. Inherited From * [Phaser.Group#x](phaser.group#x) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2969](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2969)) ### y : number The y coordinate of the group container. You can adjust the group container itself by modifying its coordinates. This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. Inherited From * [Phaser.Group#y](phaser.group#y) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2978](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2978)) ### [readonly] z : integer The z-depth value of this object within its parent container/Group - the World is a Group as well. This value must be unique for each child in a Group. Inherited From * [Phaser.Group#z](phaser.group#z) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 57](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L57)) Public Methods -------------- ### add(child, silent, index) → {[DisplayObject](global#DisplayObject)} Adds an existing object as the top child in this group. The child is automatically added to the top of the group, and is displayed above every previous child. Or if the *optional* index is specified, the child is added at the location specified by the index value, this allows you to control child ordering. If the child was already in this Group, it is simply returned, and nothing else happens to it. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. Use [addAt](phaser.group#addAt) to control where a child is added. Use [create](phaser.group#create) to create and add a new child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | | | The display object to add as a child. | | `silent` | boolean | <optional> | false | If true the child will not dispatch the `onAddedToGroup` event. | | `index` | integer | <optional> | | The index within the group to insert the child to. Where 0 is the bottom of the Group. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added to the group. Inherited From * [Phaser.Group#add](phaser.group#add) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 341](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L341)) ### addAll(property, amount, checkAlive, checkVisible) Adds the amount to the given property on all children in this group. `Group.addAll('x', 10)` will add 10 to the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to increment, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Inherited From * [Phaser.Group#addAll](phaser.group#addAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1386](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1386)) ### addAt(child, index, silent) → {[DisplayObject](global#DisplayObject)} Adds an existing object to this group. The child is added to the group at the location specified by the index value, this allows you to control child ordering. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | | | The display object to add as a child. | | `index` | integer | <optional> | 0 | The index within the group to insert the child to. | | `silent` | boolean | <optional> | false | If true the child will not dispatch the `onAddedToGroup` event. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added to the group. Inherited From * [Phaser.Group#addAt](phaser.group#addAt) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 418](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L418)) ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### addMultiple(children, silent) → {Array.<[DisplayObject](global#DisplayObject)> | [Phaser.Group](phaser.group)} Adds an array of existing Display Objects to this Group. The Display Objects are automatically added to the top of this Group, and will render on-top of everything already in this Group. As well as an array you can also pass another Group as the first argument. In this case all of the children from that Group will be removed from it and added into this Group. If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `children` | Array.<[DisplayObject](global#DisplayObject)> | [Phaser.Group](phaser.group) | | | An array of display objects or a Phaser.Group. If a Group is given then *all* children will be moved from it. | | `silent` | boolean | <optional> | false | If true the children will not dispatch the `onAddedToGroup` event. | ##### Returns Array.<[DisplayObject](global#DisplayObject)> | [Phaser.Group](phaser.group) - The array of children or Group of children that were added to this Group. Inherited From * [Phaser.Group#addMultiple](phaser.group#addMultiple) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 489](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L489)) ### addToHash(child) → {boolean} Adds a child of this Group into the hash array. This call will return false if the child is not a child of this Group, or is already in the hash. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The display object to add to this Groups hash. Must be a member of this Group already and not present in the hash. | ##### Returns boolean - True if the child was successfully added to the hash, otherwise false. Inherited From * [Phaser.Group#addToHash](phaser.group#addToHash) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 439](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L439)) ### align(width, height, cellWidth, cellHeight, position, offset) → {boolean} This method iterates through all children in the Group (regardless if they are visible or exist) and then changes their position so they are arranged in a Grid formation. Children must have the `alignTo` method in order to be positioned by this call. All default Phaser Game Objects have this. The grid dimensions are determined by the first four arguments. The `width` and `height` arguments relate to the width and height of the grid respectively. For example if the Group had 100 children in it: `Group.align(10, 10, 32, 32)` This will align all of the children into a grid formation of 10x10, using 32 pixels per grid cell. If you want a wider grid, you could do: `Group.align(25, 4, 32, 32)` This will align the children into a grid of 25x4, again using 32 pixels per grid cell. You can choose to set *either* the `width` or `height` value to -1. Doing so tells the method to keep on aligning children until there are no children left. For example if this Group had 48 children in it, the following: `Group.align(-1, 8, 32, 32)` ... will align the children so that there are 8 children vertically (the second argument), and each row will contain 6 sprites, except the last one, which will contain 5 (totaling 48) You can also do: `Group.align(10, -1, 32, 32)` In this case it will create a grid 10 wide, and as tall as it needs to be in order to fit all of the children in. The `position` property allows you to control where in each grid cell the child is positioned. This is a constant and can be one of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. The final argument; `offset` lets you start the alignment from a specific child index. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `width` | integer | | | The width of the grid in items (not pixels). Set to -1 for a dynamic width. If -1 then you must set an explicit height value. | | `height` | integer | | | The height of the grid in items (not pixels). Set to -1 for a dynamic height. If -1 then you must set an explicit width value. | | `cellWidth` | integer | | | The width of each grid cell, in pixels. | | `cellHeight` | integer | | | The height of each grid cell, in pixels. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offset` | integer | <optional> | 0 | Optional index to start the alignment from. Defaults to zero, the first child in the Group, but can be set to any valid child index value. | ##### Returns boolean - True if the Group children were aligned, otherwise false. Inherited From * [Phaser.Group#align](phaser.group#align) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 682](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L682)) ### alignIn(container, position, offsetX, offsetY) → {[Phaser.Group](phaser.group)} Aligns this Group within another Game Object, or Rectangle, known as the 'container', to one of 9 possible positions. The container must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Groups within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Group to another Game Object does **not** make it a child of the container. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. Groups are placed in such a way that their *bounds* align with the container, taking into consideration rotation and scale of its children. This allows you to neatly align Groups, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Group. For example: `group.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `container` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns [Phaser.Group](phaser.group) - This Group. Inherited From * [Phaser.Group#alignIn](phaser.group#alignIn) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2873](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2873)) ### alignTo(parent, position, offsetX, offsetY) → {[Phaser.Group](phaser.group)} Aligns this Group to the side of another Game Object, or Rectangle, known as the 'parent', in one of 11 possible positions. The parent must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Groups within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Group to another Game Object does **not** make it a child of the parent. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. Groups are placed in such a way that their *bounds* align with the parent, taking into consideration rotation and scale of the children. This allows you to neatly align Groups, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Group. For example: `group.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns [Phaser.Group](phaser.group) - This Group. Inherited From * [Phaser.Group#alignTo](phaser.group#alignTo) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2915](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2915)) ### <internal> ascendingSortHandler(a, b) An internal helper function for the sort process. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | object | The first object being sorted. | | `b` | object | The second object being sorted. | Inherited From * [Phaser.Group#ascendingSortHandler](phaser.group#ascendingSortHandler) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1919](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1919)) ### bringToTop(child) → {any} Brings the given child to the top of this group so it renders above all other children. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to bring to the top of this group. | ##### Returns any - The child that was moved. Inherited From * [Phaser.Group#bringToTop](phaser.group#bringToTop) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 907](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L907)) ### callAll(method, context, args) Calls a function, specified by name, on all on children. The function is called for all children regardless if they are dead or alive (see callAllExists for different options). After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `method` | string | | | Name of the function on the child to call. Deep property lookup is supported. | | `context` | string | <optional> | null | A string containing the context under which the method will be executed. Set to null to default to the child. | | `args` | any | <repeatable> | | Additional parameters that will be passed to the method. | Inherited From * [Phaser.Group#callAll](phaser.group#callAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1538](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1538)) ### callAllExists(callback, existsValue, parameter) Calls a function, specified by name, on all children in the group who exist (or do not exist). After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `callback` | string | | Name of the function on the children to call. | | `existsValue` | boolean | | Only children with exists=existsValue will be called. | | `parameter` | any | <repeatable> | Additional parameters that will be passed to the callback. | Inherited From * [Phaser.Group#callAllExists](phaser.group#callAllExists) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1454](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1454)) ### <internal> callbackFromArray(child, callback, length) Returns a reference to a function that exists on a child of the group based on the given callback array. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | object | The object to inspect. | | `callback` | array | The array of function names. | | `length` | integer | The size of the array (pre-calculated in callAll). | Inherited From * [Phaser.Group#callbackFromArray](phaser.group#callbackFromArray) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1488](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1488)) ### checkAll(key, value, checkAlive, checkVisible, force) Quickly check that the same property across all children of this group is equal to the given value. This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be checked. | | `checkAlive` | boolean | <optional> | false | If set then only children with alive=true will be checked. This includes any Groups that are children. | | `checkVisible` | boolean | <optional> | false | If set then only children with visible=true will be checked. This includes any Groups that are children. | | `force` | boolean | <optional> | false | If `force` is true then the property will be checked on the child regardless if it already exists or not. If true and the property doesn't exist, false will be returned. | Inherited From * [Phaser.Group#checkAll](phaser.group#checkAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1353](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1353)) ### checkProperty(child, key, value, force) → {boolean} Checks a property for the given value on the child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | any | | | The child to check the property value on. | | `key` | array | | | An array of strings that make up the property that will be set. | | `value` | any | | | The value that will be checked. | | `force` | boolean | <optional> | false | If `force` is true then the property will be checked on the child regardless if it already exists or not. If true and the property doesn't exist, false will be returned. | ##### Returns boolean - True if the property was was equal to value, false if not. Inherited From * [Phaser.Group#checkProperty](phaser.group#checkProperty) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1217)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### countDead() → {integer} Get the number of dead children in this group. ##### Returns integer - The number of children flagged as dead. Inherited From * [Phaser.Group#countDead](phaser.group#countDead) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2338](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2338)) ### countLiving() → {integer} Get the number of living children in this group. ##### Returns integer - The number of children flagged as alive. Inherited From * [Phaser.Group#countLiving](phaser.group#countLiving) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2326](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2326)) ### create(x, y, key, frame, exists, index) → {[DisplayObject](global#DisplayObject)} Creates a new Phaser.Sprite object and adds it to the top of this group. Use [classType](phaser.group#classType) to change the type of object created. The child is automatically added to the top of the group, and is displayed above every previous child. Or if the *optional* index is specified, the child is added at the location specified by the index value, this allows you to control child ordering. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate to display the newly created Sprite at. The value is in relation to the group.x point. | | `y` | number | | | The y coordinate to display the newly created Sprite at. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | | `exists` | boolean | <optional> | true | The default exists state of the Sprite. | | `index` | integer | <optional> | | The index within the group to insert the child to. Where 0 is the bottom of the Group. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was created: will be a [Phaser.Sprite](phaser.sprite) unless #classType has been changed. Inherited From * [Phaser.Group#create](phaser.group#create) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 544](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L544)) ### createMultiple(quantity, key, frame, exists) → {array} Creates multiple Phaser.Sprite objects and adds them to the top of this Group. This method is useful if you need to quickly generate a pool of sprites, such as bullets. Use [classType](phaser.group#classType) to change the type of object created. You can provide an array as the `key` and / or `frame` arguments. When you do this it will create `quantity` Sprites for every key (and frame) in the arrays. For example: `createMultiple(25, ['ball', 'carrot'])` In the above code there are 2 keys (ball and carrot) which means that 50 sprites will be created in total, 25 of each. You can also have the `frame` as an array: `createMultiple(5, 'bricks', [0, 1, 2, 3])` In the above there is one key (bricks), which is a sprite sheet. The frames array tells this method to use frames 0, 1, 2 and 3. So in total it will create 20 sprites, because the quantity was set to 5, so that is 5 brick sprites of frame 0, 5 brick sprites with frame 1, and so on. If you set both the key and frame arguments to be arrays then understand it will create a total quantity of sprites equal to the size of both arrays times each other. I.e.: `createMultiple(20, ['diamonds', 'balls'], [0, 1, 2])` The above will create 20 'diamonds' of frame 0, 20 with frame 1 and 20 with frame 2. It will then create 20 'balls' of frame 0, 20 with frame 1 and 20 with frame 2. In total it will have created 120 sprites. By default the Sprites will have their `exists` property set to `false`, and they will be positioned at 0x0, relative to the `Group.x / y` values. If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `quantity` | integer | | | The number of Sprites to create. | | `key` | string | array | | | The Cache key of the image that the Sprites will use. Or an Array of keys. See the description for details on how the quantity applies when arrays are used. | | `frame` | integer | string | array | <optional> | 0 | If the Sprite image contains multiple frames you can specify which one to use here. Or an Array of frames. See the description for details on how the quantity applies when arrays are used. | | `exists` | boolean | <optional> | false | The default exists state of the Sprite. | ##### Returns array - An array containing all of the Sprites that were created. Inherited From * [Phaser.Group#createMultiple](phaser.group#createMultiple) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 581](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L581)) ### customSort(sortHandler, context) Sort the children in the group according to custom sort function. The `sortHandler` is provided the two parameters: the two children involved in the comparison (a and b). It should return -1 if `a > b`, 1 if `a < b` or 0 if `a === b`. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `sortHandler` | function | | The custom sort function. | | `context` | object | <optional> | The context in which the sortHandler is called. | Inherited From * [Phaser.Group#customSort](phaser.group#customSort) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1895](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1895)) ### <internal> descendingSortHandler(a, b) An internal helper function for the sort process. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | object | The first object being sorted. | | `b` | object | The second object being sorted. | Inherited From * [Phaser.Group#descendingSortHandler](phaser.group#descendingSortHandler) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1951](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1951)) ### destroy(destroyChildren, soft) Destroys this group. Removes all children, then removes this group from its parent and nulls references. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroyChildren` | boolean | <optional> | true | If true `destroy` will be invoked on each removed child. | | `soft` | boolean | <optional> | false | A 'soft destroy' (set to true) doesn't remove this group from its parent or null the game reference. Set to false and it does. | Inherited From * [Phaser.Group#destroy](phaser.group#destroy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2611](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2611)) ### divideAll(property, amount, checkAlive, checkVisible) Divides the given property by the amount on all children in this group. `Group.divideAll('x', 2)` will half the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to divide, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Inherited From * [Phaser.Group#divideAll](phaser.group#divideAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1437](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1437)) ### filter(predicate, checkExists) → {[Phaser.ArraySet](phaser.arrayset)} Find children matching a certain predicate. For example: ``` var healthyList = Group.filter(function(child, index, children) { return child.health > 10 ? true : false; }, true); healthyList.callAll('attack'); ``` Note: Currently this will skip any children which are Groups themselves. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `predicate` | function | | | The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, the index as the second, and the entire child array as the third | | `checkExists` | boolean | <optional> | false | If true, only existing can be selected; otherwise all children can be selected and will be passed to the predicate. | ##### Returns [Phaser.ArraySet](phaser.arrayset) - Returns an array list containing all the children that the predicate returned true for Inherited From * [Phaser.Group#filter](phaser.group#filter) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1677](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1677)) ### forEach(callback, callbackContext, checkExists, args) Call a function on each child in this group. Additional arguments for the callback can be specified after the `checkExists` parameter. For example, ``` Group.forEach(awardBonusGold, this, true, 100, 500) ``` would invoke `awardBonusGold` function with the parameters `(child, 100, 500)`. Note: This check will skip any children which are Groups themselves. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `checkExists` | boolean | <optional> | false | If set only children matching for which `exists` is true will be passed to the callback, otherwise all children will be passed. | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Inherited From * [Phaser.Group#forEach](phaser.group#forEach) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1717](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1717)) ### forEachAlive(callback, callbackContext, args) Call a function on each alive child in this group. See [forEach](phaser.group#forEach) for details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Inherited From * [Phaser.Group#forEachAlive](phaser.group#forEachAlive) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1799](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1799)) ### forEachDead(callback, callbackContext, args) Call a function on each dead child in this group. See [forEach](phaser.group#forEach) for details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Inherited From * [Phaser.Group#forEachDead](phaser.group#forEachDead) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1827](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1827)) ### forEachExists(callback, callbackContext, args) Call a function on each existing child in this group. See [forEach](phaser.group#forEach) for details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Inherited From * [Phaser.Group#forEachExists](phaser.group#forEachExists) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1771](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1771)) ### getAll(property, value, startIndex, endIndex) → {any} Returns all children in this Group. You can optionally specify a matching criteria using the `property` and `value` arguments. For example: `getAll('exists', true)` would return only children that have their exists property set. Optionally you can specify a start and end index. For example if this Group had 100 children, and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only the first 50 children in the Group. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `property` | string | <optional> | | An optional property to test against the value argument. | | `value` | any | <optional> | | If property is set then Child.property must strictly equal this value to be included in the results. | | `startIndex` | integer | <optional> | 0 | The first child index to start the search from. | | `endIndex` | integer | <optional> | | The last child index to search up until. | ##### Returns any - A random existing child of this Group. Inherited From * [Phaser.Group#getAll](phaser.group#getAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2392](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2392)) ### getAt(index) → {[DisplayObject](global#DisplayObject) | integer} Returns the child found at the given index within this group. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | integer | The index to return the child from. | ##### Returns [DisplayObject](global#DisplayObject) | integer - The child that was found at the given index, or -1 for an invalid index. Inherited From * [Phaser.Group#getAt](phaser.group#getAt) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 524](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L524)) ### getBottom() → {any} Returns the child at the bottom of this group. The bottom child the child being displayed (rendered) below every other child. ##### Returns any - The child at the bottom of the Group. Inherited From * [Phaser.Group#getBottom](phaser.group#getBottom) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2221](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2221)) ### getBounds(targetCoordinateSpace) → {Rectangle} Retrieves the global bounds of the displayObjectContainer as a rectangle. The bounds calculation takes all visible children into consideration. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `targetCoordinateSpace` | PIXIDisplayObject | PIXIMatrix | <optional> | Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object. | ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.DisplayObjectContainer#getBounds](pixi.displayobjectcontainer#getBounds) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 280](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L280)) ### getByName(name) → {any} Searches the Group for the first instance of a child with the `name` property matching the given argument. Should more than one child have the same name only the first instance is returned. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `name` | string | The name to search for. | ##### Returns any - The first child with a matching name, or null if none were found. Inherited From * [Phaser.Group#getByName](phaser.group#getByName) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1042](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1042)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getClosestTo(object, callback, callbackContext) → {any} Get the closest child to given Object, with optional callback to filter children. This can be a Sprite, Group, Image or any object with public x and y properties. 'close' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. You can use the optional `callback` argument to apply your own filter to the distance checks. If the child is closer then the previous child, it will be sent to `callback` as the first argument, with the distance as the second. The callback should return `true` if it passes your filtering criteria, otherwise it should return `false`. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `object` | any | | The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. | | `callback` | function | <optional> | The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. | | `callbackContext` | object | <optional> | The context in which the function should be called (usually 'this'). | ##### Returns any - The child closest to given object, or `null` if no child was found. Inherited From * [Phaser.Group#getClosestTo](phaser.group#getClosestTo) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2238](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2238)) ### getFirstAlive(createIfNull, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Get the first child that is alive (`child.alive === true`). This is handy for choosing a squad leader, etc. You can use the optional argument `createIfNull` to create a new Game Object if no alive ones were found in this Group. It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `createIfNull` | boolean | <optional> | false | If `true` and no alive children are found a new one is created. | | `x` | number | <optional> | | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The alive dead child, or `null` if none found and `createIfNull` was false. Inherited From * [Phaser.Group#getFirstAlive](phaser.group#getFirstAlive) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2105](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2105)) ### getFirstDead(createIfNull, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Get the first child that is dead (`child.alive === false`). This is handy for checking if everything has been wiped out and adding to the pool as needed. You can use the optional argument `createIfNull` to create a new Game Object if no dead ones were found in this Group. It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `createIfNull` | boolean | <optional> | false | If `true` and no dead children are found a new one is created. | | `x` | number | <optional> | | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The first dead child, or `null` if none found and `createIfNull` was false. Inherited From * [Phaser.Group#getFirstDead](phaser.group#getFirstDead) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2135](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2135)) ### getFirstExists(exists, createIfNull, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Get the first display object that exists, or doesn't exist. You can use the optional argument `createIfNull` to create a new Game Object if none matching your exists argument were found in this Group. It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `exists` | boolean | <optional> | true | If true, find the first existing child; otherwise find the first non-existing child. | | `createIfNull` | boolean | <optional> | false | If `true` and no alive children are found a new one is created. | | `x` | number | <optional> | | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The first child, or `null` if none found and `createIfNull` was false. Inherited From * [Phaser.Group#getFirstExists](phaser.group#getFirstExists) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2071](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2071)) ### getFurthestFrom(object, callback, callbackContext) → {any} Get the child furthest away from the given Object, with optional callback to filter children. This can be a Sprite, Group, Image or any object with public x and y properties. 'furthest away' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. You can use the optional `callback` argument to apply your own filter to the distance checks. If the child is closer then the previous child, it will be sent to `callback` as the first argument, with the distance as the second. The callback should return `true` if it passes your filtering criteria, otherwise it should return `false`. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `object` | any | | The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. | | `callback` | function | <optional> | The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. | | `callbackContext` | object | <optional> | The context in which the function should be called (usually 'this'). | ##### Returns any - The child furthest from the given object, or `null` if no child was found. Inherited From * [Phaser.Group#getFurthestFrom](phaser.group#getFurthestFrom) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2282](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2282)) ### getIndex(child) → {integer} Get the index position of the given child in this group, which should match the child's `z` property. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to get the index for. | ##### Returns integer - The index of the child or -1 if it's not a member of this group. Inherited From * [Phaser.Group#getIndex](phaser.group#getIndex) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1029](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1029)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the displayObjectContainer as a rectangle without any transformations. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.DisplayObjectContainer#getLocalBounds](pixi.displayobjectcontainer#getLocalBounds) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 437](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L437)) ### getRandom(startIndex, length) → {any} Returns a random child from the group. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `startIndex` | integer | <optional> | 0 | Offset from the front of the group (lowest child). | | `length` | integer | <optional> | (to top) | Restriction on the number of values you want to randomly select from. | ##### Returns any - A random child of this Group. Inherited From * [Phaser.Group#getRandom](phaser.group#getRandom) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2350](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2350)) ### getRandomExists(startIndex, endIndex) → {any} Returns a random child from the Group that has `exists` set to `true`. Optionally you can specify a start and end index. For example if this Group had 100 children, and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only the first 50 children in the Group. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `startIndex` | integer | <optional> | 0 | The first child index to start the search from. | | `endIndex` | integer | <optional> | | The last child index to search up to. | ##### Returns any - A random child of this Group that exists. Inherited From * [Phaser.Group#getRandomExists](phaser.group#getRandomExists) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2372](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2372)) ### getTop() → {any} Return the child at the top of this group. The top child is the child displayed (rendered) above every other child. ##### Returns any - The child at the top of the Group. Inherited From * [Phaser.Group#getTop](phaser.group#getTop) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2204](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2204)) ### hasProperty(child, key) → {boolean} Checks if the child has the given property. Will scan up to 4 levels deep only. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to check for the existence of the property on. | | `key` | Array.<string> | An array of strings that make up the property. | ##### Returns boolean - True if the child has the property, otherwise false. Inherited From * [Phaser.Group#hasProperty](phaser.group#hasProperty) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1104](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1104)) ### iterate(key, value, returnType, callback, callbackContext, args) → {any} Iterates over the children of the group performing one of several actions for matched children. A child is considered a match when it has a property, named `key`, whose value is equal to `value` according to a strict equality comparison. The result depends on the `returnType`: * [RETURN\_TOTAL](phaser.group#.RETURN_TOTAL): The callback, if any, is applied to all matching children. The number of matched children is returned. * [RETURN\_NONE](phaser.group#.RETURN_NONE): The callback, if any, is applied to all matching children. No value is returned. * [RETURN\_CHILD](phaser.group#.RETURN_CHILD): The callback, if any, is applied to the *first* matching child and the *first* matched child is returned. If there is no matching child then null is returned. If `args` is specified it must be an array. The matched child will be assigned to the first element and the entire array will be applied to the callback function. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The child property to check, i.e. 'exists', 'alive', 'health' | | `value` | any | | | A child matches if `child[key] === value` is true. | | `returnType` | integer | | | How to iterate the children and what to return. | | `callback` | function | <optional> | null | Optional function that will be called on each matching child. The matched child is supplied as the first argument. | | `callbackContext` | object | <optional> | | The context in which the function should be called (usually 'this'). | | `args` | Array.<any> | <optional> | (none) | The arguments supplied to to the callback; the first array index (argument) will be replaced with the matched child. | ##### Returns any - Returns either an integer (for RETURN\_TOTAL), the first matched child (for RETURN\_CHILD), or null. Inherited From * [Phaser.Group#iterate](phaser.group#iterate) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1976](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1976)) ### moveAll(group, silent) → {[Phaser.Group](phaser.group)} Moves all children from this Group to the Group given. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `group` | [Phaser.Group](phaser.group) | | | The new Group to which the children will be moved to. | | `silent` | boolean | <optional> | false | If true the children will not dispatch the `onAddedToGroup` event for the new Group. | ##### Returns [Phaser.Group](phaser.group) - The Group to which all the children were moved. Inherited From * [Phaser.Group#moveAll](phaser.group#moveAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2479](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2479)) ### moveDown(child) → {any} Moves the given child down one place in this group unless it's already at the bottom. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to move down in the group. | ##### Returns any - The child that was moved. Inherited From * [Phaser.Group#moveDown](phaser.group#moveDown) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 969](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L969)) ### moveUp(child) → {any} Moves the given child up one place in this group unless it's already at the top. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to move up in the group. | ##### Returns any - The child that was moved. Inherited From * [Phaser.Group#moveUp](phaser.group#moveUp) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 945](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L945)) ### multiplyAll(property, amount, checkAlive, checkVisible) Multiplies the given property by the amount on all children in this group. `Group.multiplyAll('x', 2)` will x2 the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to multiply, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Inherited From * [Phaser.Group#multiplyAll](phaser.group#multiplyAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1420](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1420)) ### next() → {any} Advances the group cursor to the next (higher) object in the group. If the cursor is at the end of the group (top child) it is moved the start of the group (bottom child). ##### Returns any - The child the cursor now points to. Inherited From * [Phaser.Group#next](phaser.group#next) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 833](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L833)) ### <internal> postUpdate() The core postUpdate - as called by World. Inherited From * [Phaser.Group#postUpdate](phaser.group#postUpdate) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1656](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1656)) ### <internal> preUpdate() The core preUpdate - as called by World. Inherited From * [Phaser.Group#preUpdate](phaser.group#preUpdate) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1611](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1611)) ### previous() → {any} Moves the group cursor to the previous (lower) child in the group. If the cursor is at the start of the group (bottom child) it is moved to the end (top child). ##### Returns any - The child the cursor now points to. Inherited From * [Phaser.Group#previous](phaser.group#previous) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 862](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L862)) ### remove(child, destroy, silent) → {boolean} Removes the given child from this group. This will dispatch an `onRemovedFromGroup` event from the child (if it has one), and optionally destroy the child. If the group cursor was referring to the removed child it is updated to refer to the next child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | any | | | The child to remove. | | `destroy` | boolean | <optional> | false | If true `destroy` will be invoked on the removed child. | | `silent` | boolean | <optional> | false | If true the the child will not dispatch the `onRemovedFromGroup` event. | ##### Returns boolean - true if the child was removed from this group, otherwise false. Inherited From * [Phaser.Group#remove](phaser.group#remove) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2431](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2431)) ### removeAll(destroy, silent, destroyTexture) Removes all children from this Group, but does not remove the group from its parent. The children can be optionally destroyed as they are removed. You can also optionally also destroy the BaseTexture the Child is using. Be careful if you've more than one Game Object sharing the same BaseTexture. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroy` | boolean | <optional> | false | If true `destroy` will be invoked on each removed child. | | `silent` | boolean | <optional> | false | If true the children will not dispatch their `onRemovedFromGroup` events. | | `destroyTexture` | boolean | <optional> | false | If true, and if the `destroy` argument is also true, the BaseTexture belonging to the Child is also destroyed. Note that if another Game Object is sharing the same BaseTexture it will invalidate it. | Inherited From * [Phaser.Group#removeAll](phaser.group#removeAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2508](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2508)) ### removeBetween(startIndex, endIndex, destroy, silent) Removes all children from this group whose index falls beteen the given startIndex and endIndex values. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `startIndex` | integer | | | The index to start removing children from. | | `endIndex` | integer | <optional> | | The index to stop removing children at. Must be higher than startIndex. If undefined this method will remove all children between startIndex and the end of the group. | | `destroy` | boolean | <optional> | false | If true `destroy` will be invoked on each removed child. | | `silent` | boolean | <optional> | false | If true the children will not dispatch their `onRemovedFromGroup` events. | Inherited From * [Phaser.Group#removeBetween](phaser.group#removeBetween) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2556](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2556)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### removeFromHash(child) → {boolean} Removes a child of this Group from the hash array. This call will return false if the child is not in the hash. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The display object to remove from this Groups hash. Must be a member of this Group and in the hash. | ##### Returns boolean - True if the child was successfully removed from the hash, otherwise false. Inherited From * [Phaser.Group#removeFromHash](phaser.group#removeFromHash) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 464](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L464)) ### replace(oldChild, newChild) → {any} Replaces a child of this Group with the given newChild. The newChild cannot be a member of this Group. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `oldChild` | any | The child in this group that will be replaced. | | `newChild` | any | The child to be inserted into this group. | ##### Returns any - Returns the oldChild that was replaced within this group. Inherited From * [Phaser.Group#replace](phaser.group#replace) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1065](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1065)) ### resetChild(child, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Takes a child and if the `x` and `y` arguments are given it calls `child.reset(x, y)` on it. If the `key` and optionally the `frame` arguments are given, it calls `child.loadTexture(key, frame)` on it. The two operations are separate. For example if you just wish to load a new texture then pass `null` as the x and y values. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | | The child to reset and/or load the texture on. | | `x` | number | <optional> | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was reset: usually a [Phaser.Sprite](phaser.sprite). Inherited From * [Phaser.Group#resetChild](phaser.group#resetChild) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2165](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2165)) ### resetCursor(index) → {any} Sets the group cursor to the first child in the group. If the optional index parameter is given it sets the cursor to the object at that index instead. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `index` | integer | <optional> | 0 | Set the cursor to point to a specific index. | ##### Returns any - The child the cursor now points to. Inherited From * [Phaser.Group#resetCursor](phaser.group#resetCursor) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 806](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L806)) ### reverse() Reverses all children in this group. This operation applies only to immediate children and does not propagate to subgroups. Inherited From * [Phaser.Group#reverse](phaser.group#reverse) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1015](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1015)) ### sendToBack(child) → {any} Sends the given child to the bottom of this group so it renders below all other children. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to send to the bottom of this group. | ##### Returns any - The child that was moved. Inherited From * [Phaser.Group#sendToBack](phaser.group#sendToBack) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 926](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L926)) ### set(child, key, value, checkAlive, checkVisible, operation, force) → {boolean} Quickly set a property on a single child of this group to a new value. The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | [Phaser.Sprite](phaser.sprite) | | | The child to set the property on. | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be set. | | `checkAlive` | boolean | <optional> | false | If set then the child will only be updated if alive=true. | | `checkVisible` | boolean | <optional> | false | If set then the child will only be updated if visible=true. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | ##### Returns boolean - True if the property was set, false if not. Inherited From * [Phaser.Group#set](phaser.group#set) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1246](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1246)) ### setAll(key, value, checkAlive, checkVisible, operation, force) Quickly set the same property across all children of this group to a new value. This call doesn't descend down children, so if you have a Group inside of this group, the property will be set on the group but not its children. If you need that ability please see `Group.setAllChildren`. The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be set. | | `checkAlive` | boolean | <optional> | false | If set then only children with alive=true will be updated. This includes any Groups that are children. | | `checkVisible` | boolean | <optional> | false | If set then only children with visible=true will be updated. This includes any Groups that are children. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | Inherited From * [Phaser.Group#setAll](phaser.group#setAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1277](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1277)) ### setAllChildren(key, value, checkAlive, checkVisible, operation, force) Quickly set the same property across all children of this group, and any child Groups, to a new value. If this group contains other Groups then the same property is set across their children as well, iterating down until it reaches the bottom. Unlike with `setAll` the property is NOT set on child Groups itself. The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be set. | | `checkAlive` | boolean | <optional> | false | If set then only children with alive=true will be updated. This includes any Groups that are children. | | `checkVisible` | boolean | <optional> | false | If set then only children with visible=true will be updated. This includes any Groups that are children. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | Inherited From * [Phaser.Group#setAllChildren](phaser.group#setAllChildren) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1312](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1312)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### setProperty(child, key, value, operation, force) → {boolean} Sets a property to the given value on the child. The operation parameter controls how the value is set. The operations are: * 0: set the existing value to the given value; if force is `true` a new property will be created if needed * 1: will add the given value to the value already present. * 2: will subtract the given value from the value already present. * 3: will multiply the value already present by the given value. * 4: will divide the value already present by the given value. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | any | | | The child to set the property value on. | | `key` | array | | | An array of strings that make up the property that will be set. | | `value` | any | | | The value that will be set. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | ##### Returns boolean - True if the property was set, false if not. Inherited From * [Phaser.Group#setProperty](phaser.group#setProperty) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1139](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1139)) ### sort(key, order) Sort the children in the group according to a particular key and ordering. Call this function to sort the group according to a particular key value and order. For example to depth sort Sprites for Zelda-style game you might call `group.sort('y', Phaser.Group.SORT_ASCENDING)` at the bottom of your `State.update()`. Internally this uses a standard JavaScript Array sort, so everything that applies there also applies here, including alphabetical sorting, mixing strings and numbers, and Unicode sorting. See MDN for more details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | <optional> | 'z' | The name of the property to sort on. Defaults to the objects z-depth value. | | `order` | integer | <optional> | Phaser.Group.SORT\_ASCENDING | Order ascending ([SORT\_ASCENDING](phaser.group#.SORT_ASCENDING)) or descending ([SORT\_DESCENDING](phaser.group#.SORT_DESCENDING)). | Inherited From * [Phaser.Group#sort](phaser.group#sort) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1855](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1855)) ### subAll(property, amount, checkAlive, checkVisible) Subtracts the amount from the given property on all children in this group. `Group.subAll('x', 10)` will minus 10 from the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to decrement, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Inherited From * [Phaser.Group#subAll](phaser.group#subAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1403](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1403)) ### swap(child1, child2) Swaps the position of two children in this group. Both children must be in this group, a child cannot be swapped with itself, and unparented children cannot be swapped. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child1` | any | The first child to swap. | | `child2` | any | The second child to swap. | Inherited From * [Phaser.Group#swap](phaser.group#swap) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 891](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L891)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) ### <internal> update() The core update - as called by World. Inherited From * [Phaser.Group#update](phaser.group#update) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1639](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1639)) ### <internal> updateZ() Internal method that re-applies all of the children's Z values. This must be called whenever children ordering is altered so that their `z` indices are correctly updated. Inherited From * [Phaser.Group#updateZ](phaser.group#updateZ) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 663](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L663)) ### xy(index, x, y) Positions the child found at the given index within this group to the given x and y coordinates. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | integer | The index of the child in the group to set the position of. | | `x` | number | The new x position of the child. | | `y` | number | The new y position of the child. | Inherited From * [Phaser.Group#xy](phaser.group#xy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 993](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L993))
programming_docs
phaser Class: Phaser.Component.Reset Class: Phaser.Component.Reset ============================= Constructor ----------- ### new Reset() The Reset component allows a Game Object to be reset and repositioned to a new location. Source code: [gameobjects/components/Reset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Reset.js) ([Line 12](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Reset.js#L12)) Public Methods -------------- ### reset(x, y, health) → {PIXI.DisplayObject} Resets the Game Object. This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`, `visible` and `renderable` to true. If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value. If this Game Object has a Physics Body it will reset the Body. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate (in world space) to position the Game Object at. | | `y` | number | | | The y coordinate (in world space) to position the Game Object at. | | `health` | number | <optional> | 1 | The health to give the Game Object if it has the Health component. | ##### Returns PIXI.DisplayObject - This instance. Source code: [gameobjects/components/Reset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Reset.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Reset.js#L30)) phaser Class: Phaser.Component.BringToTop Class: Phaser.Component.BringToTop ================================== Constructor ----------- ### new BringToTop() The BringToTop Component features quick access to Group sorting related methods. Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 12](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L12)) Public Methods -------------- ### bringToTop() → {PIXI.DisplayObject} Brings this Game Object to the top of its parents display list. Visually this means it will render over the top of any old child in the same Group. If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L24)) ### moveDown() → {PIXI.DisplayObject} Moves this Game Object down one place in its parents display list. This call has no effect if the Game Object is already at the bottom of the display list. If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L87)) ### moveUp() → {PIXI.DisplayObject} Moves this Game Object up one place in its parents display list. This call has no effect if the Game Object is already at the top of the display list. If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 66](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L66)) ### sendToBack() → {PIXI.DisplayObject} Sends this Game Object to the bottom of its parents display list. Visually this means it will render below all other children in the same Group. If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L45)) phaser Class: Phaser.Component.InputEnabled Class: Phaser.Component.InputEnabled ==================================== Constructor ----------- ### new InputEnabled() The InputEnabled component allows a Game Object to have its own InputHandler and process input related events. Source code: [gameobjects/components/InputEnabled.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js) ([Line 12](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js#L12)) Public Properties ----------------- ### input : [Phaser.InputHandler](phaser.inputhandler) | null The Input Handler for this Game Object. By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`. After you have done this, this property will be a reference to the Phaser InputHandler. ##### Type * [Phaser.InputHandler](phaser.inputhandler) | null Source code: [gameobjects/components/InputEnabled.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js#L24)) ### inputEnabled : boolean By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created for this Game Object and it will then start to process click / touch events and more. You can then access the Input Handler via `this.input`. Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`. If you set this property to false it will stop the Input Handler from processing any more input events. If you want to *temporarily* disable input for a Game Object, then it's better to set `input.enabled = false`, as it won't reset any of the Input Handlers internal properties. You can then toggle this back on as needed. Source code: [gameobjects/components/InputEnabled.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js#L42)) phaser Class: Phaser.Loader Class: Phaser.Loader ==================== Constructor ----------- ### new Loader(game) The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. The loader uses a combination of tag loading (eg. Image elements) and XHR and provides progress and completion callbacks. Parallel loading (see [enableParallel](phaser.loader#enableParallel)) is supported and enabled by default. Load-before behavior of parallel resources is controlled by synchronization points as discussed in withSyncPoint. Texture Atlases can be created with tools such as [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) and [Shoebox](http://renderhjs.net/shoebox/) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L22)) Public Properties ----------------- ### [static] PHYSICS\_LIME\_CORONA\_JSON : number Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 322](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L322)) ### [static] PHYSICS\_PHASER\_JSON : number Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 328](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L328)) ### [static] TEXTURE\_ATLAS\_JSON\_ARRAY : number Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 304](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L304)) ### [static] TEXTURE\_ATLAS\_JSON\_HASH : number Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 310](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L310)) ### [static] TEXTURE\_ATLAS\_JSON\_PYXEL : number Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 334](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L334)) ### [static] TEXTURE\_ATLAS\_XML\_STARLING : number Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 316](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L316)) ### \_withSyncPointDepth A counter: if more than zero, files will be automatically added as a synchronization point. ##### Properties: | Name | Type | Description | | --- | --- | --- | | `_withSyncPointDepth;` | integer | | Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 227](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L227)) ### baseURL : string If you want to append a URL before the path of any asset you can set this here. Useful if allowing the asset base url to be configured outside of the game code. The string *must* end with a "/". Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 83](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L83)) ### <internal> cache : [Phaser.Cache](phaser.cache) Local reference to the Phaser.Cache. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 36](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L36)) ### crossOrigin : boolean | string The crossOrigin value applied to loaded images. Very often this needs to be set to 'anonymous'. ##### Type * boolean | string Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 74](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L74)) ### enableParallel : boolean If true (the default) then parallel downloading will be enabled. To disable all parallel downloads this must be set to false prior to any resource being loaded. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 211](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L211)) ### <internal> game : [Phaser.Game](phaser.game) Local reference to game. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L29)) ### hasLoaded : boolean True if all assets in the queue have finished loading. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 57](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L57)) ### headers : Object Used to map the application mime-types to to the Accept header in XHR requests. If you don't require these mappings, or they cause problems on your server, then remove them from the headers object and the XHR request will not try to use them. This object can also be used to set the `X-Requested-With` header to `XMLHttpRequest` (or any other value you need). To enable this do: `this.load.headers.requestedWith = 'XMLHttpRequest'` before adding anything to the Loader. The XHR loader will then call: `setRequestHeader('X-Requested-With', this.headers['requestedWith'])` Default Value * {"undefined":"application/xml"} Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 122](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L122)) ### isLoading : boolean True if the Loader is in the process of loading the queue. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L50)) ### <internal> maxParallelDownloads : integer The number of concurrent / parallel resources to try and fetch at once. Many current browsers limit 6 requests per domain; this is slightly conservative. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 221](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L221)) ### onFileComplete : [Phaser.Signal](phaser.signal) This event is dispatched when a file has either loaded or failed to load. Any function bound to this will receive the following parameters: progress, file key, success?, total loaded files, total files Where progress is a number between 1 and 100 (inclusive) representing the percentage of the load. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 175](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L175)) ### onFileError : [Phaser.Signal](phaser.signal) This event is dispatched when a file (or pack) errors as a result of the load request. For files it will be triggered before `onFileComplete`. For packs it will be triggered before `onPackComplete`. Params: `(file key, file)` Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 186](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L186)) ### onFileStart : [Phaser.Signal](phaser.signal) This event is dispatched immediately before a file starts loading. It's possible the file may fail (eg. download error, invalid format) after this event is sent. Params: `(progress, file key, file url)` Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 162](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L162)) ### onLoadComplete : [Phaser.Signal](phaser.signal) This event is dispatched when the final file in the load queue has either loaded or failed. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 141](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L141)) ### onLoadStart : [Phaser.Signal](phaser.signal) This event is dispatched when the loading process starts: before the first file has been requested, but after all the initial packs have been loaded. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 134](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L134)) ### onPackComplete : [Phaser.Signal](phaser.signal) This event is dispatched when an asset pack has either loaded or failed to load. This is called when the asset pack manifest file has loaded and successfully added its contents to the loader queue. Params: `(pack key, success?, total packs loaded, total packs)` Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 152](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L152)) ### path : string The value of `path`, if set, is placed before any *relative* file path given. For example: `load.path = "images/sprites/"; load.image("ball", "ball.png"); load.image("tree", "level1/oaktree.png"); load.image("boom", "http://server.com/explode.png");` Would load the `ball` file from `images/sprites/ball.png` and the tree from `images/sprites/level1/oaktree.png` but the file `boom` would load from the URL given as it's an absolute URL. Please note that the path is added before the filename but *after* the baseURL (if set.) The string *must* end with a "/". Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 103](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L103)) ### <internal> preloadSprite : Object You can optionally link a progress sprite with [setPreloadSprite](phaser.loader#setPreloadSprite). This property is an object containing: sprite, rect, direction, width and height Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 67](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L67)) ### progress The rounded load progress percentage value (from 0 to 100). See [Phaser.Loader#progressFloat](phaser.loader#progressFloat). ##### Properties: | Type | Description | | --- | --- | | integer | | Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 3060](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L3060)) ### progressFloat The non-rounded load progress value (from 0.0 to 100.0). A general indicator of the progress. It is possible for the progress to decrease, after `onLoadStart`, if more files are dynamically added. ##### Properties: | Type | Description | | --- | --- | | number | | Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 3042](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L3042)) ### resetLocked : boolean If true all calls to Loader.reset will be ignored. Useful if you need to create a load queue before swapping to a preloader state. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 43](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L43)) ### useXDomainRequest : boolean This method is *deprecated* and should not be used. It may be removed in the future. If true and if the browser supports XDomainRequest, it will be used in preference for XHR. This is only relevant for IE 9 and should *only* be enabled for IE 9 clients when required by the server/CDN. Deprecated: * This is only relevant for IE 9. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 196](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L196)) Public Methods -------------- ### addSyncPoint(type, key) → {[Phaser.Loader](phaser.loader)} Add a synchronization point to a specific file/asset in the load queue. This has no effect on already loaded assets. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `type` | string | The type of resource to turn into a sync point (image, audio, xml, etc). | | `key` | string | Key of the file you want to turn into a sync point. | ##### Returns [Phaser.Loader](phaser.loader) - This Loader instance. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 1675](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L1675)) See * withSyncPoint ### <internal> addToFileList(type, key, url, properties, overwrite, extension) → {[Phaser.Loader](phaser.loader)} Internal function that adds a new entry to the file list. Do not call directly. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `type` | string | | | The type of resource to add to the list (image, audio, xml, etc). | | `key` | string | | | The unique Cache ID key of this resource. | | `url` | string | <optional> | | The URL the asset will be loaded from. | | `properties` | object | <optional> | (none) | Any additional properties needed to load the file. These are added directly to the added file object and overwrite any defaults. | | `overwrite` | boolean | <optional> | false | If true then this will overwrite a file asset of the same type/key. Otherwise it will only add a new asset. If overwrite is true, and the asset is already being loaded (or has been loaded), then it is appended instead. | | `extension` | string | <optional> | | If no URL is given the Loader will sometimes auto-generate the URL based on the key, using this as the extension. | ##### Returns [Phaser.Loader](phaser.loader) - This instance of the Phaser Loader. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 515](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L515)) ### atlas(key, textureURL, atlasURL, atlasData, format) → {[Phaser.Loader](phaser.loader)} Adds a Texture Atlas file to the current load queue. To create the Texture Atlas you can use tools such as: [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) [Shoebox](http://renderhjs.net/shoebox/) If using Texture Packer we recommend you enable "Trim sprite names". If your atlas software has an option to "rotate" the resulting frames, you must disable it. You can choose to either load the data externally, by providing a URL to a json file. Or you can pass in a JSON object or String via the `atlasData` parameter. If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. If the textureURL isn't specified then the Loader will take the key and create a filename from that. For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". If you do not desire this action then provide URLs and / or a data object. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `key` | string | | Unique asset key of the texture atlas file. | | `textureURL` | string | <optional> | URL of the texture atlas image file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png". | | `atlasURL` | string | <optional> | URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json". | | `atlasData` | object | <optional> | A JSON or XML data object. You don't need this if the data is being loaded from a URL. | | `format` | number | <optional> | The format of the data. Can be Phaser.Loader.TEXTURE\_ATLAS\_JSON\_ARRAY (the default), Phaser.Loader.TEXTURE\_ATLAS\_JSON\_HASH or Phaser.Loader.TEXTURE\_ATLAS\_XML\_STARLING. | ##### Returns [Phaser.Loader](phaser.loader) - This Loader instance. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 1544](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L1544)) ### atlasJSONArray(key, textureURL, atlasURL, atlasData) → {[Phaser.Loader](phaser.loader)} Adds a Texture Atlas file to the current load queue. Unlike `Loader.atlasJSONHash` this call expects the atlas data to be in a JSON Array format. To create the Texture Atlas you can use tools such as: [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) [Shoebox](http://renderhjs.net/shoebox/) If using Texture Packer we recommend you enable "Trim sprite names". If your atlas software has an option to "rotate" the resulting frames, you must disable it. You can choose to either load the data externally, by providing a URL to a json file. Or you can pass in a JSON object or String via the `atlasData` parameter. If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. If the textureURL isn't specified then the Loader will take the key and create a filename from that. For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". If you do not desire this action then provide URLs and / or a data object. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `key` | string | | Unique asset key of the texture atlas file. | | `textureURL` | string | <optional> | URL of the texture atlas image file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png". | | `atlasURL` | string | <optional> | URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json". | | `atlasData` | object | <optional> | A JSON data object. You don't need this if the data is being loaded from a URL. | ##### Returns [Phaser.Loader](phaser.loader) - This Loader instance. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 1398](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L1398)) ### atlasJSONHash(key, textureURL, atlasURL, atlasData) → {[Phaser.Loader](phaser.loader)} Adds a Texture Atlas file to the current load queue. Unlike `Loader.atlas` this call expects the atlas data to be in a JSON Hash format. To create the Texture Atlas you can use tools such as: [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) [Shoebox](http://renderhjs.net/shoebox/) If using Texture Packer we recommend you enable "Trim sprite names". If your atlas software has an option to "rotate" the resulting frames, you must disable it. You can choose to either load the data externally, by providing a URL to a json file. Or you can pass in a JSON object or String via the `atlasData` parameter. If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. If the textureURL isn't specified then the Loader will take the key and create a filename from that. For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". If you do not desire this action then provide URLs and / or a data object. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `key` | string | | Unique asset key of the texture atlas file. | | `textureURL` | string | <optional> | URL of the texture atlas image file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png". | | `atlasURL` | string | <optional> | URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json". | | `atlasData` | object | <optional> | A JSON data object. You don't need this if the data is being loaded from a URL. | ##### Returns [Phaser.Loader](phaser.loader) - This Loader instance. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 1444](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L1444)) ### atlasXML(key, textureURL, atlasURL, atlasData) → {[Phaser.Loader](phaser.loader)} Adds a Texture Atlas file to the current load queue. This call expects the atlas data to be in the Starling XML data format. To create the Texture Atlas you can use tools such as: [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) [Shoebox](http://renderhjs.net/shoebox/) If using Texture Packer we recommend you enable "Trim sprite names". If your atlas software has an option to "rotate" the resulting frames, you must disable it. You can choose to either load the data externally, by providing a URL to an xml file. Or you can pass in an XML object or String via the `atlasData` parameter. If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache. If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. Retrieve the file via `Cache.getImage(key)`. XML files are automatically parsed upon load. If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed. The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. If the textureURL isn't specified then the Loader will take the key and create a filename from that. For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.xml". If you do not desire this action then provide URLs and / or a data object. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `key` | string | | Unique asset key of the texture atlas file. | | `textureURL` | string | <optional> | URL of the texture atlas image file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png". | | `atlasURL` | string | <optional> | URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.xml". | | `atlasData` | object | <optional> | An XML data object. You don't need this if the data is being loaded from a URL. | ##### Returns [Phaser.Loader](phaser.loader) - This Loader instance. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 1490](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L1490)) ### audio(key, urls, autoDecode) → {[Phaser.Loader](phaser.loader)} Adds an audio file to the current load queue. The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. Retrieve the file via `Cache.getSound(key)`. The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio. When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system. The solution is to use a lower encoding rate such as 44100 Hz. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Unique asset key of the audio file. | | `urls` | string | Array.<string> | Array.<object> | | | Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`. If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected. For example: `"jump.mp3"`, `['jump.mp3', 'jump.ogg', 'jump.m4a']`, or `[{uri: "data:<opus_resource>", type: 'opus'}, 'fallback.mp3']`. BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource. | | `autoDecode` | boolean | <optional> | true | When using Web Audio the audio files can either be decoded at load time or run-time. Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. | ##### Returns [Phaser.Loader](phaser.loader) - This Loader instance. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 991](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L991)) ### audioSprite(key, urls, jsonURL, jsonData, autoDecode) → {[Phaser.Loader](phaser.loader)} Adds an audio sprite file to the current load queue. The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. Audio Sprites are a combination of audio files and a JSON configuration. The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite Retrieve the file via `Cache.getSoundData(key)`. The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Unique asset key of the audio file. | | `urls` | Array | string | | | An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL. | | `jsonURL` | string | <optional> | null | The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null. | | `jsonData` | string | object | <optional> | null | A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null. | | `autoDecode` | boolean | <optional> | true | When using Web Audio the audio files can either be decoded at load time or run-time. Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. | ##### Returns [Phaser.Loader](phaser.loader) - This Loader instance. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 1034](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L1034)) ### audiosprite(key, urls, jsonURL, jsonData, autoDecode) → {[Phaser.Loader](phaser.loader)} A legacy alias for Loader.audioSprite. Please see that method for documentation. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Unique asset key of the audio file. | | `urls` | Array | string | | | An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL. | | `jsonURL` | string | <optional> | null | The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null. | | `jsonData` | string | object | <optional> | null | A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null. | | `autoDecode` | boolean | <optional> | true | When using Web Audio the audio files can either be decoded at load time or run-time. Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. | ##### Returns [Phaser.Loader](phaser.loader) - This Loader instance. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 1093](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L1093)) ### binary(key, url, callback, callbackContext) → {[Phaser.Loader](phaser.loader)} Adds a binary file to the current load queue. The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. Retrieve the file via `Cache.getBinary(key)`. The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" and no URL is given then the Loader will set the URL to be "alien.bin". It will always add `.bin` as the extension. If you do not desire this action then provide a URL. It will be loaded via xhr with a responseType of "arraybuffer". You can specify an optional callback to process the file after load. When the callback is called it will be passed 2 parameters: the key of the file and the file data. WARNING: If a callback is specified the data will be set to whatever it returns. Always return the data object, even if you didn't modify it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Unique asset key of the binary file. | | `url` | string | <optional> | | URL of the binary file. If undefined or `null` the url will be set to `<key>.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin". | | `callback` | function | <optional> | (none) | Optional callback that will be passed the file after loading, so you can perform additional processing on it. | | `callbackContext` | object | <optional> | | The context under which the callback will be applied. If not specified it will use the callback itself as the context. | ##### Returns [Phaser.Loader](phaser.loader) - This Loader instance. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 911](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L911)) ### bitmapFont(key, textureURL, atlasURL, atlasData, xSpacing, ySpacing) → {[Phaser.Loader](phaser.loader)} Adds Bitmap Font files to the current load queue. To create the Bitmap Font files you can use: BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner Littera (Web-based, free): http://kvazars.com/littera/ You can choose to either load the data externally, by providing a URL to an xml file. Or you can pass in an XML object or String via the `xmlData` parameter. If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache. If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. Retrieve the file via `Cache.getBitmapFont(key)`. XML files are automatically parsed upon load. If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed. The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. If the textureURL isn't specified then the Loader will take the key and create a filename from that. For example if the key is "megaFont" and textureURL is null then the Loader will set the URL to be "megaFont.png". The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will set the atlasURL to be the key. For example if the key is "megaFont" the atlasURL will be set to "megaFont.xml". If you do not desire this action then provide URLs and / or a data object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Unique asset key of the bitmap font. | | `textureURL` | string | | | URL of the Bitmap Font texture file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "megaFont" then the URL will be "megaFont.png". | | `atlasURL` | string | | | URL of the Bitmap Font atlas file (xml/json). If undefined or `null` AND `atlasData` is null, the url will be set to `<key>.xml`, i.e. if `key` was "megaFont" then the URL will be "megaFont.xml". | | `atlasData` | object | | | An optional Bitmap Font atlas in string form (stringified xml/json). | | `xSpacing` | number | <optional> | 0 | If you'd like to add additional horizontal spacing between the characters then set the pixel value here. | | `ySpacing` | number | <optional> | 0 | If you'd like to add additional vertical spacing between the lines then set the pixel value here. | ##### Returns [Phaser.Loader](phaser.loader) - This Loader instance. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 1307](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L1307)) ### checkKeyExists(type, key) → {boolean} Check whether a file/asset with a specific key is queued to be loaded. To access a loaded asset use Phaser.Cache, eg. [Phaser.Cache#checkImageKey](phaser.cache#checkImageKey) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `type` | string | The type asset you want to check. | | `key` | string | Key of the asset you want to check. | ##### Returns boolean - Return true if exists, otherwise return false. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 390](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L390)) ### getAsset(type, key) → {any} Find a file/asset with a specific key. Only assets in the download file queue will be found. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `type` | string | The type asset you want to check. | | `key` | string | Key of the asset you want to check. | ##### Returns any - Returns an object if found that has 2 properties: `index` and `file`; otherwise a non-true value is returned. The index may change and should only be used immediately following this call. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 441](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L441)) ### getAssetIndex(type, key) → {number} Get the queue-index of the file/asset with a specific key. Only assets in the download file queue will be found. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `type` | string | The type asset you want to check. | | `key` | string | Key of the asset you want to check. | ##### Returns number - The index of this key in the filelist, or -1 if not found. The index may change and should only be used immediately following this call Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 406](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L406)) ### image(key, url, overwrite) → {[Phaser.Loader](phaser.loader)} Adds an Image to the current load queue. The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. Retrieve the image via `Cache.getImage(key)` The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. If you do not desire this action then provide a URL. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Unique asset key of this image file. | | `url` | string | <optional> | | URL of an image file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png". | | `overwrite` | boolean | <optional> | false | If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. | ##### Returns [Phaser.Loader](phaser.loader) - This Loader instance. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 693](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L693)) ### images(keys, urls) → {[Phaser.Loader](phaser.loader)} Adds an array of images to the current load queue. It works by passing each element of the array to the Loader.image method. The files are **not** loaded immediately after calling this method. The files are added to the queue ready to be loaded when the loader starts. Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. The keys must be unique Strings. They are used to add the files to the Phaser.Cache upon successful load. Retrieve the images via `Cache.getImage(key)` The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. If you do not desire this action then provide a URL. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `keys` | array | | An array of unique asset keys of the image files. | | `urls` | array | <optional> | Optional array of URLs. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png". If provided the URLs array length must match the keys array length. | ##### Returns [Phaser.Loader](phaser.loader) - This Loader instance. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 722](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L722)) ### json(key, url, overwrite) → {[Phaser.Loader](phaser.loader)} Adds a JSON file to the current load queue. The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load. If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" and no URL is given then the Loader will set the URL to be "alien.json". It will always add `.json` as the extension. If you do not desire this action then provide a URL. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Unique asset key of the json file. | | `url` | string | <optional> | | URL of the JSON file. If undefined or `null` the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json". | | `overwrite` | boolean | <optional> | false | If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. | ##### Returns [Phaser.Loader](phaser.loader) - This Loader instance. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 794](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L794)) ### pack(key, url, data, callbackContext) → {[Phaser.Loader](phaser.loader)} Add a JSON resource pack ('packfile') to the Loader. A packfile is a JSON file that contains a list of assets to the be loaded. Please see the example 'loader/asset pack' in the Phaser Examples repository. Packs are always put before the first non-pack file that is not loaded / loading. This means that all packs added before any loading has started are added to the front of the file queue, in the order added. The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. The URL of the packfile can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Unique asset key of this resource pack. | | `url` | string | <optional> | | URL of the Asset Pack JSON file. If you wish to pass a json object instead set this to null and pass the object as the data parameter. | | `data` | object | <optional> | | The Asset Pack JSON data. Use this to pass in a json data object rather than loading it from a URL. TODO | | `callbackContext` | object | <optional> | (loader) | Some Loader operations, like Binary and Script require a context for their callbacks. Pass the context here. | ##### Returns [Phaser.Loader](phaser.loader) - This Loader instance. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 613](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L613)) ### physics(key, url, data, format) → {[Phaser.Loader](phaser.loader)} Adds a physics data file to the current load queue. The data must be in `Lime + Corona` JSON format. [Physics Editor](https://www.codeandweb.com) by code'n'web exports in this format natively. You can choose to either load the data externally, by providing a URL to a json file. Or you can pass in a JSON object or String via the `data` parameter. If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue. The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load. If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that. For example if the key is "alien" and no URL or data is given then the Loader will set the URL to be "alien.json". It will always use `.json` as the extension. If you do not desire this action then provide a URL or data object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Unique asset key of the physics json data. | | `url` | string | <optional> | | URL of the physics data file. If undefined or `null` and no data is given the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json". | | `data` | object | string | <optional> | | An optional JSON data object. If given then the url is ignored and this JSON object is used for physics data instead. | | `format` | string | <optional> | Phaser.Physics.LIME\_CORONA\_JSON | The format of the physics data. | ##### Returns [Phaser.Loader](phaser.loader) - This Loader instance. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 1246](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L1246)) ### <internal> removeAll() Remove all file loading requests - this is *insufficient* to stop current loading. Use `reset` instead. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 1722](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L1722)) ### <internal> removeFile(type, key) Remove a file/asset from the loading queue. A file that is loaded or has started loading cannot be removed. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `type` | string | The type of resource to add to the list (image, audio, xml, etc). | | `key` | string | Key of the file you want to remove. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 1698](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L1698)) ### <internal> replaceInFileList(type, key, url, properties) Internal function that replaces an existing entry in the file list with a new one. Do not call directly. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `type` | string | The type of resource to add to the list (image, audio, xml, etc). | | `key` | string | The unique Cache ID key of this resource. | | `url` | string | The URL the asset will be loaded from. | | `properties` | object | Any additional properties needed to load the file. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 597](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L597)) ### <internal> reset(hard, clearEvents) Reset the loader and clear any queued assets. If `Loader.resetLocked` is true this operation will abort. This will abort any loading and clear any queued assets. Optionally you can clear any associated events. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `hard` | boolean | <optional> | false | If true then the preload sprite and other artifacts may also be cleared. | | `clearEvents` | boolean | <optional> | false | If true then the all Loader signals will have removeAll called on them. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 465](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L465)) ### <internal> resize() Called automatically by ScaleManager when the game resizes in RESIZE scalemode. This can be used to adjust the preloading sprite size, eg. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 373](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L373)) ### script(key, url, callback, callbackContext) → {[Phaser.Loader](phaser.loader)} Adds a JavaScript file to the current load queue. The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. The key must be a unique String. The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" and no URL is given then the Loader will set the URL to be "alien.js". It will always add `.js` as the extension. If you do not desire this action then provide a URL. Upon successful load the JavaScript is automatically turned into a script tag and executed, so be careful what you load! A callback, which will be invoked as the script tag has been created, can also be specified. The callback must return relevant `data`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Unique asset key of the script file. | | `url` | string | <optional> | | URL of the JavaScript file. If undefined or `null` the url will be set to `<key>.js`, i.e. if `key` was "alien" then the URL will be "alien.js". | | `callback` | function | <optional> | (none) | Optional callback that will be called after the script tag has loaded, so you can perform additional processing. | | `callbackContext` | object | <optional> | (loader) | The context under which the callback will be applied. If not specified it will use the Phaser Loader as the context. | ##### Returns [Phaser.Loader](phaser.loader) - This Loader instance. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 876](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L876)) ### setPreloadSprite(sprite, direction) Set a Sprite to be a "preload" sprite by passing it to this method. A "preload" sprite will have its width or height crop adjusted based on the percentage of the loader in real-time. This allows you to easily make loading bars for games. The sprite will automatically be made visible when calling this. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `sprite` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | | | The sprite or image that will be cropped during the load. | | `direction` | number | <optional> | 0 | A value of zero means the sprite will be cropped horizontally, a value of 1 means its will be cropped vertically. | Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 338](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L338)) ### shader(key, url, overwrite) → {[Phaser.Loader](phaser.loader)} Adds a fragment shader file to the current load queue. The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. Retrieve the file via `Cache.getShader(key)`. The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "blur" and no URL is given then the Loader will set the URL to be "blur.frag". It will always add `.frag` as the extension. If you do not desire this action then provide a URL. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Unique asset key of the fragment file. | | `url` | string | <optional> | | URL of the fragment file. If undefined or `null` the url will be set to `<key>.frag`, i.e. if `key` was "blur" then the URL will be "blur.frag". | | `overwrite` | boolean | <optional> | false | If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. | ##### Returns [Phaser.Loader](phaser.loader) - This Loader instance. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 822](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L822)) ### spritesheet(key, url, frameWidth, frameHeight, frameMax, margin, spacing) → {[Phaser.Loader](phaser.loader)} Adds a Sprite Sheet to the current load queue. The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. To clarify the terminology that Phaser uses: A Sprite Sheet is an image containing frames, usually of an animation, that are all equal dimensions and often in sequence. For example if the frame size is 32x32 then every frame in the sprite sheet will be that size. Sometimes (outside of Phaser) the term "sprite sheet" is used to refer to a texture atlas. A Texture Atlas works by packing together images as best it can, using whatever frame sizes it likes, often with cropping and trimming the frames in the process. Software such as Texture Packer, Flash CC or Shoebox all generate texture atlases, not sprite sheets. If you've got an atlas then use `Loader.atlas` instead. The key must be a unique String. It is used to add the image to the Phaser.Cache upon successful load. Retrieve the file via `Cache.getImage(key)`. Sprite sheets, being image based, live in the same Cache as all other Images. The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. If you do not desire this action then provide a URL. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Unique asset key of the sheet file. | | `url` | string | | | URL of the sprite sheet file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png". | | `frameWidth` | number | | | Width in pixels of a single frame in the sprite sheet. | | `frameHeight` | number | | | Height in pixels of a single frame in the sprite sheet. | | `frameMax` | number | <optional> | -1 | How many frames in this sprite sheet. If not specified it will divide the whole image into frames. | | `margin` | number | <optional> | 0 | If the frames have been drawn with a margin, specify the amount here. | | `spacing` | number | <optional> | 0 | If the frames have been drawn with spacing between them, specify the amount here. | ##### Returns [Phaser.Loader](phaser.loader) - This Loader instance. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 949](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L949)) ### start() Start loading the assets. Normally you don't need to call this yourself as the StateManager will do so. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 1735](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L1735)) ### text(key, url, overwrite) → {[Phaser.Loader](phaser.loader)} Adds a Text file to the current load queue. The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. Retrieve the file via `Cache.getText(key)` The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" and no URL is given then the Loader will set the URL to be "alien.txt". It will always add `.txt` as the extension. If you do not desire this action then provide a URL. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Unique asset key of the text file. | | `url` | string | <optional> | | URL of the text file. If undefined or `null` the url will be set to `<key>.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". | | `overwrite` | boolean | <optional> | false | If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. | ##### Returns [Phaser.Loader](phaser.loader) - This Loader instance. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 767](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L767)) ### tilemap(key, url, data, format) → {[Phaser.Loader](phaser.loader)} Adds a Tile Map data file to the current load queue. Phaser can load data in two different formats: CSV and Tiled JSON. Tiled is a free software package, specifically for creating tilemaps, and is available from http://www.mapeditor.org You can choose to either load the data externally, by providing a URL to a json file. Or you can pass in a JSON object or String via the `data` parameter. If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue. The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. Retrieve the file via `Cache.getTilemapData(key)`. JSON files are automatically parsed upon load. If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that. For example if the key is "level1" and no URL or data is given then the Loader will set the URL to be "level1.json". If you set the format to be Tilemap.CSV it will set the URL to be "level1.csv" instead. If you do not desire this action then provide a URL or data object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Unique asset key of the tilemap data. | | `url` | string | <optional> | | URL of the tile map file. If undefined or `null` and no data is given the url will be set to `<key>.json`, i.e. if `key` was "level1" then the URL will be "level1.json". | | `data` | object | string | <optional> | | An optional JSON data object. If given then the url is ignored and this JSON object is used for map data instead. | | `format` | number | <optional> | Phaser.Tilemap.CSV | The format of the map data. Either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED\_JSON. | ##### Returns [Phaser.Loader](phaser.loader) - This Loader instance. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 1165](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L1165)) ### <internal> totalLoadedFiles() → {number} Returns the number of files that have already been loaded, even if they errored. ##### Returns number - The number of files that have already been loaded (even if they errored) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 2988](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L2988)) ### <internal> totalLoadedPacks() → {number} Returns the number of asset packs that have already been loaded, even if they errored. ##### Returns number - The number of asset packs that have already been loaded (even if they errored) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 3014](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L3014)) ### <internal> totalQueuedFiles() → {number} Returns the number of files still waiting to be processed in the load queue. This value decreases as each file in the queue is loaded. ##### Returns number - The number of files that still remain in the load queue. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 3001](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L3001)) ### <internal> totalQueuedPacks() → {number} Returns the number of asset packs still waiting to be processed in the load queue. This value decreases as each pack in the queue is loaded. ##### Returns number - The number of asset packs that still remain in the load queue. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 3027](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L3027)) ### <internal> transformUrl(url, file) → {string} Transforms the asset URL. The default implementation prepends the baseURL if the url doesn't begin with http or // ##### Parameters | Name | Type | Description | | --- | --- | --- | | `url` | string | The url to transform. | | `file` | object | The file object being transformed. | ##### Returns string - The transformed url. In rare cases where the url isn't specified it will return false instead. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 2063](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L2063)) ### video(key, urls, loadEvent, asBlob) → {[Phaser.Loader](phaser.loader)} Adds a video file to the current load queue. The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. Retrieve the file via `Cache.getVideo(key)`. The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. You don't need to preload a video in order to play it in your game. See `Video.createVideoFromURL` for details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Unique asset key of the video file. | | `urls` | string | Array.<string> | Array.<object> | | | Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`. If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected. For example: `"boom.mp4"`, `['boom.mp4', 'boom.ogg', 'boom.webm']`, or `[{uri: "data:<opus_resource>", type: 'opus'}, 'fallback.mp4']`. BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource. | | `loadEvent` | string | <optional> | 'canplaythrough' | This sets the Video source event to listen for before the load is considered complete. 'canplaythrough' implies the video has downloaded enough, and bandwidth is high enough that it can be played to completion. 'canplay' implies the video has downloaded enough to start playing, but not necessarily to finish. 'loadeddata' just makes sure that the video meta data and first frame have downloaded. Phaser uses this value automatically if the browser is detected as being Firefox and no `loadEvent` is given, otherwise it defaults to `canplaythrough`. | | `asBlob` | boolean | <optional> | false | Video files can either be loaded via the creation of a video element which has its src property set. Or they can be loaded via xhr, stored as binary data in memory and then converted to a Blob. This isn't supported in IE9 or Android 2. If you need to have the same video playing at different times across multiple Sprites then you need to load it as a Blob. | ##### Returns [Phaser.Loader](phaser.loader) - This Loader instance. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 1111](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L1111)) ### withSyncPoints(callback, callbackContext) → {[Phaser.Loader](phaser.loader)} Add a synchronization point to the assets/files added within the supplied callback. A synchronization point denotes that an asset *must* be completely loaded before subsequent assets can be loaded. An asset marked as a sync-point does not need to wait for previous assets to load (unless they are sync-points). Resources, such as packs, may still be downloaded around sync-points, as long as they do not finalize loading. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The callback is invoked and is supplied with a single argument: the loader. | | `callbackContext` | object | <optional> | (loader) | Context for the callback. | ##### Returns [Phaser.Loader](phaser.loader) - This Loader instance. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 1649](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L1649)) ### xml(key, url, overwrite) → {[Phaser.Loader](phaser.loader)} Adds an XML file to the current load queue. The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. Retrieve the file via `Cache.getXML(key)`. The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" and no URL is given then the Loader will set the URL to be "alien.xml". It will always add `.xml` as the extension. If you do not desire this action then provide a URL. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Unique asset key of the xml file. | | `url` | string | <optional> | | URL of the XML file. If undefined or `null` the url will be set to `<key>.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". | | `overwrite` | boolean | <optional> | false | If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. | ##### Returns [Phaser.Loader](phaser.loader) - This Loader instance. Source code: [loader/Loader.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js) ([Line 849](https://github.com/photonstorm/phaser/tree/v2.6.2/src/loader/Loader.js#L849))
programming_docs
phaser Class: Phaser.Physics Class: Phaser.Physics ===================== Constructor ----------- ### new Physics(game, physicsConfig) The Physics Manager is responsible for looking after all of the running physics systems. Phaser supports 4 physics systems: Arcade Physics, P2, Ninja Physics and Box2D via a commercial plugin. Game Objects (such as Sprites) can only belong to 1 physics system, but you can have multiple systems active in a single game. For example you could have P2 managing a polygon-built terrain landscape that an vehicle drives over, while it could be firing bullets that use the faster (due to being much simpler) Arcade Physics system. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | | A reference to the currently running game. | | `physicsConfig` | object | <optional> | null | A physics configuration object to pass to the Physics world on creation. | Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 21](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L21)) Classes ------- [Arcade](phaser.physics.arcade) [Ninja](phaser.physics.ninja) [P2](phaser.physics.p2) Public Properties ----------------- ### [static] ARCADE : number Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 73](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L73)) ### [static] BOX2D : number Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 91](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L91)) ### [static] CHIPMUNK : number Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 97](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L97)) ### [static] MATTERJS : number Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 103](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L103)) ### [static] NINJA : number Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L85)) ### [static] P2JS : number Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 79](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L79)) ### arcade : [Phaser.Physics.Arcade](phaser.physics.arcade) The Arcade Physics system. Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L38)) ### box2d :Phaser.Physics.Box2D The Box2D Physics system. Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 53](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L53)) ### chipmunk :Phaser.Physics.Chipmunk The Chipmunk Physics system (to be done). Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L58)) ### config : Object The physics configuration object as passed to the game on creation. Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 33](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L33)) ### game : [Phaser.Game](phaser.game) Local reference to game. Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L28)) ### matter :Phaser.Physics.Matter The MatterJS Physics system (coming soon). Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 63](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L63)) ### ninja : [Phaser.Physics.Ninja](phaser.physics.ninja) The N+ Ninja Physics system. Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 48](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L48)) ### p2 : [Phaser.Physics.P2](phaser.physics.p2) The P2.JS Physics system. Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 43](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L43)) Public Methods -------------- ### <internal> clear() Clears down all active physics systems. This doesn't destroy them, it just clears them of objects and is called when the State changes. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 349](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L349)) ### destroy() Destroys all active physics systems. Usually only called on a Game Shutdown, not on a State swap. Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 399](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L399)) ### enable(object, system, debug) This will create a default physics body on the given game object or array of objects. A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. It can be for any of the physics systems that have been started: Phaser.Physics.Arcade - A light weight AABB based collision system with basic separation. Phaser.Physics.P2JS - A full-body advanced physics system supporting multiple object shapes, polygon loading, contact materials, springs and constraints. Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. Advanced AABB and Circle vs. Tile collision. Phaser.Physics.BOX2D - A port of https://code.google.com/p/box2d-html5 Phaser.Physics.MATTER - A full-body and light-weight advanced physics system (still in development) Phaser.Physics.CHIPMUNK is still in development. If you require more control over what type of body is created, for example to create a Ninja Physics Circle instead of the default AABB, then see the individual physics systems `enable` methods instead of using this generic one. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `object` | object | array | | | The game object to create the physics body on. Can also be an array of objects, a body will be created on every object in the array. | | `system` | number | <optional> | Phaser.Physics.ARCADE | The physics system that will be used to create the body. Defaults to Arcade Physics. | | `debug` | boolean | <optional> | false | Enable the debug drawing for this body. Defaults to false. | Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 208](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L208)) ### parseConfig() Parses the Physics Configuration object passed to the Game constructor and starts any physics systems specified within. Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 107](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L107)) ### <internal> preUpdate() preUpdate checks. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 260](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L260)) ### <internal> reset() Resets the active physics system. Called automatically on a Phaser.State swap. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 374](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L374)) ### setBoundsToWorld(left, right, top, bottom, setCollisionGroup) Sets the bounds of the Physics world to match the Game.World dimensions. You can optionally set which 'walls' to create: left, right, top or bottom. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `left` | boolean | <optional> | true | If true will create the left bounds wall. | | `right` | boolean | <optional> | true | If true will create the right bounds wall. | | `top` | boolean | <optional> | true | If true will create the top bounds wall. | | `bottom` | boolean | <optional> | true | If true will create the bottom bounds wall. | | `setCollisionGroup` | boolean | <optional> | true | If true the Bounds will be set to use its own Collision Group. | Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 552](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L552)) ### <internal> setBoundsToWorld() Updates the physics bounds to match the world dimensions. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 314](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L314)) ### setWorldMaterial(material, left, right, top, bottom) Sets the given material against the 4 bounds of this World. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `material` | [Phaser.Physics.P2.Material](phaser.physics.p2.material) | | | The material to set. | | `left` | boolean | <optional> | true | If true will set the material on the left bounds wall. | | `right` | boolean | <optional> | true | If true will set the material on the right bounds wall. | | `top` | boolean | <optional> | true | If true will set the material on the top bounds wall. | | `bottom` | boolean | <optional> | true | If true will set the material on the bottom bounds wall. | Source code: [physics/p2/World.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js) ([Line 569](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/World.js#L569)) ### startSystem(system) This will create an instance of the requested physics simulation. Phaser.Physics.Arcade is running by default, but all others need activating directly. You can start the following physics systems: Phaser.Physics.P2JS - A full-body advanced physics system by Stefan Hedman. Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. Phaser.Physics.BOX2D - A commercial Phaser Plugin (see http://phaser.io) Both Ninja Physics and Box2D require their respective plugins to be loaded before you can start them. They are not bundled into the core Phaser library. If the physics world has already been created (i.e. in another state in your game) then calling startSystem will reset the physics world, not re-create it. If you need to start them again from their constructors then set Phaser.Physics.p2 (or whichever system you want to recreate) to `null` before calling `startSystem`. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `system` | number | The physics system to start: Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA or Phaser.Physics.BOX2D. | Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 142](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L142)) ### <internal> update() Updates all running physics systems. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [physics/Physics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js) ([Line 287](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/Physics.js#L287)) phaser Class: Phaser.KeyCode Class: Phaser.KeyCode ===================== Constructor ----------- ### new KeyCode() A key code represents a physical key on a keyboard. The KeyCode class contains commonly supported keyboard key codes which can be used as keycode`-parameters in several [Phaser.Keyboard](phaser.keyboard) and [Phaser.Key](phaser.key) methods. *Note*: These values should only be used indirectly, eg. as `Phaser.KeyCode.KEY`. Future versions may replace the actual values, such that they remain compatible with `keycode`-parameters. The current implementation maps to the [KeyboardEvent.keyCode](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode) property. *Note*: Use `Phaser.KeyCode.KEY` instead of `Phaser.Keyboard.KEY` to refer to a key code; the latter approach is supported for compatibility. Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 609](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L609)) Public Properties ----------------- ### <static> A Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 611](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L611)) ### <static> ALT Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 779](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L779)) ### <static> B Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 613](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L613)) ### <static> BACKSPACE Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 767](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L767)) ### <static> BACKWARD\_SLASH Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 761](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L761)) ### <static> C Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 615](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L615)) ### <static> CAPS\_LOCK Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 781](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L781)) ### <static> CLEAR Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 771](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L771)) ### <static> CLOSED\_BRACKET Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 763](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L763)) ### <static> COLON Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 745](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L745)) ### <static> COMMA Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 749](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L749)) ### <static> CONTROL Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 777](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L777)) ### <static> D Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 617](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L617)) ### <static> DELETE Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 809](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L809)) ### <static> DOWN Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 801](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L801)) ### <static> E Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 619](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L619)) ### <static> EIGHT Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 679](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L679)) ### <static> END Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 791](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L791)) ### <static> ENTER Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 773](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L773)) ### <static> EQUALS Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 747](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L747)) ### <static> ESC Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 783](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L783)) ### <static> F Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 621](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L621)) ### <static> F1 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 715](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L715)) ### <static> F2 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 717](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L717)) ### <static> F3 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 719](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L719)) ### <static> F4 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 721](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L721)) ### <static> F5 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 723](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L723)) ### <static> F6 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 725](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L725)) ### <static> F7 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 727](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L727)) ### <static> F8 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 729](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L729)) ### <static> F9 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 731](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L731)) ### <static> F10 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 733](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L733)) ### <static> F11 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 735](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L735)) ### <static> F12 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 737](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L737)) ### <static> F13 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 739](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L739)) ### <static> F14 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 741](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L741)) ### <static> F15 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 743](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L743)) ### <static> FIVE Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 673](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L673)) ### <static> FOUR Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 671](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L671)) ### <static> G Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 623](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L623)) ### <static> H Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 625](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L625)) ### <static> HELP Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 811](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L811)) ### <static> HOME Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 793](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L793)) ### <static> I Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 627](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L627)) ### <static> INSERT Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 807](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L807)) ### <static> J Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 629](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L629)) ### <static> K Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 631](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L631)) ### <static> L Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 633](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L633)) ### <static> LEFT Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 795](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L795)) ### <static> M Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 635](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L635)) ### <static> MINUS Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 805](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L805)) ### <static> N Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 637](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L637)) ### <static> NINE Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 681](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L681)) ### <static> NUM\_LOCK Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 813](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L813)) ### <static> NUMPAD\_0 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 683](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L683)) ### <static> NUMPAD\_1 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 685](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L685)) ### <static> NUMPAD\_2 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 687](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L687)) ### <static> NUMPAD\_3 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 689](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L689)) ### <static> NUMPAD\_4 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 691](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L691)) ### <static> NUMPAD\_5 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 693](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L693)) ### <static> NUMPAD\_6 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 695](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L695)) ### <static> NUMPAD\_7 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 697](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L697)) ### <static> NUMPAD\_8 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 699](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L699)) ### <static> NUMPAD\_9 Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 701](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L701)) ### <static> NUMPAD\_ADD Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 705](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L705)) ### <static> NUMPAD\_DECIMAL Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 711](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L711)) ### <static> NUMPAD\_DIVIDE Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 713](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L713)) ### <static> NUMPAD\_ENTER Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 707](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L707)) ### <static> NUMPAD\_MULTIPLY Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 703](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L703)) ### <static> NUMPAD\_SUBTRACT Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 709](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L709)) ### <static> O Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 639](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L639)) ### <static> ONE Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 665](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L665)) ### <static> OPEN\_BRACKET Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 759](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L759)) ### <static> P Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 641](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L641)) ### <static> PAGE\_DOWN Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 789](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L789)) ### <static> PAGE\_UP Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 787](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L787)) ### <static> PERIOD Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 753](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L753)) ### <static> PLUS Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 803](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L803)) ### <static> Q Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 643](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L643)) ### <static> QUESTION\_MARK Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 755](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L755)) ### <static> QUOTES Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 765](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L765)) ### <static> R Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 645](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L645)) ### <static> RIGHT Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 799](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L799)) ### <static> S Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 647](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L647)) ### <static> SEVEN Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 677](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L677)) ### <static> SHIFT Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 775](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L775)) ### <static> SIX Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 675](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L675)) ### <static> SPACEBAR Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 785](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L785)) ### <static> T Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 649](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L649)) ### <static> TAB Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 769](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L769)) ### <static> THREE Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 669](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L669)) ### <static> TILDE Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 757](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L757)) ### <static> TWO Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 667](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L667)) ### <static> U Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 651](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L651)) ### <static> UNDERSCORE Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 751](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L751)) ### <static> UP Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 797](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L797)) ### <static> V Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 653](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L653)) ### <static> W Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 655](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L655)) ### <static> X Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 657](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L657)) ### <static> Y Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 659](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L659)) ### <static> Z Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 661](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L661)) ### <static> ZERO Source code: [input/Keyboard.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js) ([Line 663](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Keyboard.js#L663))
programming_docs
phaser Class: Phaser.Physics.Ninja.AABB Class: Phaser.Physics.Ninja.AABB ================================ Constructor ----------- ### new AABB(body, x, y, width, height) Ninja Physics AABB constructor. Note: This class could be massively optimised and reduced in size. I leave that challenge up to you. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `body` | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | The body that owns this shape. | | `x` | number | The x coordinate to create this shape at. | | `y` | number | The y coordinate to create this shape at. | | `width` | number | The width of this AABB. | | `height` | number | The height of this AABB. | Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L20)) Public Properties ----------------- ### aabbTileProjections : Object All of the collision response handlers. Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L86)) ### body ##### Properties: | Name | Type | Description | | --- | --- | --- | | `system` | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | A reference to the body that owns this shape. | Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 25](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L25)) ### [readonly] height : number The height. Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 64](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L64)) ### oldpos : [Phaser.Point](phaser.point) The position of this object in the previous update. Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 40](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L40)) ### pos : [Phaser.Point](phaser.point) The position of this object. Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 35](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L35)) ### system : [Phaser.Physics.Ninja](phaser.physics.ninja) A reference to the physics system. Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L30)) ### velocity : [Phaser.Point](phaser.point) The velocity of this object. Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 81](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L81)) ### [readonly] width : number The width. Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L58)) ### [readonly] xw : number Half the width. Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L46)) ### [readonly] yw ##### Properties: | Name | Type | Description | | --- | --- | --- | | `xw` | number | Half the height. | Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 52](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L52)) Public Methods -------------- ### collideAABBVsAABB(aabb) Collides this AABB against a AABB. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `aabb` | [Phaser.Physics.Ninja.AABB](phaser.physics.ninja.aabb) | The AABB to collide against. | Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 336](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L336)) ### collideAABBVsTile(tile) Collides this AABB against a Tile. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `tile` | [Phaser.Physics.Ninja.Tile](phaser.physics.ninja.tile) | The Tile to collide against. | Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 408](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L408)) ### collideWorldBounds() Collides this AABB against the world bounds. Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 295](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L295)) ### destroy() Destroys this AABB's reference to Body and System Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 993](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L993)) ### integrate() Updates this AABBs position. Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 108](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L108)) ### projAABB\_22DegB(x, y, obj, t) → {number} Resolves 22 Degree tile collision. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Penetration depth on the x axis. | | `y` | number | Penetration depth on the y axis. | | `obj` | [Phaser.Physics.Ninja.AABB](phaser.physics.ninja.aabb) | The AABB involved in the collision. | | `t` | [Phaser.Physics.Ninja.Tile](phaser.physics.ninja.tile) | The Tile involved in the collision. | ##### Returns number - The result of the collision. Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 702](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L702)) ### projAABB\_22DegS(x, y, obj, t) → {number} Resolves 22 Degree tile collision. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Penetration depth on the x axis. | | `y` | number | Penetration depth on the y axis. | | `obj` | [Phaser.Physics.Ninja.AABB](phaser.physics.ninja.aabb) | The AABB involved in the collision. | | `t` | [Phaser.Physics.Ninja.Tile](phaser.physics.ninja.tile) | The Tile involved in the collision. | ##### Returns number - The result of the collision. Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 622](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L622)) ### projAABB\_45Deg(x, y, obj, t) → {number} Resolves 45 Degree tile collision. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Penetration depth on the x axis. | | `y` | number | Penetration depth on the y axis. | | `obj` | [Phaser.Physics.Ninja.AABB](phaser.physics.ninja.aabb) | The AABB involved in the collision. | | `t` | [Phaser.Physics.Ninja.Tile](phaser.physics.ninja.tile) | The Tile involved in the collision. | ##### Returns number - The result of the collision. Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 569](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L569)) ### projAABB\_67DegB(x, y, obj, t) → {number} Resolves 67 Degree tile collision. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Penetration depth on the x axis. | | `y` | number | Penetration depth on the y axis. | | `obj` | [Phaser.Physics.Ninja.AABB](phaser.physics.ninja.aabb) | The AABB involved in the collision. | | `t` | [Phaser.Physics.Ninja.Tile](phaser.physics.ninja.tile) | The Tile involved in the collision. | ##### Returns number - The result of the collision. Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 834](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L834)) ### projAABB\_67DegS(x, y, obj, t) → {number} Resolves 67 Degree tile collision. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Penetration depth on the x axis. | | `y` | number | Penetration depth on the y axis. | | `obj` | [Phaser.Physics.Ninja.AABB](phaser.physics.ninja.aabb) | The AABB involved in the collision. | | `t` | [Phaser.Physics.Ninja.Tile](phaser.physics.ninja.tile) | The Tile involved in the collision. | ##### Returns number - The result of the collision. Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 755](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L755)) ### projAABB\_Concave(x, y, obj, t) → {number} Resolves Concave tile collision. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Penetration depth on the x axis. | | `y` | number | Penetration depth on the y axis. | | `obj` | [Phaser.Physics.Ninja.AABB](phaser.physics.ninja.aabb) | The AABB involved in the collision. | | `t` | [Phaser.Physics.Ninja.Tile](phaser.physics.ninja.tile) | The Tile involved in the collision. | ##### Returns number - The result of the collision. Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 935](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L935)) ### projAABB\_Convex(x, y, obj, t) → {number} Resolves Convex tile collision. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Penetration depth on the x axis. | | `y` | number | Penetration depth on the y axis. | | `obj` | [Phaser.Physics.Ninja.AABB](phaser.physics.ninja.aabb) | The AABB involved in the collision. | | `t` | [Phaser.Physics.Ninja.Tile](phaser.physics.ninja.tile) | The Tile involved in the collision. | ##### Returns number - The result of the collision. Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 885](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L885)) ### projAABB\_Full(x, y, obj, t) → {number} Resolves Full tile collision. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Penetration depth on the x axis. | | `y` | number | Penetration depth on the y axis. | | `obj` | [Phaser.Physics.Ninja.AABB](phaser.physics.ninja.aabb) | The AABB involved in the collision. | | `t` | [Phaser.Physics.Ninja.Tile](phaser.physics.ninja.tile) | The Tile involved in the collision. | ##### Returns number - The result of the collision. Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 491](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L491)) ### projAABB\_Half(x, y, obj, t) → {number} Resolves Half tile collision. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Penetration depth on the x axis. | | `y` | number | Penetration depth on the y axis. | | `obj` | [Phaser.Physics.Ninja.AABB](phaser.physics.ninja.aabb) | The AABB involved in the collision. | | `t` | [Phaser.Physics.Ninja.Tile](phaser.physics.ninja.tile) | The Tile involved in the collision. | ##### Returns number - The result of the collision. Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 510](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L510)) ### render(context, xOffset, yOffset, color, filled) Render this AABB for debugging purposes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `context` | object | The context to render to. | | `xOffset` | number | X offset from AABB's position to render at. | | `yOffset` | number | Y offset from AABB's position to render at. | | `color` | string | color of the debug shape to be rendered. (format is css color string). | | `filled` | boolean | Render the shape as solid (true) or hollow (false). | Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 1003](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L1003)) ### reportCollision(px, py, dx, dy) Process a collision partner-agnostic collision response and apply the resulting forces. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `px` | number | The tangent velocity | | `py` | number | The tangent velocity | | `dx` | number | Collision normal | | `dy` | number | Collision normal | Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 128](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L128)) ### reportCollisionVsBody(px, py, dx, dy, obj) Process a body collision and apply the resulting forces. Still very much WIP and doesn't work fully. Feel free to fix! ##### Parameters | Name | Type | Description | | --- | --- | --- | | `px` | number | The tangent velocity | | `py` | number | The tangent velocity | | `dx` | number | Collision normal | | `dy` | number | Collision normal | | `obj` | number | Object this AABB collided with | Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 248](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L248)) ### reportCollisionVsWorld(px, py, dx, dy) Process a world collision and apply the resulting forces. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `px` | number | The tangent velocity | | `py` | number | The tangent velocity | | `dx` | number | Collision normal | | `dy` | number | Collision normal | Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 202](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L202)) ### resolveTile(x, y, body, tile) → {boolean} Resolves tile collision. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Penetration depth on the x axis. | | `y` | number | Penetration depth on the y axis. | | `body` | [Phaser.Physics.Ninja.AABB](phaser.physics.ninja.aabb) | The AABB involved in the collision. | | `tile` | [Phaser.Physics.Ninja.Tile](phaser.physics.ninja.tile) | The Tile involved in the collision. | ##### Returns boolean - True if the collision was processed, otherwise false. Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 467](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L467)) ### reverse() Source code: [physics/ninja/AABB.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js) ([Line 216](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/ninja/AABB.js#L216)) phaser Class: Phaser.Creature Class: Phaser.Creature ====================== Constructor ----------- ### new Creature(game, x, y, key, mesh, animation) Creature is a custom Game Object used in conjunction with the Creature Runtime libraries by Kestrel Moon Studios. It allows you to display animated Game Objects that were created with the [Creature Automated Animation Tool](http://www.kestrelmoon.com/creature/). Note 1: You can only use Phaser.Creature objects in WebGL enabled games. They do not work in Canvas mode games. Note 2: You must use a build of Phaser that includes the CreatureMeshBone.js runtime and gl-matrix.js, or have them loaded before your Phaser game boots. See the Phaser custom build process for more details. By default the Creature runtimes are NOT included in any pre-configured version of Phaser. So you'll need to do `grunt custom` to create a build that includes them. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | | A reference to the currently running game. | | `x` | number | | | The x coordinate of the Game Object. The coordinate is relative to any parent container this Game Object may be in. | | `y` | number | | | The y coordinate of the Game Object. The coordinate is relative to any parent container this Game Object may be in. | | `key` | string | [PIXI.Texture](pixi.texture) | | | The texture used by the Creature Object during rendering. It can be a string which is a reference to the Cache entry, or an instance of a PIXI.Texture. | | `mesh` | string | | | The mesh data for the Creature Object. It should be a string which is a reference to the Cache JSON entry. | | `animation` | string | <optional> | 'default' | The animation within the mesh data to play. | Source code: [gameobjects/Creature.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js#L42)) Extends ------- * [PIXI.DisplayObjectContainer](pixi.displayobjectcontainer) * [Phaser.Component.Core](phaser.component.core) * [Phaser.Component.Angle](phaser.component.angle) * [Phaser.Component.AutoCull](phaser.component.autocull) * [Phaser.Component.BringToTop](phaser.component.bringtotop) * [Phaser.Component.Destroy](phaser.component.destroy) * [Phaser.Component.FixedToCamera](phaser.component.fixedtocamera) * [Phaser.Component.LifeSpan](phaser.component.lifespan) * [Phaser.Component.Reset](phaser.component.reset) Public Properties ----------------- ### alive : boolean A useful flag to control if the Game Object is alive or dead. This is set automatically by the Health components `damage` method should the object run out of health. Or you can toggle it via your game code. This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. Inherited From * [Phaser.Component.LifeSpan#alive](phaser.component.lifespan#alive) Default Value * true Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L50)) ### angle : number The angle property is the rotation of the Game Object in *degrees* from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90. If you wish to work in radians instead of degrees you can use the property `rotation` instead. Working in radians is slightly faster as it doesn't have to perform any calculations. Inherited From * [Phaser.Component.Angle#angle](phaser.component.angle#angle) Source code: [gameobjects/components/Angle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js#L29)) ### animation :CreatureAnimation The CreatureAnimation instance. Source code: [gameobjects/Creature.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js) ([Line 69](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js#L69)) ### animations : [Phaser.AnimationManager](phaser.animationmanager) If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. Through it you can create, play, pause and stop animations. Inherited From * [Phaser.Component.Core#animations](phaser.component.core#animations) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 193](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L193)) See * [Phaser.AnimationManager](phaser.animationmanager) ### autoCull : boolean A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, or you have tested performance and find it acceptable. Inherited From * [Phaser.Component.AutoCull#autoCull](phaser.component.autocull#autoCull) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L28)) ### cameraOffset : [Phaser.Point](phaser.point) The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. Inherited From * [Phaser.Component.FixedToCamera#cameraOffset](phaser.component.fixedtocamera#cameraOffset) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L86)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### <internal> colors :PIXI.Uint16Array The vertices colors Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/Creature.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js) ([Line 142](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js#L142)) ### <internal> components : Object The components this Game Object has installed. Inherited From * [Phaser.Component.Core#components](phaser.component.core#components) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 167](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L167)) ### <internal> creatureBoundsMax : [Phaser.Point](phaser.point) The maximum bounds point. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/Creature.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js) ([Line 111](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js#L111)) ### <internal> creatureBoundsMin : [Phaser.Point](phaser.point) The minimum bounds point. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/Creature.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js) ([Line 105](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js#L105)) ### data : Object An empty Object that belongs to this Game Object. This value isn't ever used internally by Phaser, but may be used by your own code, or by Phaser Plugins, to store data that needs to be associated with the Game Object, without polluting the Game Object directly. Inherited From * [Phaser.Component.Core#data](phaser.component.core#data) Default Value * {} Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 160](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L160)) ### debug : boolean A debug flag designed for use with `Game.enableStep`. Inherited From * [Phaser.Component.Core#debug](phaser.component.core#debug) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 218](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L218)) ### [readonly] destroyPhase : boolean As a Game Object runs through its destroy method this flag is set to true, and can be checked in any sub-systems or plugins it is being destroyed from. Inherited From * [Phaser.Component.Destroy#destroyPhase](phaser.component.destroy#destroyPhase) Source code: [gameobjects/components/Destroy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js#L22)) ### events : [Phaser.Events](phaser.events) All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this Game Object, or any of its components. Inherited From * [Phaser.Component.Core#events](phaser.component.core#events) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 185](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L185)) See * [Phaser.Events](phaser.events) ### exists : boolean Controls if this Game Object is processed by the core game loop. If this Game Object has a physics body it also controls if its physics body is updated or not. When `exists` is set to `false` it will remove its physics body from the physics world if it has one. It also toggles the `visible` property to false as well. Setting `exists` to true will add its physics body back in to the physics world, if it has one. It will also set the `visible` property to `true`. Inherited From * [Phaser.Component.Core#exists](phaser.component.core#exists) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 284](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L284)) ### fixedToCamera : boolean A Game Object that is "fixed" to the camera uses its x/y coordinates as offsets from the top left of the camera during rendering. The values are adjusted at the rendering stage, overriding the Game Objects actual world position. The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times regardless where in the world the camera is. The offsets are stored in the `cameraOffset` property. Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. Inherited From * [Phaser.Component.FixedToCamera#fixedToCamera](phaser.component.fixedtocamera#fixedToCamera) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 56](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L56)) ### [readonly] fresh : boolean A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. This property is mostly used internally by the physics systems, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#fresh](phaser.component.core#fresh) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 248](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L248)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Inherited From * [Phaser.Component.Core#game](phaser.component.core#game) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 142](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L142)) ### height : number The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#height](pixi.displayobjectcontainer#height) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 600](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L600)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### [readonly] inCamera : boolean Checks if the Game Objects bounds intersect with the Game Camera bounds. Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. Inherited From * [Phaser.Component.AutoCull#inCamera](phaser.component.autocull#inCamera) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L37)) ### <internal> indices :PIXI.Uint16Array Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/Creature.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js) ([Line 131](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js#L131)) ### isPlaying : boolean Is the *current* animation playing? Source code: [gameobjects/Creature.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js) ([Line 443](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js#L443)) ### key : string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) The key of the image or texture used by this Game Object during rendering. If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. ##### Type * string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) Inherited From * [Phaser.Component.Core#key](phaser.component.core#key) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 203](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L203)) ### lifespan : number The lifespan allows you to give a Game Object a lifespan in milliseconds. Once the Game Object is 'born' you can set this to a positive value. It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. When it reaches zero it will call the `kill` method. Very handy for particles, bullets, collectibles, or any other short-lived entity. Inherited From * [Phaser.Component.LifeSpan#lifespan](phaser.component.lifespan#lifespan) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 65](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L65)) ### loop : boolean Should the *current* animation loop or not? Source code: [gameobjects/Creature.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js) ([Line 463](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js#L463)) ### manager :CreatureManager The CreatureManager instance for this object. Source code: [gameobjects/Creature.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js) ([Line 74](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js#L74)) ### name : string A user defined name given to this Game Object. This value isn't ever used internally by Phaser, it is meant as a game level property. Inherited From * [Phaser.Component.Core#name](phaser.component.core#name) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 150](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L150)) ### pendingDestroy : boolean A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. You can set it directly to allow you to flag an object to be destroyed on its next update. This is extremely useful if you wish to destroy an object from within one of its own callbacks such as with Buttons or other Input events. Inherited From * [Phaser.Component.Core#pendingDestroy](phaser.component.core#pendingDestroy) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 259](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L259)) ### [readonly] previousPosition : [Phaser.Point](phaser.point) The position the Game Object was located in the previous frame. Inherited From * [Phaser.Component.Core#previousPosition](phaser.component.core#previousPosition) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 225](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L225)) ### [readonly] previousRotation : number The rotation the Game Object was in set to in the previous frame. Value is in radians. Inherited From * [Phaser.Component.Core#previousRotation](phaser.component.core#previousRotation) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L232)) ### [readonly] renderOrderID : number The render order ID is used internally by the renderer and Input Manager and should not be modified. This property is mostly used internally by the renderers, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#renderOrderID](phaser.component.core#renderOrderID) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 240](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L240)) ### texture : [PIXI.Texture](pixi.texture) The texture the animation is using. Source code: [gameobjects/Creature.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js) ([Line 94](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js#L94)) ### timeDelta : number How quickly the animation advances. Default Value * 0.05 Source code: [gameobjects/Creature.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js) ([Line 80](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js#L80)) ### [readonly] type : number The const type of this object. Source code: [gameobjects/Creature.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js#L50)) ### <internal> uvs :PIXI.Float32Array The UV data. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/Creature.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js) ([Line 125](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js#L125)) ### <internal> vertices :PIXI.Float32Array The vertices data. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/Creature.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js) ([Line 119](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js#L119)) ### width : number The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#width](pixi.displayobjectcontainer#width) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 571](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L571)) ### world : [Phaser.Point](phaser.point) The world coordinates of this Game Object in pixels. Depending on where in the display list this Game Object is placed this value can differ from `position`, which contains the x/y coordinates relative to the Game Objects parent. Inherited From * [Phaser.Component.Core#world](phaser.component.core#world) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 211](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L211)) ### [readonly] z : number The z depth of this Game Object within its parent Group. No two objects in a Group can have the same z value. This value is adjusted automatically whenever the Group hierarchy changes. If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. Inherited From * [Phaser.Component.Core#z](phaser.component.core#z) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 177](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L177)) Public Methods -------------- ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### bringToTop() → {PIXI.DisplayObject} Brings this Game Object to the top of its parents display list. Visually this means it will render over the top of any old child in the same Group. If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#bringToTop](phaser.component.bringtotop#bringToTop) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L24)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### destroy(destroyChildren, destroyTexture) Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present and nulls its reference to `game`, freeing it up for garbage collection. If this Game Object has the Events component it will also dispatch the `onDestroy` event. You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've more than one Game Object sharing the same BaseTexture. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroyChildren` | boolean | <optional> | true | Should every child of this object have its destroy method called as well? | | `destroyTexture` | boolean | <optional> | false | Destroy the BaseTexture this Game Object is using? Note that if another Game Object is sharing the same BaseTexture it will invalidate it. | Inherited From * [Phaser.Component.Destroy#destroy](phaser.component.destroy#destroy) Source code: [gameobjects/components/Destroy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js#L37)) ### getBounds(targetCoordinateSpace) → {Rectangle} Retrieves the global bounds of the displayObjectContainer as a rectangle. The bounds calculation takes all visible children into consideration. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `targetCoordinateSpace` | PIXIDisplayObject | PIXIMatrix | <optional> | Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object. | ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.DisplayObjectContainer#getBounds](pixi.displayobjectcontainer#getBounds) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 280](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L280)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the displayObjectContainer as a rectangle without any transformations. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.DisplayObjectContainer#getLocalBounds](pixi.displayobjectcontainer#getLocalBounds) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 437](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L437)) ### kill() → {PIXI.DisplayObject} Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false. It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal. Note that killing a Game Object is a way for you to quickly recycle it in an object pool, it doesn't destroy the object or free it up from memory. If you don't need this Game Object any more you should call `destroy` instead. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.LifeSpan#kill](phaser.component.lifespan#kill) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 113](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L113)) ### moveDown() → {PIXI.DisplayObject} Moves this Game Object down one place in its parents display list. This call has no effect if the Game Object is already at the bottom of the display list. If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#moveDown](phaser.component.bringtotop#moveDown) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L87)) ### moveUp() → {PIXI.DisplayObject} Moves this Game Object up one place in its parents display list. This call has no effect if the Game Object is already at the top of the display list. If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#moveUp](phaser.component.bringtotop#moveUp) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 66](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L66)) ### play(loop) Plays the currently set animation. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `loop` | boolean | <optional> | false | Should the animation loop? | Source code: [gameobjects/Creature.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js) ([Line 413](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js#L413)) ### <internal> postUpdate() Internal method called by the World postUpdate cycle. Inherited From * [Phaser.Component.Core#postUpdate](phaser.component.core#postUpdate) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 338](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L338)) ### preUpdate() Automatically called by World.preUpdate. Source code: [gameobjects/Creature.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js) ([Line 169](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js#L169)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### reset(x, y, health) → {PIXI.DisplayObject} Resets the Game Object. This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`, `visible` and `renderable` to true. If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value. If this Game Object has a Physics Body it will reset the Body. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate (in world space) to position the Game Object at. | | `y` | number | | | The y coordinate (in world space) to position the Game Object at. | | `health` | number | <optional> | 1 | The health to give the Game Object if it has the Health component. | ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.Reset#reset](phaser.component.reset#reset) Source code: [gameobjects/components/Reset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Reset.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Reset.js#L30)) ### revive(health) → {PIXI.DisplayObject} Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `health` | number | <optional> | 100 | The health to give the Game Object. Only set if the GameObject has the Health component. | ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.LifeSpan#revive](phaser.component.lifespan#revive) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L78)) ### sendToBack() → {PIXI.DisplayObject} Sends this Game Object to the bottom of its parents display list. Visually this means it will render below all other children in the same Group. If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#sendToBack](phaser.component.bringtotop#sendToBack) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L45)) ### setAnimation(key) Sets the Animation this Creature object will play, as defined in the mesh data. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the animation to set, as defined in the mesh data. | Source code: [gameobjects/Creature.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js) ([Line 400](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js#L400)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### stop() Stops the currently playing animation. Source code: [gameobjects/Creature.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js) ([Line 431](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Creature.js#L431)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) ### update() Override this method in your own custom objects to handle any update requirements. It is called immediately after `preUpdate` and before `postUpdate`. Remember if this Game Object has any children you should call update on those too. Inherited From * [Phaser.Component.Core#update](phaser.component.core#update) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 328](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L328))
programming_docs
phaser Class: Phaser.Matrix Class: Phaser.Matrix ==================== Constructor ----------- ### new Matrix(a, b, c, d, tx, ty) The Matrix is a 3x3 matrix mostly used for display transforms within the renderer. It is represented like so: | a | b | tx | | c | d | ty | | 0 | 0 | 1 | ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `a` | number | <optional> | 1 | Horizontal scaling | | `b` | number | <optional> | 0 | Horizontal skewing | | `c` | number | <optional> | 0 | Vertical skewing | | `d` | number | <optional> | 1 | Vertical scaling | | `tx` | number | <optional> | 0 | Horizontal translation | | `ty` | number | <optional> | 0 | Vertical translation | Source code: [geom/Matrix.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js#L26)) Public Properties ----------------- ### a : number Default Value * 1 Source code: [geom/Matrix.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js) ([Line 39](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js#L39)) ### b : number Default Value * 0 Source code: [geom/Matrix.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js#L45)) ### c : number Default Value * 0 Source code: [geom/Matrix.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js#L51)) ### d : number Default Value * 1 Source code: [geom/Matrix.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js) ([Line 57](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js#L57)) ### tx : number Default Value * 0 Source code: [geom/Matrix.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js) ([Line 63](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js#L63)) ### ty : number Default Value * 0 Source code: [geom/Matrix.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js) ([Line 69](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js#L69)) ### [readonly] type : number The const type of this object. Source code: [geom/Matrix.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js) ([Line 75](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js#L75)) Public Methods -------------- ### append(matrix) → {[Phaser.Matrix](phaser.matrix)} Appends the given Matrix to this Matrix. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `matrix` | [Phaser.Matrix](phaser.matrix) | The matrix to append to this one. | ##### Returns [Phaser.Matrix](phaser.matrix) - This Matrix object. Source code: [geom/Matrix.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js) ([Line 345](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js#L345)) ### apply(pos, newPos) → {[Phaser.Point](phaser.point)} Get a new position with the current transformation applied. Can be used to go from a childs coordinate space to the world coordinate space (e.g. rendering) ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `pos` | [Phaser.Point](phaser.point) | | The origin Point. | | `newPos` | [Phaser.Point](phaser.point) | <optional> | The point that the new position is assigned to. This can be same as input point. | ##### Returns [Phaser.Point](phaser.point) - The new point, transformed through this matrix. Source code: [geom/Matrix.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js) ([Line 233](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js#L233)) ### applyInverse(pos, newPos) → {[Phaser.Point](phaser.point)} Get a new position with the inverse of the current transformation applied. Can be used to go from the world coordinate space to a childs coordinate space. (e.g. input) ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `pos` | [Phaser.Point](phaser.point) | | The origin Point. | | `newPos` | [Phaser.Point](phaser.point) | <optional> | The point that the new position is assigned to. This can be same as input point. | ##### Returns [Phaser.Point](phaser.point) - The new point, inverse transformed through this matrix. Source code: [geom/Matrix.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js) ([Line 254](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js#L254)) ### clone(output) → {[Phaser.Matrix](phaser.matrix)} Creates a new Matrix object based on the values of this Matrix. If you provide the output parameter the values of this Matrix will be copied over to it. If the output parameter is blank a new Matrix object will be created. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `output` | [Phaser.Matrix](phaser.matrix) | <optional> | If provided the values of this Matrix will be copied to it, otherwise a new Matrix object is created. | ##### Returns [Phaser.Matrix](phaser.matrix) - A clone of this Matrix. Source code: [geom/Matrix.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js) ([Line 128](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js#L128)) ### copyFrom(matrix) → {[Phaser.Matrix](phaser.matrix)} Copies the properties from the given Matrix into this Matrix. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `matrix` | [Phaser.Matrix](phaser.matrix) | The Matrix to copy from. | ##### Returns [Phaser.Matrix](phaser.matrix) - This Matrix object. Source code: [geom/Matrix.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js) ([Line 172](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js#L172)) ### copyTo(matrix) → {[Phaser.Matrix](phaser.matrix)} Copies the properties from this Matrix to the given Matrix. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `matrix` | [Phaser.Matrix](phaser.matrix) | The Matrix to copy from. | ##### Returns [Phaser.Matrix](phaser.matrix) - The destination Matrix object. Source code: [geom/Matrix.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js) ([Line 157](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js#L157)) ### fromArray(array) → {[Phaser.Matrix](phaser.matrix)} Sets the values of this Matrix to the values in the given array. The Array elements should be set as follows: a = array[0] b = array[1] c = array[3] d = array[4] tx = array[2] ty = array[5] ##### Parameters | Name | Type | Description | | --- | --- | --- | | `array` | Array | The array to copy from. | ##### Returns [Phaser.Matrix](phaser.matrix) - This Matrix object. Source code: [geom/Matrix.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js) ([Line 81](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js#L81)) ### identity() → {[Phaser.Matrix](phaser.matrix)} Resets this Matrix to an identity (default) matrix. ##### Returns [Phaser.Matrix](phaser.matrix) - This Matrix object. Source code: [geom/Matrix.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js) ([Line 371](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js#L371)) ### rotate(angle) → {[Phaser.Matrix](phaser.matrix)} Applies a rotation transformation to this matrix. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `angle` | number | The angle to rotate by, given in radians. | ##### Returns [Phaser.Matrix](phaser.matrix) - This Matrix object. Source code: [geom/Matrix.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js) ([Line 318](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js#L318)) ### scale(x, y) → {[Phaser.Matrix](phaser.matrix)} Applies a scale transformation to this matrix. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The amount to scale horizontally. | | `y` | number | The amount to scale vertically. | ##### Returns [Phaser.Matrix](phaser.matrix) - This Matrix object. Source code: [geom/Matrix.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js) ([Line 297](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js#L297)) ### setTo(a, b, c, d, tx, ty) → {[Phaser.Matrix](phaser.matrix)} Sets the values of this Matrix to the given values. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | number | Horizontal scaling | | `b` | number | Horizontal skewing | | `c` | number | Vertical skewing | | `d` | number | Vertical scaling | | `tx` | number | Horizontal translation | | `ty` | number | Vertical translation | ##### Returns [Phaser.Matrix](phaser.matrix) - This Matrix object. Source code: [geom/Matrix.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js) ([Line 103](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js#L103)) ### toArray(transpose, array) → {PIXI.Float32Array} Creates a Float32 Array with values populated from this Matrix object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `transpose` | boolean | <optional> | false | Whether the values in the array are transposed or not. | | `array` | PIXI.Float32Array | <optional> | | If provided the values will be set into this array, otherwise a new Float32Array is created. | ##### Returns PIXI.Float32Array - The newly created array which contains the matrix. Source code: [geom/Matrix.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js) ([Line 192](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js#L192)) ### translate(x, y) → {[Phaser.Matrix](phaser.matrix)} Translates the matrix on the x and y. This is the same as Matrix.tx += x. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The x value to translate on. | | `y` | number | The y value to translate on. | ##### Returns [Phaser.Matrix](phaser.matrix) - This Matrix object. Source code: [geom/Matrix.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js) ([Line 279](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Matrix.js#L279)) phaser Class: Phaser.Component.Overlap Class: Phaser.Component.Overlap =============================== Constructor ----------- ### new Overlap() The Overlap component allows a Game Object to check if it overlaps with the bounds of another Game Object. Source code: [gameobjects/components/Overlap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Overlap.js) ([Line 12](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Overlap.js#L12)) Public Methods -------------- ### overlap(displayObject) → {boolean} Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object, which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result. This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result. Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency. It should be fine for low-volume testing where physics isn't required. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `displayObject` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.TileSprite](phaser.tilesprite) | [Phaser.Button](phaser.button) | PIXI.DisplayObject | The display object to check against. | ##### Returns boolean - True if the bounds of this Game Object intersects at any point with the bounds of the given display object. Source code: [gameobjects/components/Overlap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Overlap.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Overlap.js#L29)) phaser Class: Phaser.Component.AutoCull Class: Phaser.Component.AutoCull ================================ Constructor ----------- ### new AutoCull() The AutoCull Component is responsible for providing methods that check if a Game Object is within the bounds of the World Camera. It is used by the InWorld component. Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 13](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L13)) Public Properties ----------------- ### autoCull : boolean A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, or you have tested performance and find it acceptable. Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L28)) ### [readonly] inCamera : boolean Checks if the Game Objects bounds intersect with the Game Camera bounds. Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L37)) phaser Class: Phaser.Tile Class: Phaser.Tile ================== Constructor ----------- ### new Tile(layer, index, x, y, width, height) A Tile is a representation of a single tile within the Tilemap. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `layer` | object | The layer in the Tilemap data that this tile belongs to. | | `index` | number | The index of this tile type in the core map data. | | `x` | number | The x coordinate of this tile. | | `y` | number | The y coordinate of this tile. | | `width` | number | Width of the tile. | | `height` | number | Height of the tile. | Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 19](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L19)) Public Properties ----------------- ### alpha : number The alpha value at which this tile is drawn to the canvas. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 84](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L84)) ### [readonly] bottom : number The sum of the y and height properties. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 396](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L396)) ### [readonly] canCollide : boolean True if this tile can collide on any of its faces or has a collision callback set. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 344](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L344)) ### centerX ##### Properties: | Name | Type | Description | | --- | --- | --- | | `width` | number | The width of the tile in pixels. | Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 74](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L74)) ### centerY ##### Properties: | Name | Type | Description | | --- | --- | --- | | `height` | number | The height of the tile in pixels. | Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 79](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L79)) ### collideDown : boolean Indicating collide with any object on the bottom. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 138](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L138)) ### collideLeft : boolean Indicating collide with any object on the left. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 120](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L120)) ### collideRight : boolean Indicating collide with any object on the right. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 126](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L126)) ### [readonly] collides : boolean True if this tile can collide on any of its faces. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 331](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L331)) ### collideUp : boolean Indicating collide with any object on the top. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L132)) ### collisionCallback : Function Tile collision callback. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 144](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L144)) ### collisionCallbackContext : Object The context in which the collision callback will be called. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 150](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L150)) ### faceBottom : boolean Is the bottom of this tile an interesting edge? Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 104](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L104)) ### faceLeft : boolean Is the left of this tile an interesting edge? Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 109](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L109)) ### faceRight : boolean Is the right of this tile an interesting edge? Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 114](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L114)) ### faceTop : boolean Is the top of this tile an interesting edge? Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 99](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L99)) ### flipped : boolean Whether this tile is flipped (mirrored) or not. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L49)) ### height : number The height of the tile in pixels. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 69](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L69)) ### index : number The index of this tile within the map data corresponding to the tileset, or -1 if this represents a blank/null tile. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L29)) ### layer : Object The layer in the Tilemap data that this tile belongs to. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L24)) ### [readonly] left : number The x value in pixels. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 357](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L357)) ### properties : Object Tile specific properties. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 89](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L89)) ### [readonly] right : number The sum of the x and width properties. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 370](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L370)) ### rotation : number The rotation angle of this tile. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 44](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L44)) ### scanned : boolean Has this tile been walked / turned into a poly? Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 94](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L94)) ### [readonly] top : number The y value. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 383](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L383)) ### width : number The width of the tile in pixels. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 64](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L64)) ### worldX ##### Properties: | Name | Type | Description | | --- | --- | --- | | `x` | number | The x map coordinate of this tile. | Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L54)) ### worldY ##### Properties: | Name | Type | Description | | --- | --- | --- | | `y` | number | The y map coordinate of this tile. | Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 59](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L59)) ### x : number The x map coordinate of this tile. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 34](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L34)) ### y : number The y map coordinate of this tile. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 39](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L39)) Public Methods -------------- ### containsPoint(x, y) → {boolean} Check if the given x and y world coordinates are within this Tile. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The x coordinate to test. | | `y` | number | The y coordinate to test. | ##### Returns boolean - True if the coordinates are within this Tile, otherwise false. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 156](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L156)) ### copy(tile) Copies the tile data and properties from the given tile to this tile. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `tile` | [Phaser.Tile](phaser.tile) | The tile to copy from. | Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 305](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L305)) ### destroy() Clean up memory. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 220](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L220)) ### intersects(x, y, right, bottom) Check for intersection with this tile. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The x axis in pixels. | | `y` | number | The y axis in pixels. | | `right` | number | The right point. | | `bottom` | number | The bottom point. | Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 170](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L170)) ### isInteresting(collides, faces) → {boolean} Is this tile interesting? ##### Parameters | Name | Type | Description | | --- | --- | --- | | `collides` | boolean | If true will check any collides value. | | `faces` | boolean | If true will check any face value. | ##### Returns boolean - True if the Tile is interesting, otherwise false. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 275](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L275)) ### resetCollision() Reset collision status flags. Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 256](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L256)) ### setCollision(left, right, up, down) Sets the collision flags for each side of this tile and updates the interesting faces list. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `left` | boolean | Indicating collide with any object on the left. | | `right` | boolean | Indicating collide with any object on the right. | | `up` | boolean | Indicating collide with any object on the top. | | `down` | boolean | Indicating collide with any object on the bottom. | Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 233](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L233)) ### setCollisionCallback(callback, context) Set a callback to be called when this tile is hit by an object. The callback must true true for collision processing to take place. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `callback` | function | Callback function. | | `context` | object | Callback will be called within this context. | Source code: [tilemap/Tile.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js) ([Line 205](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tile.js#L205))
programming_docs
phaser Class: Phaser.Net Class: Phaser.Net ================= Constructor ----------- ### new Net(game) Phaser.Net handles browser URL related tasks such as checking host names, domain names and query string manipulation. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | Source code: [net/Net.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/net/Net.js) ([Line 14](https://github.com/photonstorm/phaser/tree/v2.6.2/src/net/Net.js#L14)) Public Methods -------------- ### checkDomainName(domain) → {boolean} Compares the given domain name against the hostname of the browser containing the game. If the domain name is found it returns true. You can specify a part of a domain, for example 'google' would match 'google.com', 'google.co.uk', etc. Do not include 'http://' at the start. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `domain` | string | | ##### Returns boolean - true if the given domain fragment can be found in the window.location.hostname Source code: [net/Net.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/net/Net.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/net/Net.js#L38)) ### decodeURI(value) → {string} Takes a Uniform Resource Identifier (URI) component (previously created by encodeURIComponent or by a similar routine) and decodes it, replacing \ with spaces in the return. Used internally by the Net classes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `value` | string | The URI component to be decoded. | ##### Returns string - The decoded value. Source code: [net/Net.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/net/Net.js) ([Line 152](https://github.com/photonstorm/phaser/tree/v2.6.2/src/net/Net.js#L152)) ### getHostName() → {string} Returns the hostname given by the browser. ##### Returns string - Source code: [net/Net.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/net/Net.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/net/Net.js#L22)) ### getQueryString(parameter) → {string | object} Returns the Query String as an object. If you specify a parameter it will return just the value of that parameter, should it exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parameter` | string | <optional> | '' | If specified this will return just the value for that key. | ##### Returns string | object - An object containing the key value pairs found in the query string or just the value if a parameter was given. Source code: [net/Net.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/net/Net.js) ([Line 116](https://github.com/photonstorm/phaser/tree/v2.6.2/src/net/Net.js#L116)) ### updateQueryString(key, value, redirect, url) → {string} Updates a value on the Query String and returns it in full. If the value doesn't already exist it is set. If the value exists it is replaced with the new value given. If you don't provide a new value it is removed from the query string. Optionally you can redirect to the new url, or just return it as a string. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The querystring key to update. | | `value` | string | The new value to be set. If it already exists it will be replaced. | | `redirect` | boolean | If true the browser will issue a redirect to the url with the new querystring. | | `url` | string | The URL to modify. If none is given it uses window.location.href. | ##### Returns string - If redirect is false then the modified url and query string is returned. Source code: [net/Net.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/net/Net.js) ([Line 52](https://github.com/photonstorm/phaser/tree/v2.6.2/src/net/Net.js#L52)) phaser Class: Event Class: Event ============ Constructor ----------- ### new Event(target, name, data) Creates an homogenous object for tracking events so users can know what to expect. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `target` | Object | The target object that the event is called on | | `name` | String | The string name of the event that was triggered | | `data` | Object | Arbitrary event data to pass along | Source code: [plugins/path/EventTarget.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js) ([Line 202](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js#L202)) Extends ------- * Object Public Properties ----------------- ### [readonly] data : Object The data that was passed in with this event. Source code: [plugins/path/EventTarget.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js) ([Line 253](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js#L253)) ### [readonly] target : Object The original target the event triggered on. Source code: [plugins/path/EventTarget.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js) ([Line 235](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js#L235)) ### [readonly] timeStamp : number The timestamp when the event occurred. Source code: [plugins/path/EventTarget.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js) ([Line 265](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js#L265)) ### [readonly] type : string The string name of the event that this represents. Source code: [plugins/path/EventTarget.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js) ([Line 244](https://github.com/photonstorm/phaser/tree/v2.6.2/src/plugins/path/EventTarget.js#L244)) phaser Class: Phaser.Gamepad Class: Phaser.Gamepad ===================== Constructor ----------- ### new Gamepad(game) The Gamepad class handles gamepad input and dispatches gamepad events. Remember to call `gamepad.start()`. HTML5 GAMEPAD API SUPPORT IS AT AN EXPERIMENTAL STAGE! At moment of writing this (end of 2013) only Chrome supports parts of it out of the box. Firefox supports it via prefs flags (about:config, search gamepad). The browsers map the same controllers differently. This class has constants for Windows 7 Chrome mapping of XBOX 360 controller. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 21](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L21)) Public Properties ----------------- ### [readonly] active : boolean If the gamepad input is active or not - if not active it should not be updated from Input.js Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 496](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L496)) ### callbackContext : Object The context under which the callbacks are run. Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 80](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L80)) ### enabled : boolean Gamepad input will only be processed if enabled. Default Value * true Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 52](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L52)) ### game : [Phaser.Game](phaser.game) Local reference to game. Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L26)) ### onAxisCallback : Function This callback is invoked every time any gamepad axis is changed. Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 105](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L105)) ### onConnectCallback : Function This callback is invoked every time any gamepad is connected Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L85)) ### onDisconnectCallback : Function This callback is invoked every time any gamepad is disconnected Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 90](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L90)) ### onDownCallback : Function This callback is invoked every time any gamepad button is pressed down. Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 95](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L95)) ### onFloatCallback : Function This callback is invoked every time any gamepad button is changed to a value where value > 0 and value < 1. Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 110](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L110)) ### onUpCallback : Function This callback is invoked every time any gamepad button is released. Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 100](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L100)) ### [readonly] pad1 : [Phaser.SinglePad](phaser.singlepad) Gamepad #1 Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 538](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L538)) ### [readonly] pad2 : [Phaser.SinglePad](phaser.singlepad) Gamepad #2 Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 552](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L552)) ### [readonly] pad3 : [Phaser.SinglePad](phaser.singlepad) Gamepad #3 Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 566](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L566)) ### [readonly] pad4 : [Phaser.SinglePad](phaser.singlepad) Gamepad #4 Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 580](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L580)) ### [readonly] padsConnected : number How many live gamepads are currently connected. Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 524](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L524)) ### [readonly] supported : boolean Whether or not gamepads are supported in current browser. Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 510](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L510)) Public Methods -------------- ### addCallbacks(context, callbacks) Add callbacks to the main Gamepad handler to handle connect/disconnect/button down/button up/axis change/float value buttons. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `context` | object | The context under which the callbacks are run. | | `callbacks` | object | Object that takes six different callback methods:onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback | Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 139](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L139)) ### destroy() Destroys this object and the associated event listeners. Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 476](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L476)) ### isDown(buttonCode) → {boolean} Returns true if the button is currently pressed down, on ANY gamepad. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `buttonCode` | number | The buttonCode of the button to check for. | ##### Returns boolean - True if a button is currently down. Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 457](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L457)) ### justPressed(buttonCode, duration) → {boolean} Returns the "just released" state of a button from ANY gamepad connected. Just released is considered as being true if the button was released within the duration given (default 250ms). ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `buttonCode` | number | | | The buttonCode of the button to check for. | | `duration` | number | <optional> | 250 | The duration below which the button is considered as being just released. | ##### Returns boolean - True if the button is just released otherwise false. Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 436](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L436)) ### justPressed(buttonCode, duration) → {boolean} Returns the "just pressed" state of a button from ANY gamepad connected. Just pressed is considered true if the button was pressed down within the duration given (default 250ms). ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `buttonCode` | number | | | The buttonCode of the button to check for. | | `duration` | number | <optional> | 250 | The duration below which the button is considered as being just pressed. | ##### Returns boolean - True if the button is just pressed otherwise false. Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 415](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L415)) ### reset() Reset all buttons/axes of all gamepads Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 400](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L400)) ### setDeadZones() Sets the deadZone variable for all four gamepads Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 373](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L373)) ### start() Starts the Gamepad event handling. This MUST be called manually before Phaser will start polling the Gamepad API. Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 162](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L162)) ### stop() Stops the Gamepad event handling. Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 386](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L386)) ### <internal> update() Main gamepad update loop. Should not be called manually. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/Gamepad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js) ([Line 231](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Gamepad.js#L231)) phaser Class: Phaser.State Class: Phaser.State =================== Constructor ----------- ### new State() This is a base State class which can be extended if you are creating your own game. It provides quick access to common functions such as the camera, cache, input, match, sound and more. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 14](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L14)) Public Properties ----------------- ### add : [Phaser.GameObjectFactory](phaser.gameobjectfactory) A reference to the GameObjectFactory which can be used to add new objects to the World. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L29)) ### cache : [Phaser.Cache](phaser.cache) A reference to the game cache which contains any loaded or generated assets, such as images, sound and more. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 44](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L44)) ### camera : [Phaser.Camera](phaser.camera) A handy reference to World.camera. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 39](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L39)) ### game : [Phaser.Game](phaser.game) This is a reference to the currently running Game. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 19](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L19)) ### input : [Phaser.Input](phaser.input) A reference to the Input Manager. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L49)) ### key : string The string based identifier given to the State when added into the State Manager. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L24)) ### load : [Phaser.Loader](phaser.loader) A reference to the Loader, which you mostly use in the preload method of your state to load external assets. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L54)) ### make : [Phaser.GameObjectCreator](phaser.gameobjectcreator) A reference to the GameObjectCreator which can be used to make new objects. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 34](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L34)) ### math : [Phaser.Math](phaser.math) A reference to Math class with lots of helpful functions. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 59](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L59)) ### particles : [Phaser.Particles](phaser.particles) The Particle Manager. It is called during the core gameloop and updates any Particle Emitters it has created. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 99](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L99)) ### physics : [Phaser.Physics](phaser.physics) A reference to the physics manager which looks after the different physics systems available within Phaser. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 104](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L104)) ### rnd : [Phaser.RandomDataGenerator](phaser.randomdatagenerator) A reference to the seeded and repeatable random data generator. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 109](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L109)) ### scale : [Phaser.ScaleManager](phaser.scalemanager) A reference to the Scale Manager which controls the way the game scales on different displays. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 69](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L69)) ### sound : [Phaser.SoundManager](phaser.soundmanager) A reference to the Sound Manager which can create, play and stop sounds, as well as adjust global volume. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 64](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L64)) ### stage : [Phaser.Stage](phaser.stage) A reference to the Stage. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 74](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L74)) ### state ##### Properties: | Name | Type | Description | | --- | --- | --- | | `stage` | [Phaser.StateManager](phaser.statemanager) | A reference to the State Manager, which controls state changes. | Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 79](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L79)) ### time : [Phaser.Time](phaser.time) A reference to the game clock and timed events system. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 84](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L84)) ### tweens : [Phaser.TweenManager](phaser.tweenmanager) A reference to the tween manager. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 89](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L89)) ### world : [Phaser.World](phaser.world) A reference to the game world. All objects live in the Game World and its size is not bound by the display resolution. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 94](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L94)) Public Methods -------------- ### create() create is called once preload has completed, this includes the loading of any assets from the Loader. If you don't have a preload method then create is the first method called in your State. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 152](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L152)) ### init() init is the very first function called when your State starts up. It's called before preload, create or anything else. If you need to route the game away to another State you could do so here, or if you need to prepare a set of variables or objects before the preloading starts. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 115](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L115)) ### loadRender() loadRender is called during the Loader process. This only happens if you've set one or more assets to load in the preload method. The difference between loadRender and render is that any objects you render in this method you must be sure their assets exist. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 143](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L143)) ### loadUpdate() loadUpdate is called during the Loader process. This only happens if you've set one or more assets to load in the preload method. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 135](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L135)) ### paused() This method will be called if the core game loop is paused. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 197](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L197)) ### pauseUpdate() pauseUpdate is called while the game is paused instead of preUpdate, update and postUpdate. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L213)) ### preload() preload is called first. Normally you'd use this to load your game assets (or those needed for the current State) You shouldn't create any objects in this method that require assets that you're also loading in this method, as they won't yet be available. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 125](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L125)) ### preRender() The preRender method is called after all Game Objects have been updated, but before any rendering takes place. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L171)) ### render() Nearly all display objects in Phaser render automatically, you don't need to tell them to render. However the render method is called AFTER the game renderer and plugins have rendered, so you're able to do any final post-processing style effects here. Note that this happens before plugins postRender takes place. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 179](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L179)) ### resize() If your game is set to Scalemode RESIZE then each time the browser resizes it will call this function, passing in the new width and height. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 189](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L189)) ### resumed() This method will be called when the core game loop resumes from a paused state. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 205](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L205)) ### shutdown() This method will be called when the State is shutdown (i.e. you switch to another state from this one). Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 221](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L221)) ### update() The update method is left empty for your own use. It is called during the core game loop AFTER debug, physics, plugins and the Stage have had their preUpdate methods called. It is called BEFORE Stage, Tweens, Sounds, Input, Physics, Particles and Plugins have had their postUpdate methods called. Source code: [core/State.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js) ([Line 161](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/State.js#L161))
programming_docs
phaser Class: Phaser.Physics.P2.Spring Class: Phaser.Physics.P2.Spring =============================== Constructor ----------- ### new Spring(world, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `world` | [Phaser.Physics.P2](phaser.physics.p2) | | | A reference to the P2 World. | | `bodyA` | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | First connected body. | | `bodyB` | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | Second connected body. | | `restLength` | number | <optional> | 1 | Rest length of the spring. A number > 0. | | `stiffness` | number | <optional> | 100 | Stiffness of the spring. A number >= 0. | | `damping` | number | <optional> | 1 | Damping of the spring. A number >= 0. | | `worldA` | Array | <optional> | | Where to hook the spring to body A in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. | | `worldB` | Array | <optional> | | Where to hook the spring to body B in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. | | `localA` | Array | <optional> | | Where to hook the spring to body A in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. | | `localB` | Array | <optional> | | Where to hook the spring to body B in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. | Source code: [physics/p2/Spring.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Spring.js) ([Line 23](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Spring.js#L23)) Public Properties ----------------- ### data :p2.LinearSpring The actual p2 spring object. Source code: [physics/p2/Spring.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Spring.js) ([Line 70](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Spring.js#L70)) ### game : [Phaser.Game](phaser.game) Local reference to game. Source code: [physics/p2/Spring.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Spring.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Spring.js#L28)) ### world : [Phaser.Physics.P2](phaser.physics.p2) Local reference to P2 World. Source code: [physics/p2/Spring.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Spring.js) ([Line 33](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Spring.js#L33)) phaser Class: PIXI.WebGLFilterManager Class: PIXI.WebGLFilterManager ============================== Constructor ----------- ### new WebGLFilterManager() Source code: [pixi/renderers/webgl/utils/WebGLFilterManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLFilterManager.js) ([Line 5](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLFilterManager.js#L5)) Public Properties ----------------- ### filterStack : Array Source code: [pixi/renderers/webgl/utils/WebGLFilterManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLFilterManager.js) ([Line 11](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLFilterManager.js#L11)) ### offsetX : number Source code: [pixi/renderers/webgl/utils/WebGLFilterManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLFilterManager.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLFilterManager.js#L17)) ### offsetY : number Source code: [pixi/renderers/webgl/utils/WebGLFilterManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLFilterManager.js) ([Line 23](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLFilterManager.js#L23)) Public Methods -------------- ### applyFilterPass(filter, filterArea, width, height) Applies the filter to the specified area. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `filter` | [PIXI.AbstractFilter](pixi.abstractfilter) | the filter that needs to be applied | | `filterArea` | [PIXI.Texture](pixi.texture) | TODO - might need an update | | `width` | Number | the horizontal range of the filter | | `height` | Number | the vertical range of the filter | Source code: [pixi/renderers/webgl/utils/WebGLFilterManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLFilterManager.js) ([Line 336](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLFilterManager.js#L336)) ### begin(renderSession, buffer) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `renderSession` | RenderSession | - | | `buffer` | ArrayBuffer | - | Source code: [pixi/renderers/webgl/utils/WebGLFilterManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLFilterManager.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLFilterManager.js#L46)) ### destroy() Destroys the filter and removes it from the filter stack. Source code: [pixi/renderers/webgl/utils/WebGLFilterManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLFilterManager.js) ([Line 445](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLFilterManager.js#L445)) ### initShaderBuffers() Initialises the shader buffers. Source code: [pixi/renderers/webgl/utils/WebGLFilterManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLFilterManager.js) ([Line 397](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLFilterManager.js#L397)) ### popFilter() Removes the last filter from the filter stack and doesn't return it. Source code: [pixi/renderers/webgl/utils/WebGLFilterManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLFilterManager.js) ([Line 145](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLFilterManager.js#L145)) ### pushFilter(filterBlock) Applies the filter and adds it to the current filter stack. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `filterBlock` | Object | the filter that will be pushed to the current filter stack | Source code: [pixi/renderers/webgl/utils/WebGLFilterManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLFilterManager.js) ([Line 62](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLFilterManager.js#L62)) ### setContext(gl) Initialises the context and the properties. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `gl` | WebGLContext | the current WebGL drawing context | Source code: [pixi/renderers/webgl/utils/WebGLFilterManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLFilterManager.js) ([Line 32](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/utils/WebGLFilterManager.js#L32)) phaser Class: Phaser.Ellipse Class: Phaser.Ellipse ===================== Constructor ----------- ### new Ellipse(x, y, width, height) Creates a Ellipse object. A curve on a plane surrounding two focal points. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | <optional> | 0 | The X coordinate of the upper-left corner of the framing rectangle of this ellipse. | | `y` | number | <optional> | 0 | The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. | | `width` | number | <optional> | 0 | The overall width of this ellipse. | | `height` | number | <optional> | 0 | The overall height of this ellipse. | Source code: [geom/Ellipse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js) ([Line 18](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js#L18)) Public Properties ----------------- ### bottom : number The sum of the y and height properties. Changing the bottom property of an Ellipse doesn't adjust the y property, but does change the height. Gets or sets the bottom of the ellipse. Source code: [geom/Ellipse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js) ([Line 251](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js#L251)) ### empty : boolean Determines whether or not this Ellipse object is empty. Will return a value of true if the Ellipse objects dimensions are less than or equal to 0; otherwise false. If set to true it will reset all of the Ellipse objects properties to 0. An Ellipse object is empty if its width or height is less than or equal to 0. Gets or sets the empty state of the ellipse. Source code: [geom/Ellipse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js) ([Line 276](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js#L276)) ### height : number The overall height of this ellipse. Source code: [geom/Ellipse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js) ([Line 43](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js#L43)) ### left The left coordinate of the Ellipse. The same as the X coordinate. Source code: [geom/Ellipse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js) ([Line 190](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js#L190)) ### right : number The x coordinate of the rightmost point of the Ellipse. Changing the right property of an Ellipse object has no effect on the x property, but does adjust the width. Gets or sets the value of the rightmost point of the ellipse. Source code: [geom/Ellipse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js) ([Line 209](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js#L209)) ### top : number The top of the Ellipse. The same as its y property. Gets or sets the top of the ellipse. Source code: [geom/Ellipse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js) ([Line 234](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js#L234)) ### [readonly] type : number The const type of this object. Source code: [geom/Ellipse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js#L49)) ### width : number The overall width of this ellipse. Source code: [geom/Ellipse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js#L38)) ### x : number The X coordinate of the upper-left corner of the framing rectangle of this ellipse. Source code: [geom/Ellipse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js#L28)) ### y : number The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. Source code: [geom/Ellipse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js) ([Line 33](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js#L33)) Public Methods -------------- ### <static> contains(a, x, y) → {boolean} Return true if the given x/y coordinates are within the Ellipse object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | [Phaser.Ellipse](phaser.ellipse) | The Ellipse to be checked. | | `x` | number | The X value of the coordinate to test. | | `y` | number | The Y value of the coordinate to test. | ##### Returns boolean - True if the coordinates are within this ellipse, otherwise false. Source code: [geom/Ellipse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js) ([Line 299](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js#L299)) ### clone(output) → {[Phaser.Ellipse](phaser.ellipse)} Returns a new Ellipse object with the same values for the x, y, width, and height properties as this Ellipse object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `output` | [Phaser.Ellipse](phaser.ellipse) | Optional Ellipse object. If given the values will be set into the object, otherwise a brand new Ellipse object will be created and returned. | ##### Returns [Phaser.Ellipse](phaser.ellipse) - The cloned Ellipse object. Source code: [geom/Ellipse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js) ([Line 117](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js#L117)) ### contains(x, y) → {boolean} Return true if the given x/y coordinates are within this Ellipse object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The X value of the coordinate to test. | | `y` | number | The Y value of the coordinate to test. | ##### Returns boolean - True if the coordinates are within this ellipse, otherwise false. Source code: [geom/Ellipse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js) ([Line 138](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js#L138)) ### copyFrom(source) → {[Phaser.Ellipse](phaser.ellipse)} Copies the x, y, width and height properties from any given object to this Ellipse. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `source` | any | The object to copy from. | ##### Returns [Phaser.Ellipse](phaser.ellipse) - This Ellipse object. Source code: [geom/Ellipse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js#L87)) ### copyTo(dest) → {object} Copies the x, y, width and height properties from this Ellipse to any given object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `dest` | any | The object to copy to. | ##### Returns object - This dest object. Source code: [geom/Ellipse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js) ([Line 100](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js#L100)) ### getBounds() → {[Phaser.Rectangle](phaser.rectangle)} Returns the framing rectangle of the ellipse as a Phaser.Rectangle object. ##### Returns [Phaser.Rectangle](phaser.rectangle) - The bounds of the Ellipse. Source code: [geom/Ellipse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js) ([Line 75](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js#L75)) ### random(out) → {[Phaser.Point](phaser.point)} Returns a uniformly distributed random point from anywhere within this Ellipse. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `out` | [Phaser.Point](phaser.point) | object | <optional> | A Phaser.Point, or any object with public x/y properties, that the values will be set in. If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. | ##### Returns [Phaser.Point](phaser.point) - An object containing the random point in its `x` and `y` properties. Source code: [geom/Ellipse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js) ([Line 152](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js#L152)) ### setTo(x, y, width, height) → {[Phaser.Ellipse](phaser.ellipse)} Sets the members of the Ellipse to the specified values. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The X coordinate of the upper-left corner of the framing rectangle of this ellipse. | | `y` | number | The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. | | `width` | number | The overall width of this ellipse. | | `height` | number | The overall height of this ellipse. | ##### Returns [Phaser.Ellipse](phaser.ellipse) - This Ellipse object. Source code: [geom/Ellipse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js#L55)) ### toString() → {string} Returns a string representation of this object. ##### Returns string - A string representation of the instance. Source code: [geom/Ellipse.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js) ([Line 177](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Ellipse.js#L177)) phaser Class: Phaser.PointerMode Class: Phaser.PointerMode ========================= Constructor ----------- ### new PointerMode() Enumeration categorizing operational modes of pointers. PointerType values represent valid bitmasks. For example, a value representing both Mouse and Touch devices can be expressed as `PointerMode.CURSOR | PointerMode.CONTACT`. Values may be added for future mode categorizations. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 1258](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L1258)) Public Properties ----------------- ### [static] CONTACT A 'CONTACT' pointer has an *active cursor* that only tracks movement when actived; notably this is a touch-style input. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 1273](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L1273)) ### [static] CURSOR A 'CURSOR' is a pointer with a *passive cursor* such as a mouse, touchpad, watcom stylus, or even TV-control arrow-pad. It has the property that a cursor is passively moved without activating the input. This currently corresponds with [Phaser.Pointer#isMouse](phaser.pointer#isMouse) property. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 1267](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L1267)) phaser Class: Phaser.Component.Smoothed Class: Phaser.Component.Smoothed ================================ Constructor ----------- ### new Smoothed() The Smoothed component allows a Game Object to control anti-aliasing of an image based texture. Source code: [gameobjects/components/Smoothed.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Smoothed.js) ([Line 12](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Smoothed.js#L12)) Public Properties ----------------- ### smoothed : boolean Enable or disable texture smoothing for this Game Object. It only takes effect if the Game Object is using an image based texture. Smoothing is enabled by default. Source code: [gameobjects/components/Smoothed.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Smoothed.js) ([Line 25](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Smoothed.js#L25)) phaser Class: Phaser.Physics.P2.CollisionGroup Class: Phaser.Physics.P2.CollisionGroup ======================================= Constructor ----------- ### new CollisionGroup(bitmask) Collision Group ##### Parameters | Name | Type | Description | | --- | --- | --- | | `bitmask` | number | The CollisionGroup bitmask. | Source code: [physics/p2/CollisionGroup.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/CollisionGroup.js) ([Line 14](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/CollisionGroup.js#L14)) Public Properties ----------------- ### mask : number The CollisionGroup bitmask. Source code: [physics/p2/CollisionGroup.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/CollisionGroup.js) ([Line 19](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/CollisionGroup.js#L19))
programming_docs
phaser Class: Phaser.Utils.Debug Class: Phaser.Utils.Debug ========================= Constructor ----------- ### new Debug(game) A collection of methods for displaying debug information about game objects. If your game is running in Canvas mode, then you should invoke all of the Debug methods from your games `render` function. This is because they are drawn directly onto the game canvas itself, so if you call any debug methods outside of `render` they are likely to be overwritten by the game itself. If your game is running in WebGL then Debug will create a Sprite that is placed at the top of the Stage display list and bind a canvas texture to it, which must be uploaded every frame. Be advised: this is very expensive, especially in browsers like Firefox. So please only enable Debug in WebGL mode if you really need it (or your desktop can cope with it well) and disable it for production! ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 23](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L23)) Public Properties ----------------- ### bmd : [Phaser.BitmapData](phaser.bitmapdata) In WebGL mode this BitmapData contains a copy of the debug canvas. Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L38)) ### canvas :HTMLCanvasElement The canvas to which Debug calls draws. Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 43](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L43)) ### columnWidth : number The spacing between columns. Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 59](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L59)) ### context :CanvasRenderingContext2D The 2d context of the canvas. Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 48](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L48)) ### currentAlpha : number The alpha of the Debug context, set before all debug information is rendered to it. Default Value * 1 Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L87)) ### currentX : number The current X position the debug information will be rendered at. Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 75](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L75)) ### currentY : number The current Y position the debug information will be rendered at. Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 81](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L81)) ### dirty : boolean Does the canvas need re-rendering? Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 92](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L92)) ### font : string The font that the debug information is rendered in. Default Value * '14px Courier' Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L54)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L28)) ### lineHeight : number The line height between the debug text. Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 64](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L64)) ### renderShadow : boolean Should the text be rendered with a slight shadow? Makes it easier to read on different types of background. Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 69](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L69)) ### sprite : [Phaser.Image](phaser.image) If debugging in WebGL mode we need this. Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 33](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L33)) Public Methods -------------- ### body(sprite, color, filled) Render a Sprites Physics body if it has one set. The body is rendered as a filled or stroked rectangle. This only works for Arcade Physics, Ninja Physics (AABB and Circle only) and Box2D Physics bodies. To display a P2 Physics body you should enable debug mode on the body when creating it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `sprite` | [Phaser.Sprite](phaser.sprite) | | | The Sprite who's body will be rendered. | | `color` | string | <optional> | 'rgba(0,255,0,0.4)' | Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'. | | `filled` | boolean | <optional> | true | Render the body as a filled rectangle (true) or a stroked rectangle (false) | Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 747](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L747)) ### bodyInfo(sprite, x, y, color) Render a Sprites Physic Body information. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `sprite` | [Phaser.Sprite](phaser.sprite) | | | The sprite to be rendered. | | `x` | number | | | X position of the debug info to be rendered. | | `y` | number | | | Y position of the debug info to be rendered. | | `color` | string | <optional> | 'rgb(255,255,255)' | color of the debug info to be rendered. (format is css color string). | Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 781](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L781)) ### <internal> boot() Internal method that boots the debug displayer. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L98)) ### box2dBody(sprite, color) Renders 'debug draw' data for the given Box2D body. This uses the standard debug drawing feature of Box2D, so colors will be decided by the Box2D engine. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `sprite` | [Phaser.Sprite](phaser.sprite) | | | The sprite whos body will be rendered. | | `color` | string | <optional> | 'rgb(0,255,0)' | color of the debug info to be rendered. (format is css color string). | Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 828](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L828)) ### box2dWorld() Renders 'debug draw' data for the Box2D world if it exists. This uses the standard debug drawing feature of Box2D, so colors will be decided by the Box2D engine. Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 810](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L810)) ### cameraInfo(camera, x, y, color) Render camera information including dimensions and location. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `camera` | [Phaser.Camera](phaser.camera) | | | The Phaser.Camera to show the debug information for. | | `x` | number | | | X position of the debug info to be rendered. | | `y` | number | | | Y position of the debug info to be rendered. | | `color` | string | <optional> | 'rgb(255,255,255)' | color of the debug info to be rendered. (format is css color string). | Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 285](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L285)) ### destroy() Destroy this object. Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 877](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L877)) ### geom(object, color, filled) Renders a Rectangle. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `object` | [Phaser.Rectangle](phaser.rectangle) | object | | | The geometry object to render. | | `color` | string | <optional> | | Color of the debug info to be rendered (format is css color string). | | `filled` | boolean | <optional> | true | Render the objected as a filled (default, true) or a stroked (false) | Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 645](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L645)) ### geom(object, color, filled, forceType) Renders a Phaser geometry object including Rectangle, Circle, Point or Line. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `object` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Circle](phaser.circle) | [Phaser.Point](phaser.point) | [Phaser.Line](phaser.line) | | | The geometry object to render. | | `color` | string | <optional> | | Color of the debug info to be rendered (format is css color string). | | `filled` | boolean | <optional> | true | Render the objected as a filled (default, true) or a stroked (false) | | `forceType` | number | <optional> | 0 | Force rendering of a specific type. If 0 no type will be forced, otherwise 1 = Rectangle, 2 = Circle, 3 = Point and 4 = Line. | Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 580](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L580)) ### inputInfo(x, y, color) Render debug information about the Input object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | X position of the debug info to be rendered. | | `y` | number | | | Y position of the debug info to be rendered. | | `color` | string | <optional> | 'rgb(255,255,255)' | color of the debug info to be rendered. (format is css color string). | Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 433](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L433)) ### key(key, x, y, color) Renders Phaser.Key object information. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | [Phaser.Key](phaser.key) | | | The Key to render the information for. | | `x` | number | | | X position of the debug info to be rendered. | | `y` | number | | | Y position of the debug info to be rendered. | | `color` | string | <optional> | 'rgb(255,255,255)' | color of the debug info to be rendered. (format is css color string). | Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 412](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L412)) ### <internal> line() Internal method that outputs a single line of text split over as many columns as needed, one per parameter. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 226](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L226)) ### lineInfo(line, x, y, color) Renders Line information in the given color. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `line` | [Phaser.Line](phaser.line) | | | The Line to display the data for. | | `x` | number | | | X position of the debug info to be rendered. | | `y` | number | | | Y position of the debug info to be rendered. | | `color` | string | <optional> | 'rgb(255,255,255)' | color of the debug info to be rendered. (format is css color string). | Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 541](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L541)) ### pixel(x, y, color, size) Renders a single pixel at the given size. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | X position of the pixel to be rendered. | | `y` | number | | | Y position of the pixel to be rendered. | | `color` | string | <optional> | | Color of the pixel (format is css color string). | | `size` | number | <optional> | 2 | The 'size' to render the pixel at. | Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 560](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L560)) ### pointer(pointer, hideIfUp, downColor, upColor, color) Renders the Pointer.circle object onto the stage in green if down or red if up along with debug text. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `pointer` | [Phaser.Pointer](phaser.pointer) | | | The Pointer you wish to display. | | `hideIfUp` | boolean | <optional> | false | Doesn't render the circle if the pointer is up. | | `downColor` | string | <optional> | 'rgba(0,255,0,0.5)' | The color the circle is rendered in if down. | | `upColor` | string | <optional> | 'rgba(255,0,0,0.5)' | The color the circle is rendered in if up (and hideIfUp is false). | | `color` | string | <optional> | 'rgb(255,255,255)' | color of the debug info to be rendered. (format is css color string). | Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 331](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L331)) ### <internal> preUpdate() Internal method that clears the canvas (if a Sprite) ready for a new debug session. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 143](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L143)) ### quadTree(quadtree, color) Visually renders a QuadTree to the display. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `quadtree` | [Phaser.QuadTree](phaser.quadtree) | The quadtree to render. | | `color` | string | The color of the lines in the quadtree. | Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 707](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L707)) ### reset() Clears the Debug canvas. Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 162](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L162)) ### <internal> resize(scaleManager, width, height) Internal method that resizes the BitmapData and Canvas. Called by ScaleManager.onSizeChange only in WebGL mode. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `scaleManager` | [Phaser.ScaleManager](phaser.scalemanager) | The Phaser ScaleManager. | | `width` | number | The new width of the game. | | `height` | number | The new height of the game. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L124)) ### ropeSegments(rope, color, filled) Renders the Rope's segments. Note: This is really expensive as it has to calculate new segments every time you call it ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `rope` | [Phaser.Rope](phaser.rope) | | | The rope to display the segments of. | | `color` | string | <optional> | | Color of the debug info to be rendered (format is css color string). | | `filled` | boolean | <optional> | true | Render the rectangle as a fillRect (default, true) or a strokeRect (false) | Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 472](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L472)) ### soundInfo(sound, x, y, color) Render Sound information, including decoded state, duration, volume and more. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `sound` | [Phaser.Sound](phaser.sound) | | | The sound object to debug. | | `x` | number | | | X position of the debug info to be rendered. | | `y` | number | | | Y position of the debug info to be rendered. | | `color` | string | <optional> | 'rgb(255,255,255)' | color of the debug info to be rendered. (format is css color string). | Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 254](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L254)) ### spriteBounds(sprite, color, filled) Renders the Sprites bounds. Note: This is really expensive as it has to calculate the bounds every time you call it! ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `sprite` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | | | The sprite to display the bounds of. | | `color` | string | <optional> | | Color of the debug info to be rendered (format is css color string). | | `filled` | boolean | <optional> | true | Render the rectangle as a fillRect (default, true) or a strokeRect (false) | Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 453](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L453)) ### spriteCoords(sprite, x, y, color) Renders the sprite coordinates in local, positional and world space. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `sprite` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | | | The sprite to display the coordinates for. | | `x` | number | | | X position of the debug info to be rendered. | | `y` | number | | | Y position of the debug info to be rendered. | | `color` | string | <optional> | 'rgb(255,255,255)' | color of the debug info to be rendered. (format is css color string). | Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 515](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L515)) ### spriteInfo(sprite, x, y, color) Render debug infos (including name, bounds info, position and some other properties) about the Sprite. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `sprite` | [Phaser.Sprite](phaser.sprite) | | | The Sprite to display the information of. | | `x` | number | | | X position of the debug info to be rendered. | | `y` | number | | | Y position of the debug info to be rendered. | | `color` | string | <optional> | 'rgb(255,255,255)' | color of the debug info to be rendered. (format is css color string). | Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 492](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L492)) ### spriteInputInfo(sprite, x, y, color) Render Sprite Input Debug information. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `sprite` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | | | The sprite to display the input data for. | | `x` | number | | | X position of the debug info to be rendered. | | `y` | number | | | Y position of the debug info to be rendered. | | `color` | string | <optional> | 'rgb(255,255,255)' | color of the debug info to be rendered. (format is css color string). | Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 391](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L391)) ### <internal> start(x, y, color, columnWidth) Internal method that resets and starts the debug output values. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | <optional> | 0 | The X value the debug info will start from. | | `y` | number | <optional> | 0 | The Y value the debug info will start from. | | `color` | string | <optional> | 'rgb(255,255,255)' | The color the debug text will drawn in. | | `columnWidth` | number | <optional> | 0 | The spacing between columns. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 181](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L181)) ### <internal> stop() Internal method that stops the debug output. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 214](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L214)) ### text(text, x, y, color, font) Render a string of text. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `text` | string | | The line of text to draw. | | `x` | number | | X position of the debug info to be rendered. | | `y` | number | | Y position of the debug info to be rendered. | | `color` | string | <optional> | Color of the debug info to be rendered (format is css color string). | | `font` | string | <optional> | The font of text to draw. | Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 676](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L676)) ### timer(timer, x, y, color) Render Timer information. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `timer` | [Phaser.Timer](phaser.timer) | | | The Phaser.Timer to show the debug information for. | | `x` | number | | | X position of the debug info to be rendered. | | `y` | number | | | Y position of the debug info to be rendered. | | `color` | string | <optional> | 'rgb(255,255,255)' | color of the debug info to be rendered. (format is css color string). | Source code: [utils/Debug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js) ([Line 312](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Debug.js#L312))
programming_docs
phaser Class: Phaser.Component.Animation Class: Phaser.Component.Animation ================================= Constructor ----------- ### new Animation() The Animation Component provides a `play` method, which is a proxy to the `AnimationManager.play` method. Source code: [gameobjects/components/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Animation.js) ([Line 12](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Animation.js#L12)) Public Methods -------------- ### play(name, frameRate, loop, killOnComplete) → {[Phaser.Animation](phaser.animation)} Plays an Animation. The animation should have previously been created via `animations.add`. If the animation is already playing calling this again won't do anything. If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `name` | string | | | The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'. | | `frameRate` | number | <optional> | null | The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. | | `loop` | boolean | <optional> | false | Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. | | `killOnComplete` | boolean | <optional> | false | If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. | ##### Returns [Phaser.Animation](phaser.animation) - A reference to playing Animation. Source code: [gameobjects/components/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Animation.js) ([Line 31](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Animation.js#L31)) phaser Class: Phaser.Color Class: Phaser.Color =================== Constructor ----------- ### new Color() The Phaser.Color class is a set of static methods that assist in color manipulation and conversion. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 12](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L12)) Public Methods -------------- ### <static> blendAdd(a, b) → {integer} Adds the source and backdrop colors together and returns the value, up to a maximum of 255. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1058](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1058)) ### <static> blendAverage(a, b) → {integer} Takes the average of the source and backdrop colors. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1045](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1045)) ### <static> blendColorBurn(a, b) → {integer} Darkens the backdrop color to reflect the source color. Painting with white produces no change. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1217)) ### <static> blendColorDodge(a, b) → {integer} Brightens the backdrop color to reflect the source color. Painting with black produces no change. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1203](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1203)) ### <static> blendDarken(a, b) → {integer} Selects the darker of the backdrop and source colors. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1016](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1016)) ### <static> blendDifference(a, b) → {integer} Subtracts the darker of the two constituent colors from the lighter. Painting with white inverts the backdrop color; painting with black produces no change. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1084](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1084)) ### <static> blendExclusion(a, b) → {integer} Produces an effect similar to that of the Difference mode, but lower in contrast. Painting with white inverts the backdrop color; painting with black produces no change. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1127](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1127)) ### <static> blendGlow(a, b) → {integer} Glow blend mode. This mode is a variation of reflect mode with the source and backdrop colors swapped. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1331](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1331)) ### <static> blendHardLight(a, b) → {integer} Multiplies or screens the colors, depending on the source color value. If the source color is lighter than 0.5, the backdrop is lightened, as if it were screened; this is useful for adding highlights to a scene. If the source color is darker than 0.5, the backdrop is darkened, as if it were multiplied; this is useful for adding shadows to a scene. The degree of lightening or darkening is proportional to the difference between the source color and 0.5; if it is equal to 0.5, the backdrop is unchanged. Painting with pure black or white produces pure black or white. The effect is similar to shining a harsh spotlight on the backdrop. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1179](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1179)) ### <static> blendHardMix(a, b) → {integer} Runs blendVividLight on the source and backdrop colors. If the resulting color is 128 or more, it receives a value of 255; if less than 128, a value of 0. Therefore, all blended pixels have red, green, and blue channel values of either 0 or 255. This changes all pixels to primary additive colors (red, green, or blue), white, or black. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1302](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1302)) ### <static> blendLighten(a, b) → {integer} Selects the lighter of the backdrop and source colors. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1003](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1003)) ### <static> blendLinearBurn(a, b) → {integer} An alias for blendSubtract, it simply sums the values of the two colors and subtracts 255. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1244](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1244)) ### <static> blendLinearDodge(a, b) → {integer} An alias for blendAdd, it simply sums the values of the two colors. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1231](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1231)) ### <static> blendLinearLight(a, b) → {integer} This blend mode combines Linear Dodge and Linear Burn (rescaled so that neutral colors become middle gray). Dodge applies to values of top layer lighter than middle gray, and burn to darker values. The calculation simplifies to the sum of bottom layer and twice the top layer, subtract 128. The contrast decreases. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1257](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1257)) ### <static> blendMultiply(a, b) → {integer} Multiplies the backdrop and source color values. The result color is always at least as dark as either of the two constituent colors. Multiplying any color with black produces black; multiplying with white leaves the original color unchanged. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1029](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1029)) ### <static> blendNegation(a, b) → {integer} Negation blend mode. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1099](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1099)) ### <static> blendNormal(a, b) → {integer} Blends the source color, ignoring the backdrop. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 990](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L990)) ### <static> blendOverlay(a, b) → {integer} Multiplies or screens the colors, depending on the backdrop color. Source colors overlay the backdrop while preserving its highlights and shadows. The backdrop color is not replaced, but is mixed with the source color to reflect the lightness or darkness of the backdrop. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1141](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1141)) ### <static> blendPhoenix(a, b) → {integer} Phoenix blend mode. This subtracts the lighter color from the darker color, and adds 255, giving a bright result. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1344](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1344)) ### <static> blendPinLight(a, b) → {integer} If the backdrop color (light source) is lighter than 50%, the blendDarken mode is used, and colors lighter than the backdrop color do not change. If the backdrop color is darker than 50% gray, colors lighter than the blend color are replaced, and colors darker than the blend color do not change. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1288](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1288)) ### <static> blendReflect(a, b) → {integer} Reflect blend mode. This mode is useful when adding shining objects or light zones to images. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1318](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1318)) ### <static> blendScreen(a, b) → {integer} Multiplies the complements of the backdrop and source color values, then complements the result. The result color is always at least as light as either of the two constituent colors. Screening any color with white produces white; screening with black leaves the original color unchanged. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1112)) ### <static> blendSoftLight(a, b) → {integer} Darkens or lightens the colors, depending on the source color value. If the source color is lighter than 0.5, the backdrop is lightened, as if it were dodged; this is useful for adding highlights to a scene. If the source color is darker than 0.5, the backdrop is darkened, as if it were burned in. The degree of lightening or darkening is proportional to the difference between the source color and 0.5; if it is equal to 0.5, the backdrop is unchanged. Painting with pure black or white produces a distinctly darker or lighter area, but does not result in pure black or white. The effect is similar to shining a diffused spotlight on the backdrop. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1156](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1156)) ### <static> blendSubtract(a, b) → {integer} Combines the source and backdrop colors and returns their value minus 255. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1071](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1071)) ### <static> blendVividLight(a, b) → {integer} This blend mode combines Color Dodge and Color Burn (rescaled so that neutral colors become middle gray). Dodge applies when values in the top layer are lighter than middle gray, and burn to darker values. The middle gray is the neutral color. When color is lighter than this, this effectively moves the white point of the bottom layer down by twice the difference; when it is darker, the black point is moved up by twice the difference. The perceived contrast increases. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | integer | The source color to blend, in the range 1 to 255. | | `b` | integer | The backdrop color to blend, in the range 1 to 255. | ##### Returns integer - The blended color value, in the range 1 to 255. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 1272](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L1272)) ### <static> componentToHex(color) → {string} Return a string containing a hex representation of the given color component. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `color` | number | The color channel to get the hex value for, must be a value between 0 and 255. | ##### Returns string - A string of length 2 characters, i.e. 255 = ff, 100 = 64. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 694](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L694)) ### <static> createColor(r, g, b, a, h, s, l, v) → {object} A utility function to create a lightweight 'color' object with the default components. Any components that are not specified will default to zero. This is useful when you want to use a shared color object for the getPixel and getPixelAt methods. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `r` | number | <optional> | 0 | The red color component, in the range 0 - 255. | | `g` | number | <optional> | 0 | The green color component, in the range 0 - 255. | | `b` | number | <optional> | 0 | The blue color component, in the range 0 - 255. | | `a` | number | <optional> | 1 | The alpha color component, in the range 0 - 1. | | `h` | number | <optional> | 0 | The hue, in the range 0 - 1. | | `s` | number | <optional> | 0 | The saturation, in the range 0 - 1. | | `l` | number | <optional> | 0 | The lightness, in the range 0 - 1. | | `v` | number | <optional> | 0 | The value, in the range 0 - 1. | ##### Returns object - The resulting object with r, g, b, a properties and h, s, l and v. Author: * Matt DesLauriers (@mattdesl) Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 438](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L438)) ### <static> fromRGBA(rgba, out) → {object} A utility to convert an integer in 0xRRGGBBAA format to a color object. This does not rely on endianness. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `rgba` | number | | An RGBA hex | | `out` | object | <optional> | The object to use, optional. | ##### Returns object - A color object. Author: * Matt DesLauriers (@mattdesl) Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 97](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L97)) ### <static> getAlpha(color) → {number} Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `color` | number | In the format 0xAARRGGBB. | ##### Returns number - The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 930](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L930)) ### <static> getAlphaFloat(color) → {number} Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `color` | number | In the format 0xAARRGGBB. | ##### Returns number - The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 942](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L942)) ### <static> getBlue(color) → {number} Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `color` | number | In the format 0xAARRGGBB. | ##### Returns number - The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue). Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 978](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L978)) ### <static> getColor(r, g, b) → {number} Given 3 color values this will return an integer representation of it. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `r` | number | The red color component, in the range 0 - 255. | | `g` | number | The green color component, in the range 0 - 255. | | `b` | number | The blue color component, in the range 0 - 255. | ##### Returns number - A native color value integer (format: 0xRRGGBB). Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 500](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L500)) ### <static> getColor32(a, r, g, b) → {number} Given an alpha and 3 color values this will return an integer representation of it. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | number | The alpha color component, in the range 0 - 255. | | `r` | number | The red color component, in the range 0 - 255. | | `g` | number | The green color component, in the range 0 - 255. | | `b` | number | The blue color component, in the range 0 - 255. | ##### Returns number - A native color value integer (format: 0xAARRGGBB). Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 483](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L483)) ### <static> getGreen(color) → {number} Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `color` | number | In the format 0xAARRGGBB. | ##### Returns number - The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green). Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 966](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L966)) ### <static> getRandomColor(min, max, alpha) → {number} Returns a random color value between black and white Set the min value to start each channel from the given offset. Set the max value to restrict the maximum color used per channel. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `min` | number | <optional> | 0 | The lowest value to use for the color. | | `max` | number | <optional> | 255 | The highest value to use for the color. | | `alpha` | number | <optional> | 255 | The alpha value of the returning color (default 255 = fully opaque). | ##### Returns number - 32-bit color value with alpha. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 834](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L834)) ### <static> getRed(color) → {number} Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `color` | number | In the format 0xAARRGGBB. | ##### Returns number - The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red). Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 954](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L954)) ### <static> getRGB(color) → {object} Return the component parts of a color as an Object with the properties alpha, red, green, blue. Alpha will only be set if it exist in the given color (0xAARRGGBB) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `color` | number | Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB). | ##### Returns object - An Object with properties: alpha, red, green, blue (also r, g, b and a). Alpha will only be present if a color value > 16777215 was given. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 866](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L866)) ### <static> getWebRGB(color) → {string} Returns a CSS friendly string value from the given color. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `color` | number | Object | Color in RGB (0xRRGGBB), ARGB format (0xAARRGGBB) or an Object with r, g, b, a properties. | ##### Returns string - A string in the format: 'rgba(r,g,b,a)' Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 908](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L908)) ### <static> hexToColor(hex, out) → {object} Converts a hex string into a Phaser Color object. The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional "#" or "0x", or be unprefixed. An alpha channel is *not* supported. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `hex` | string | | The color string in a hex format. | | `out` | object | <optional> | An object into which 3 properties will be created or set: r, g and b. If not provided a new object will be created. | ##### Returns object - An object with the red, green and blue values set in the r, g and b properties. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 564](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L564)) ### <static> hexToRGB(hex) → {number} Converts a hex string into an integer color value. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `hex` | string | The hex string to convert. Can be in the short-hand format `#03f` or `#0033ff`. | ##### Returns number - The rgb color value in the format 0xAARRGGBB. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 545](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L545)) ### <static> HSLColorWheel(s, l) → {array} Get HSL color wheel values in an array which will be 360 elements in size. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `s` | number | <optional> | 0.5 | The saturation, in the range 0 - 1. | | `l` | number | <optional> | 0.5 | The lightness, in the range 0 - 1. | ##### Returns array - An array containing 360 elements corresponding to the HSL color wheel. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 735](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L735)) ### <static> HSLtoRGB(h, s, l, out) → {object} Converts an HSL (hue, saturation and lightness) color value to RGB. Conversion forumla from http://en.wikipedia.org/wiki/HSL\_color\_space. Assumes HSL values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. Based on code by Michael Jackson (https://github.com/mjijackson) ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `h` | number | | The hue, in the range 0 - 1. | | `s` | number | | The saturation, in the range 0 - 1. | | `l` | number | | The lightness, in the range 0 - 1. | | `out` | object | <optional> | An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. | ##### Returns object - An object with the red, green and blue values set in the r, g and b properties. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 220](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L220)) ### <static> HSVColorWheel(s, v) → {array} Get HSV color wheel values in an array which will be 360 elements in size. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `s` | number | <optional> | 1 | The saturation, in the range 0 - 1. | | `v` | number | <optional> | 1 | The value, in the range 0 - 1. | ##### Returns array - An array containing 360 elements corresponding to the HSV color wheel. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 710](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L710)) ### <static> HSVtoRGB(h, s, v, out) → {object} Converts an HSV (hue, saturation and value) color value to RGB. Conversion forumla from http://en.wikipedia.org/wiki/HSL\_color\_space. Assumes HSV values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. Based on code by Michael Jackson (https://github.com/mjijackson) ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `h` | number | | The hue, in the range 0 - 1. | | `s` | number | | The saturation, in the range 0 - 1. | | `v` | number | | The value, in the range 0 - 1. | | `out` | object | <optional> | An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. | ##### Returns object - An object with the red, green and blue values set in the r, g and b properties. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 327](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L327)) ### <static> hueToColor(p, q, t) → {number} Converts a hue to an RGB color. Based on code by Michael Jackson (https://github.com/mjijackson) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `p` | number | | | `q` | number | | | `t` | number | | ##### Returns number - The color component value. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 396](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L396)) ### <static> interpolateColor(color1, color2, steps, currentStep, alpha) → {number} Interpolates the two given colours based on the supplied step and currentStep properties. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `color1` | number | The first color value. | | `color2` | number | The second color value. | | `steps` | number | The number of steps to run the interpolation over. | | `currentStep` | number | The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. | | `alpha` | number | The alpha of the returned color. | ##### Returns number - The interpolated color value. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 760](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L760)) ### <static> interpolateColorWithRGB(color, r, g, b, steps, currentStep) → {number} Interpolates the two given colours based on the supplied step and currentStep properties. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `color` | number | The first color value. | | `r` | number | The red color value, between 0 and 0xFF (255). | | `g` | number | The green color value, between 0 and 0xFF (255). | | `b` | number | The blue color value, between 0 and 0xFF (255). | | `steps` | number | The number of steps to run the interpolation over. | | `currentStep` | number | The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. | ##### Returns number - The interpolated color value. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 786](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L786)) ### <static> interpolateRGB(r1, g1, b1, r2, g2, b2, steps, currentStep) → {number} Interpolates the two given colours based on the supplied step and currentStep properties. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `r1` | number | The red color value, between 0 and 0xFF (255). | | `g1` | number | The green color value, between 0 and 0xFF (255). | | `b1` | number | The blue color value, between 0 and 0xFF (255). | | `r2` | number | The red color value, between 0 and 0xFF (255). | | `g2` | number | The green color value, between 0 and 0xFF (255). | | `b2` | number | The blue color value, between 0 and 0xFF (255). | | `steps` | number | The number of steps to run the interpolation over. | | `currentStep` | number | The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. | ##### Returns number - The interpolated color value. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 810](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L810)) ### <static> packPixel(r, g, b, a) → {number} Packs the r, g, b, a components into a single integer, for use with Int32Array. If device is little endian then ABGR order is used. Otherwise RGBA order is used. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `r` | number | The red color component, in the range 0 - 255. | | `g` | number | The green color component, in the range 0 - 255. | | `b` | number | The blue color component, in the range 0 - 255. | | `a` | number | The alpha color component, in the range 0 - 255. | ##### Returns number - The packed color as uint32 Author: * Matt DesLauriers (@mattdesl) Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 14](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L14)) ### <static> RGBtoHSL(r, g, b, out) → {object} Converts an RGB color value to HSL (hue, saturation and lightness). Conversion forumla from http://en.wikipedia.org/wiki/HSL\_color\_space. Assumes RGB values are contained in the set [0, 255] and returns h, s and l in the set [0, 1]. Based on code by Michael Jackson (https://github.com/mjijackson) ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `r` | number | | The red color component, in the range 0 - 255. | | `g` | number | | The green color component, in the range 0 - 255. | | `b` | number | | The blue color component, in the range 0 - 255. | | `out` | object | <optional> | An object into which 3 properties will be created, h, s and l. If not provided a new object will be created. | ##### Returns object - An object with the hue, saturation and lightness values set in the h, s and l properties. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 161](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L161)) ### <static> RGBtoHSV(r, g, b, out) → {object} Converts an RGB color value to HSV (hue, saturation and value). Conversion forumla from http://en.wikipedia.org/wiki/HSL\_color\_space. Assumes RGB values are contained in the set [0, 255] and returns h, s and v in the set [0, 1]. Based on code by Michael Jackson (https://github.com/mjijackson) ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `r` | number | | The red color component, in the range 0 - 255. | | `g` | number | | The green color component, in the range 0 - 255. | | `b` | number | | The blue color component, in the range 0 - 255. | | `out` | object | <optional> | An object into which 3 properties will be created, h, s and v. If not provided a new object will be created. | ##### Returns object - An object with the hue, saturation and value set in the h, s and v properties. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 271](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L271)) ### <static> RGBtoString(r, g, b, a, prefix) → {string} Converts the given color values into a string. If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `r` | number | | | The red color component, in the range 0 - 255. | | `g` | number | | | The green color component, in the range 0 - 255. | | `b` | number | | | The blue color component, in the range 0 - 255. | | `a` | number | <optional> | 255 | The alpha color component, in the range 0 - 255. | | `prefix` | string | <optional> | '#' | The prefix used in the return string. If '#' it will return `#RRGGBB`, else `0xAARRGGBB`. | ##### Returns string - A string containing the color values. If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 516](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L516)) ### <static> toABGR(r, g, b, a) → {number} Converts RGBA components to a 32 bit integer in AABBGGRR format. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `r` | number | The red color component, in the range 0 - 255. | | `g` | number | The green color component, in the range 0 - 255. | | `b` | number | The blue color component, in the range 0 - 255. | | `a` | number | The alpha color component, in the range 0 - 255. | ##### Returns number - A RGBA-packed 32 bit integer Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 144](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L144)) ### <static> toRGBA(r, g, b, a) → {number} A utility to convert RGBA components to a 32 bit integer in RRGGBBAA format. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `r` | number | The red color component, in the range 0 - 255. | | `g` | number | The green color component, in the range 0 - 255. | | `b` | number | The blue color component, in the range 0 - 255. | | `a` | number | The alpha color component, in the range 0 - 255. | ##### Returns number - A RGBA-packed 32 bit integer Author: * Matt DesLauriers (@mattdesl) Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 126](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L126)) ### <static> unpackPixel(rgba, out, hsl, hsv) → {object} Unpacks the r, g, b, a components into the specified color object, or a new object, for use with Int32Array. If little endian, then ABGR order is used when unpacking, otherwise, RGBA order is used. The resulting color object has the `r, g, b, a` properties which are unrelated to endianness. Note that the integer is assumed to be packed in the correct endianness. On little-endian the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. If you want a endian-independent method, use fromRGBA(rgba) and toRGBA(r, g, b, a). ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `rgba` | number | | | The integer, packed in endian order by packPixel. | | `out` | object | <optional> | | An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. | | `hsl` | boolean | <optional> | false | Also convert the rgb values into hsl? | | `hsv` | boolean | <optional> | false | Also convert the rgb values into hsv? | ##### Returns object - An object with the red, green and blue values set in the r, g and b properties. Author: * Matt DesLauriers (@mattdesl) Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 40](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L40)) ### <static> updateColor(out) → {number} Takes a color object and updates the rgba, color and color32 properties. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `out` | object | The color object to update. | ##### Returns number - A native color value integer (format: 0xAARRGGBB). Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 465](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L465)) ### <static> valueToColor(value, out) → {object} Converts a value - a "hex" string, a "CSS 'web' string", or a number - into red, green, blue, and alpha components. The value can be a string (see `hexToColor` and `webToColor` for the supported formats) or a packed integer (see `getRGB`). An alpha channel is *not* supported when specifying a hex string. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `value` | string | number | | The color expressed as a recognized string format or a packed integer. | | `out` | object | <optional> | The object to use for the output. If not provided a new object will be created. | ##### Returns object - The (`out`) object with the red, green, blue, and alpha values set as the r/g/b/a properties. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 641](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L641)) ### <static> webToColor(web, out) → {object} Converts a CSS 'web' string into a Phaser Color object. The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1]. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `web` | string | | The color string in CSS 'web' format. | | `out` | object | <optional> | An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. | ##### Returns object - An object with the red, green, blue and alpha values set in the r, g, b and a properties. Source code: [utils/Color.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js) ([Line 608](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/Color.js#L608))
programming_docs
phaser Class: Phaser.SoundManager Class: Phaser.SoundManager ========================== Constructor ----------- ### new SoundManager(game) The Sound Manager is responsible for playing back audio via either the Legacy HTML Audio tag or via Web Audio if the browser supports it. Note: On Firefox 25+ on Linux if you have media.gstreamer disabled in about:config then it cannot play back mp3 or m4a files. The audio file type and the encoding of those files are extremely important. Not all browsers can play all audio formats. There is a good guide to what's supported here: http://hpr.dogphilosophy.net/test/ If you are reloading a Phaser Game on a page that never properly refreshes (such as in an AngularJS project) then you will quickly run out of AudioContext nodes. If this is the case create a global var called PhaserGlobal on the window object before creating the game. The active AudioContext will then be saved to window.PhaserGlobal.audioContext when the Phaser game is destroyed, and re-used when it starts again. Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio. When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system. The solution is to use a lower encoding rate such as 44100 Hz. Sometimes the audio context will be created with a sampleRate of 48000. If this happens and audio distorts you should re-create the context. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | Reference to the current game instance. | Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L26)) Public Properties ----------------- ### channels : number The number of audio channels to use in playback. Default Value * 32 Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 96](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L96)) ### connectToMaster : boolean Used in conjunction with Sound.externalNode this allows you to stop a Sound node being connected to the SoundManager master gain node. Default Value * true Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 84](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L84)) ### context :AudioContext The AudioContext being used for playback. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 60](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L60)) ### game : [Phaser.Game](phaser.game) Local reference to game. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 31](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L31)) ### mute : boolean Gets or sets the muted state of the SoundManager. This effects all sounds in the game. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 765](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L765)) ### muteOnPause : boolean Set to true to have all sound muted when the Phaser game pauses (such as on loss of focus), or set to false to keep audio playing, regardless of the game pause state. You may need to do this should you wish to control audio muting via external DOM buttons or similar. Default Value * true Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 105](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L105)) ### noAudio : boolean True if audio been disabled via the PhaserGlobal (useful if you need to use a 3rd party audio library) or the device doesn't support any audio. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L78)) ### onMute : [Phaser.Signal](phaser.signal) This signal is dispatched when the SoundManager is globally muted, either directly via game code or as a result of the game pausing. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 48](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L48)) ### onSoundDecode : [Phaser.Signal](phaser.signal) The event dispatched when a sound decodes (typically only for mp3 files) Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 36](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L36)) ### onUnMute : [Phaser.Signal](phaser.signal) This signal is dispatched when the SoundManager is globally un-muted, either directly via game code or as a result of the game resuming from a pause. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L54)) ### onVolumeChange : [Phaser.Signal](phaser.signal) This signal is dispatched whenever the global volume changes. The new volume is passed as the only parameter to your callback. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L42)) ### touchLocked : boolean true if the audio system is currently locked awaiting a touch event. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 90](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L90)) ### [readonly] usingAudioTag : boolean True the SoundManager and device are both using the Audio tag instead of Web Audio. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 72](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L72)) ### [readonly] usingWebAudio : boolean True the SoundManager and device are both using Web Audio. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 66](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L66)) ### volume : number Gets or sets the global volume of the SoundManager, a value between 0 and 1. The value given is clamped to the range 0 to 1. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 805](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L805)) Public Methods -------------- ### add(key, volume, loop, connect) → {[Phaser.Sound](phaser.sound)} Adds a new Sound into the SoundManager. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Asset key for the sound. | | `volume` | number | <optional> | 1 | Default value for the volume. | | `loop` | boolean | <optional> | false | Whether or not the sound will loop. | | `connect` | boolean | <optional> | true | Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. | ##### Returns [Phaser.Sound](phaser.sound) - The new sound instance. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 540](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L540)) ### addSprite(key) → {[Phaser.AudioSprite](phaser.audiosprite)} Adds a new AudioSprite into the SoundManager. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | Asset key for the sound. | ##### Returns [Phaser.AudioSprite](phaser.audiosprite) - The new AudioSprite instance. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 564](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L564)) ### <internal> boot() Initialises the sound manager. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 169](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L169)) ### decode(key, sound) Decode a sound by its asset key. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `key` | string | | Assets key of the sound to be decoded. | | `sound` | [Phaser.Sound](phaser.sound) | <optional> | Its buffer will be set to decoded data. | Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 406](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L406)) ### destroy() Stops all the sounds in the game, then destroys them and finally clears up any callbacks. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 722](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L722)) ### pauseAll() Pauses all the sounds in the game. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 362](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L362)) ### play(key, volume, loop) → {[Phaser.Sound](phaser.sound)} Adds a new Sound into the SoundManager and starts it playing. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | Asset key for the sound. | | `volume` | number | <optional> | 1 | Default value for the volume. | | `loop` | boolean | <optional> | false | Whether or not the sound will loop. | ##### Returns [Phaser.Sound](phaser.sound) - The new sound instance. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 631](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L631)) ### remove(sound) → {boolean} Removes a Sound from the SoundManager. The removed Sound is destroyed before removal. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `sound` | [Phaser.Sound](phaser.sound) | The sound object to remove. | ##### Returns boolean - True if the sound was removed successfully, otherwise false. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 579](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L579)) ### removeByKey(key) → {number} Removes all Sounds from the SoundManager that have an asset key matching the given value. The removed Sounds are destroyed before removal. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key to match when removing sound objects. | ##### Returns number - The number of matching sound objects that were removed. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 604](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L604)) ### resumeAll() Resumes every sound in the game. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 384](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L384)) ### setDecodedCallback(files, callback, callbackContext) This method allows you to give the SoundManager a list of Sound files, or keys, and a callback. Once all of the Sound files have finished decoding the callback will be invoked. The amount of time spent decoding depends on the codec used and file size. If all of the files given have already decoded the callback is triggered immediately. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `files` | string | array | An array containing either Phaser.Sound objects or their key strings as found in the Phaser.Cache. | | `callback` | function | The callback which will be invoked once all files have finished decoding. | | `callbackContext` | Object | The context in which the callback will run. | Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 443](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L443)) ### setTouchLock() Sets the Input Manager touch callback to be SoundManager.unlock. Required for iOS audio device unlocking. Mostly just used internally. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 270](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L270)) ### stopAll() Stops all the sounds in the game. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 340](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L340)) ### unlock() → {boolean} Enables the audio, usually after the first touch. ##### Returns boolean - True if the callback should be removed, otherwise false. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 296](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L296)) ### <internal> update() Updates every sound in the game, checks for audio unlock on mobile and monitors the decoding watch list. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [sound/SoundManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js) ([Line 493](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/SoundManager.js#L493)) phaser Class: Phaser.Component.Core Class: Phaser.Component.Core ============================ Constructor ----------- ### new Core() Core Component Features. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 12](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L12)) Public Properties ----------------- ### animations : [Phaser.AnimationManager](phaser.animationmanager) If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. Through it you can create, play, pause and stop animations. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 193](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L193)) See * [Phaser.AnimationManager](phaser.animationmanager) ### <internal> components : Object The components this Game Object has installed. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 167](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L167)) ### data : Object An empty Object that belongs to this Game Object. This value isn't ever used internally by Phaser, but may be used by your own code, or by Phaser Plugins, to store data that needs to be associated with the Game Object, without polluting the Game Object directly. Default Value * {} Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 160](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L160)) ### debug : boolean A debug flag designed for use with `Game.enableStep`. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 218](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L218)) ### events : [Phaser.Events](phaser.events) All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this Game Object, or any of its components. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 185](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L185)) See * [Phaser.Events](phaser.events) ### exists : boolean Controls if this Game Object is processed by the core game loop. If this Game Object has a physics body it also controls if its physics body is updated or not. When `exists` is set to `false` it will remove its physics body from the physics world if it has one. It also toggles the `visible` property to false as well. Setting `exists` to true will add its physics body back in to the physics world, if it has one. It will also set the `visible` property to `true`. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 284](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L284)) ### [readonly] fresh : boolean A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. This property is mostly used internally by the physics systems, but is exposed for the use of plugins. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 248](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L248)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 142](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L142)) ### key : string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) The key of the image or texture used by this Game Object during rendering. If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. ##### Type * string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 203](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L203)) ### name : string A user defined name given to this Game Object. This value isn't ever used internally by Phaser, it is meant as a game level property. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 150](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L150)) ### pendingDestroy : boolean A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. You can set it directly to allow you to flag an object to be destroyed on its next update. This is extremely useful if you wish to destroy an object from within one of its own callbacks such as with Buttons or other Input events. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 259](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L259)) ### [readonly] previousPosition : [Phaser.Point](phaser.point) The position the Game Object was located in the previous frame. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 225](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L225)) ### [readonly] previousRotation : number The rotation the Game Object was in set to in the previous frame. Value is in radians. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L232)) ### [readonly] renderOrderID : number The render order ID is used internally by the renderer and Input Manager and should not be modified. This property is mostly used internally by the renderers, but is exposed for the use of plugins. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 240](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L240)) ### world : [Phaser.Point](phaser.point) The world coordinates of this Game Object in pixels. Depending on where in the display list this Game Object is placed this value can differ from `position`, which contains the x/y coordinates relative to the Game Objects parent. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 211](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L211)) ### [readonly] z : number The z depth of this Game Object within its parent Group. No two objects in a Group can have the same z value. This value is adjusted automatically whenever the Group hierarchy changes. If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 177](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L177)) Public Methods -------------- ### <internal, static> init() Initializes the mixin components. The `this` context should be an instance of the component mixin target. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L54)) ### <internal, static> install() Installs / registers mixin components. The `this` context should be that of the applicable object instance or prototype. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L22)) ### <internal> postUpdate() Internal method called by the World postUpdate cycle. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 338](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L338)) ### update() Override this method in your own custom objects to handle any update requirements. It is called immediately after `preUpdate` and before `postUpdate`. Remember if this Game Object has any children you should call update on those too. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 328](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L328))
programming_docs
phaser Class: Phaser.Text Class: Phaser.Text ================== Constructor ----------- ### new Text(game, x, y, text, style) Create a new game object for displaying Text. This uses a local hidden Canvas object and renders the type into it. It then makes a texture from this for rendering to the view. Because of this you can only display fonts that are currently loaded and available to the browser: fonts must be pre-loaded. See [this compatibility table](http://www.jordanm.co.uk/tinytype) for the available default fonts across mobile browsers. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | Current game instance. | | `x` | number | | X position of the new text object. | | `y` | number | | Y position of the new text object. | | `text` | string | | The actual text that will be written. | | `style` | object | <optional> | The style properties to be set on the Text. Properties | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `font` | string | <optional> | 'bold 20pt Arial' | The style and size of the font. | | `fontStyle` | string | <optional> | (from font) | The style of the font (eg. 'italic'): overrides the value in `style.font`. | | `fontVariant` | string | <optional> | (from font) | The variant of the font (eg. 'small-caps'): overrides the value in `style.font`. | | `fontWeight` | string | <optional> | (from font) | The weight of the font (eg. 'bold'): overrides the value in `style.font`. | | `fontSize` | string | number | <optional> | (from font) | The size of the font (eg. 32 or '32px'): overrides the value in `style.font`. | | `backgroundColor` | string | <optional> | null | A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable. | | `fill` | string | <optional> | 'black' | A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. | | `align` | string | <optional> | 'left' | Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that). | | `boundsAlignH` | string | <optional> | 'left' | Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. | | `boundsAlignV` | string | <optional> | 'top' | Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. | | `stroke` | string | <optional> | 'black' | A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'. | | `strokeThickness` | number | <optional> | 0 | A number that represents the thickness of the stroke. Default is 0 (no stroke). | | `wordWrap` | boolean | <optional> | false | Indicates if word wrap should be used. | | `wordWrapWidth` | number | <optional> | 100 | The width in pixels at which text will wrap. | | `maxLines` | number | <optional> | 0 | The maximum number of lines to be shown for wrapped text. | | `tabs` | number | <optional> | 0 | The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop. | | Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 40](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L40)) Extends ------- * [Phaser.Sprite](phaser.sprite) Public Properties ----------------- ### align : string Controls the horizontal alignment for multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text. For that please see `setTextBounds`. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 1870](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L1870)) ### alive : boolean A useful flag to control if the Game Object is alive or dead. This is set automatically by the Health components `damage` method should the object run out of health. Or you can toggle it via your game code. This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. Inherited From * [Phaser.Component.LifeSpan#alive](phaser.component.lifespan#alive) Default Value * true Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L50)) ### anchor :Point The anchor sets the origin point of the texture. The default is 0,0 this means the texture's origin is the top left Setting than anchor to 0.5,0.5 means the textures origin is centered Setting the anchor to 1,1 would mean the textures origin points will be the bottom right corner Inherited From * [PIXI.Sprite#anchor](pixi.sprite#anchor) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L17)) ### angle : number The angle property is the rotation of the Game Object in *degrees* from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90. If you wish to work in radians instead of degrees you can use the property `rotation` instead. Working in radians is slightly faster as it doesn't have to perform any calculations. Inherited From * [Phaser.Component.Angle#angle](phaser.component.angle#angle) Source code: [gameobjects/components/Angle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js#L29)) ### animations : [Phaser.AnimationManager](phaser.animationmanager) If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. Through it you can create, play, pause and stop animations. Inherited From * [Phaser.Component.Core#animations](phaser.component.core#animations) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 193](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L193)) See * [Phaser.AnimationManager](phaser.animationmanager) ### autoCull : boolean A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, or you have tested performance and find it acceptable. Inherited From * [Phaser.Component.AutoCull#autoCull](phaser.component.autocull#autoCull) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L28)) ### autoRound : boolean Should the linePositionX and Y values be automatically rounded before rendering the Text? You may wish to enable this if you want to remove the effect of sub-pixel aliasing from text. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 119](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L119)) ### blendMode : number The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode. Warning: You cannot have a blend mode and a filter active on the same Sprite. Doing so will render the sprite invisible. Inherited From * [PIXI.Sprite#blendMode](pixi.sprite#blendMode) Default Value * PIXI.blendModes.NORMAL; Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 82](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L82)) ### body : [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | null `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated properties and methods via it. By default Game Objects won't add themselves to any physics system and their `body` property will be `null`. To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`. You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group. Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5, so the physics body is centered on the Game Object. If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics. ##### Type * [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | null Inherited From * [Phaser.Component.PhysicsBody#body](phaser.component.physicsbody#body) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 91](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L91)) ### bottom : number The sum of the y and height properties. This is the same as `y + height - offsetY`. Inherited From * [Phaser.Component.Bounds#bottom](phaser.component.bounds#bottom) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 168](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L168)) ### boundsAlignH : string Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 1946](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L1946)) ### boundsAlignV : string Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 1969](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L1969)) ### cameraOffset : [Phaser.Point](phaser.point) The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. Inherited From * [Phaser.Component.FixedToCamera#cameraOffset](phaser.component.fixedtocamera#cameraOffset) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L86)) ### canvas :HTMLCanvasElement The canvas element that the text is rendered. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L86)) ### centerX : number The center x coordinate of the Game Object. This is the same as `(x - offsetX) + (width / 2)`. Inherited From * [Phaser.Component.Bounds#centerX](phaser.component.bounds#centerX) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L58)) ### centerY : number The center y coordinate of the Game Object. This is the same as `(y - offsetY) + (height / 2)`. Inherited From * [Phaser.Component.Bounds#centerY](phaser.component.bounds#centerY) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 80](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L80)) ### checkWorldBounds : boolean If this is set to `true` the Game Object checks if it is within the World bounds each frame. When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event. If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event. It also optionally kills the Game Object if `outOfBoundsKill` is `true`. When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame. This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, or you have tested performance and find it acceptable. Inherited From * [Phaser.Component.InWorld#checkWorldBounds](phaser.component.inworld#checkWorldBounds) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L98)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### colors :array An array of the color values as specified by [addColor](phaser.text#addColor). Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 96](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L96)) ### <internal> components : Object The components this Game Object has installed. Inherited From * [Phaser.Component.Core#components](phaser.component.core#components) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 167](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L167)) ### context :HTMLCanvasElement The context of the canvas element that the text is rendered to. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 91](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L91)) ### cropRect : [Phaser.Rectangle](phaser.rectangle) The Rectangle used to crop the texture this Game Object uses. Set this property via `crop`. If you modify this property directly you must call `updateCrop` in order to have the change take effect. Inherited From * [Phaser.Component.Crop#cropRect](phaser.component.crop#cropRect) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L24)) ### cssFont : string Change the font used. This is equivalent of the `font` property specified to [setStyle](phaser.text#setStyle), except that unlike using `setStyle` this will not change any current font fill/color settings. The CSS font string can also be individually altered with the `font`, `fontSize`, `fontWeight`, `fontStyle`, and `fontVariant` properties. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 1682](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L1682)) ### damage Damages the Game Object. This removes the given amount of health from the `health` property. If health is taken below or is equal to zero then the `kill` method is called. Inherited From * [Phaser.Component.Health#damage](phaser.component.health#damage) Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L46)) ### data : Object An empty Object that belongs to this Game Object. This value isn't ever used internally by Phaser, but may be used by your own code, or by Phaser Plugins, to store data that needs to be associated with the Game Object, without polluting the Game Object directly. Inherited From * [Phaser.Component.Core#data](phaser.component.core#data) Default Value * {} Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 160](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L160)) ### debug : boolean A debug flag designed for use with `Game.enableStep`. Inherited From * [Phaser.Component.Core#debug](phaser.component.core#debug) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 218](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L218)) ### [readonly] deltaX : number Returns the delta x value. The difference between world.x now and in the previous frame. The value will be positive if the Game Object has moved to the right or negative if to the left. Inherited From * [Phaser.Component.Delta#deltaX](phaser.component.delta#deltaX) Source code: [gameobjects/components/Delta.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js#L24)) ### [readonly] deltaY : number Returns the delta y value. The difference between world.y now and in the previous frame. The value will be positive if the Game Object has moved down or negative if up. Inherited From * [Phaser.Component.Delta#deltaY](phaser.component.delta#deltaY) Source code: [gameobjects/components/Delta.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js#L42)) ### [readonly] deltaZ : number Returns the delta z value. The difference between rotation now and in the previous frame. The delta value. Inherited From * [Phaser.Component.Delta#deltaZ](phaser.component.delta#deltaZ) Source code: [gameobjects/components/Delta.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js#L58)) ### [readonly] destroyPhase : boolean As a Game Object runs through its destroy method this flag is set to true, and can be checked in any sub-systems or plugins it is being destroyed from. Inherited From * [Phaser.Component.Destroy#destroyPhase](phaser.component.destroy#destroyPhase) Source code: [gameobjects/components/Destroy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js#L22)) ### events : [Phaser.Events](phaser.events) All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this Game Object, or any of its components. Inherited From * [Phaser.Component.Core#events](phaser.component.core#events) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 185](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L185)) See * [Phaser.Events](phaser.events) ### exists : boolean Controls if this Sprite is processed by the core Phaser game loops and Group loops. Inherited From * [PIXI.Sprite#exists](pixi.sprite#exists) Default Value * true Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 103](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L103)) ### fill : Object A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 1848](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L1848)) ### fixedToCamera : boolean A Game Object that is "fixed" to the camera uses its x/y coordinates as offsets from the top left of the camera during rendering. The values are adjusted at the rendering stage, overriding the Game Objects actual world position. The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times regardless where in the world the camera is. The offsets are stored in the `cameraOffset` property. Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. Inherited From * [Phaser.Component.FixedToCamera#fixedToCamera](phaser.component.fixedtocamera#fixedToCamera) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 56](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L56)) ### font : string Change the font family that the text will be rendered in, such as 'Arial'. Multiple CSS font families and generic fallbacks can be specified as long as [CSS font-family rules](http://www.w3.org/TR/CSS2/fonts.html#propdef-font-family) are followed. To change the entire font string use [cssFont](phaser.text#cssFont) instead: eg. `text.cssFont = 'bold 20pt Arial'`. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 1708](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L1708)) ### fontSize : number | string The size of the font. If the font size is specified in pixels (eg. `32` or `'32px`') then a number (ie. `32`) representing the font size in pixels is returned; otherwise the value with CSS unit is returned as a string (eg. `'12pt'`). ##### Type * number | string Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 1743](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L1743)) ### fontStyle : string The style of the font: 'normal', 'italic', 'oblique' Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 1806](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L1806)) ### fontStyles :array An array of the font styles values as specified by [addFontStyle](phaser.text#addFontStyle). Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 106](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L106)) ### fontVariant : string The variant the font: 'normal', 'small-caps' Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 1827](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L1827)) ### fontWeight : string The weight of the font: 'normal', 'bold', or [a valid CSS font weight](http://www.w3.org/TR/CSS2/fonts.html#propdef-font-weight). Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 1785](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L1785)) ### fontWeights :array An array of the font weights values as specified by [addFontWeight](phaser.text#addFontWeight). Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 111](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L111)) ### frame : integer Gets or sets the current frame index of the texture being used to render this Game Object. To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use, for example: `player.frame = 4`. If the frame index given doesn't exist it will revert to the first frame found in the texture. If you are using a texture atlas then you should use the `frameName` property instead. If you wish to fully replace the texture being used see `loadTexture`. Inherited From * [Phaser.Component.LoadTexture#frame](phaser.component.loadtexture#frame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 254](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L254)) ### frameName : string Gets or sets the current frame name of the texture being used to render this Game Object. To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use, for example: `player.frameName = "idle"`. If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning. If you are using a sprite sheet then you should use the `frame` property instead. If you wish to fully replace the texture being used see `loadTexture`. Inherited From * [Phaser.Component.LoadTexture#frameName](phaser.component.loadtexture#frameName) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 279](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L279)) ### [readonly] fresh : boolean A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. This property is mostly used internally by the physics systems, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#fresh](phaser.component.core#fresh) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 248](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L248)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Inherited From * [Phaser.Component.Core#game](phaser.component.core#game) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 142](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L142)) ### heal Heal the Game Object. This adds the given amount of health to the `health` property. Inherited From * [Phaser.Component.Health#heal](phaser.component.health#heal) Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 90](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L90)) ### health : number The Game Objects health value. This is a handy property for setting and manipulating health on a Game Object. It can be used in combination with the `damage` method or modified directly. Inherited From * [Phaser.Component.Health#health](phaser.component.health#health) Default Value * 1 Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L26)) ### height : number The height of the Text. Setting this will modify the scale to achieve the value requested. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 2264](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L2264)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### [readonly] inCamera : boolean Checks if the Game Objects bounds intersect with the Game Camera bounds. Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. Inherited From * [Phaser.Component.AutoCull#inCamera](phaser.component.autocull#inCamera) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L37)) ### input : [Phaser.InputHandler](phaser.inputhandler) | null The Input Handler for this Game Object. By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`. After you have done this, this property will be a reference to the Phaser InputHandler. ##### Type * [Phaser.InputHandler](phaser.inputhandler) | null Inherited From * [Phaser.Component.InputEnabled#input](phaser.component.inputenabled#input) Source code: [gameobjects/components/InputEnabled.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js#L24)) ### inputEnabled : boolean By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created for this Game Object and it will then start to process click / touch events and more. You can then access the Input Handler via `this.input`. Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`. If you set this property to false it will stop the Input Handler from processing any more input events. If you want to *temporarily* disable input for a Game Object, then it's better to set `input.enabled = false`, as it won't reset any of the Input Handlers internal properties. You can then toggle this back on as needed. Inherited From * [Phaser.Component.InputEnabled#inputEnabled](phaser.component.inputenabled#inputEnabled) Source code: [gameobjects/components/InputEnabled.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js#L42)) ### [readonly] inWorld : boolean Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds. Inherited From * [Phaser.Component.InWorld#inWorld](phaser.component.inworld#inWorld) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 129](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L129)) ### key : string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) The key of the image or texture used by this Game Object during rendering. If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. ##### Type * string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) Inherited From * [Phaser.Component.Core#key](phaser.component.core#key) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 203](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L203)) ### left : number The left coordinate of the Game Object. This is the same as `x - offsetX`. Inherited From * [Phaser.Component.Bounds#left](phaser.component.bounds#left) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 102](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L102)) ### lifespan : number The lifespan allows you to give a Game Object a lifespan in milliseconds. Once the Game Object is 'born' you can set this to a positive value. It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. When it reaches zero it will call the `kill` method. Very handy for particles, bullets, collectibles, or any other short-lived entity. Inherited From * [Phaser.Component.LifeSpan#lifespan](phaser.component.lifespan#lifespan) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 65](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L65)) ### lineSpacing : number Additional spacing (in pixels) between each line of text if multi-line. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 2080](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L2080)) ### maxHealth : number The Game Objects maximum health value. This works in combination with the `heal` method to ensure the health value never exceeds the maximum. Inherited From * [Phaser.Component.Health#maxHealth](phaser.component.health#maxHealth) Default Value * 100 Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 35](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L35)) ### name : string A user defined name given to this Game Object. This value isn't ever used internally by Phaser, it is meant as a game level property. Inherited From * [Phaser.Component.Core#name](phaser.component.core#name) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 150](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L150)) ### [readonly] offsetX : number The amount the Game Object is visually offset from its x coordinate. This is the same as `width * anchor.x`. It will only be > 0 if anchor.x is not equal to zero. Inherited From * [Phaser.Component.Bounds#offsetX](phaser.component.bounds#offsetX) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L24)) ### [readonly] offsetY : number The amount the Game Object is visually offset from its y coordinate. This is the same as `height * anchor.y`. It will only be > 0 if anchor.y is not equal to zero. Inherited From * [Phaser.Component.Bounds#offsetY](phaser.component.bounds#offsetY) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L42)) ### outOfBoundsKill : boolean If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false. Inherited From * [Phaser.Component.InWorld#outOfBoundsKill](phaser.component.inworld#outOfBoundsKill) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 106](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L106)) ### outOfCameraBoundsKill : boolean If this and the `autoCull` property are both set to `true`, then the `kill` method is called as soon as the Game Object leaves the camera bounds. Inherited From * [Phaser.Component.InWorld#outOfCameraBoundsKill](phaser.component.inworld#outOfCameraBoundsKill) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 115](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L115)) ### padding : [Phaser.Point](phaser.point) Specify a padding value which is added to the line width and height when calculating the Text size. ALlows you to add extra spacing if Phaser is unable to accurately determine the true font dimensions. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 73](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L73)) ### pendingDestroy : boolean A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. You can set it directly to allow you to flag an object to be destroyed on its next update. This is extremely useful if you wish to destroy an object from within one of its own callbacks such as with Buttons or other Input events. Inherited From * [Phaser.Component.Core#pendingDestroy](phaser.component.core#pendingDestroy) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 259](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L259)) ### [readonly] physicsType : number The const physics body type of this object. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 66](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L66)) ### [readonly] previousPosition : [Phaser.Point](phaser.point) The position the Game Object was located in the previous frame. Inherited From * [Phaser.Component.Core#previousPosition](phaser.component.core#previousPosition) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 225](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L225)) ### [readonly] previousRotation : number The rotation the Game Object was in set to in the previous frame. Value is in radians. Inherited From * [Phaser.Component.Core#previousRotation](phaser.component.core#previousRotation) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L232)) ### [readonly] renderOrderID : number The render order ID is used internally by the renderer and Input Manager and should not be modified. This property is mostly used internally by the renderers, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#renderOrderID](phaser.component.core#renderOrderID) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 240](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L240)) ### resolution : integer The resolution of the canvas the text is rendered to. This defaults to match the resolution of the renderer, but can be changed on a per Text object basis. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 1895](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L1895)) ### right : number The right coordinate of the Game Object. This is the same as `x + width - offsetX`. Inherited From * [Phaser.Component.Bounds#right](phaser.component.bounds#right) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L124)) ### scaleMax : [Phaser.Point](phaser.point) The maximum scale this Game Object will scale up to. It allows you to prevent a parent from scaling this Game Object higher than the given value. Set it to `null` to remove the limit. Inherited From * [Phaser.Component.ScaleMinMax#scaleMax](phaser.component.scaleminmax#scaleMax) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L46)) ### scaleMin : [Phaser.Point](phaser.point) The minimum scale this Game Object will scale down to. It allows you to prevent a parent from scaling this Game Object lower than the given value. Set it to `null` to remove the limit. Inherited From * [Phaser.Component.ScaleMinMax#scaleMin](phaser.component.scaleminmax#scaleMin) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 36](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L36)) ### setHealth Sets the health property of the Game Object to the given amount. Will never exceed the `maxHealth` value. Inherited From * [Phaser.Component.Health#setHealth](phaser.component.health#setHealth) Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 70](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L70)) ### shader : [PIXI.AbstractFilter](pixi.abstractfilter) The shader that will be used to render this Sprite. Set to null to remove a current shader. Inherited From * [PIXI.Sprite#shader](pixi.sprite#shader) Default Value * null Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L93)) ### shadowBlur : number The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene). Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 2173](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L2173)) ### shadowColor : string The color of the shadow, as given in CSS rgba format. Set the alpha component to 0 to disable the shadow. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 2151](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L2151)) ### shadowFill : boolean Sets if the drop shadow is applied to the Text fill. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 2217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L2217)) ### shadowOffsetX : number The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 2107](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L2107)) ### shadowOffsetY : number The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 2129](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L2129)) ### shadowStroke : boolean Sets if the drop shadow is applied to the Text stroke. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 2195](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L2195)) ### smoothed : boolean Enable or disable texture smoothing for this Game Object. It only takes effect if the Game Object is using an image based texture. Smoothing is enabled by default. Inherited From * [Phaser.Component.Smoothed#smoothed](phaser.component.smoothed#smoothed) Source code: [gameobjects/components/Smoothed.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Smoothed.js) ([Line 25](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Smoothed.js#L25)) ### stroke : string A canvas fillstyle that will be used on the text stroke eg 'blue', '#FCFF00'. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 1992](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L1992)) ### strokeColors :array An array of the stroke color values as specified by [addStrokeColor](phaser.text#addStrokeColor). Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 101](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L101)) ### strokeThickness : number A number that represents the thickness of the stroke. Default is 0 (no stroke) Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 2014](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L2014)) ### tabs : integer | array The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an integer or an array of varying tab sizes, one tab per element. For example if you set tabs to 100 then when Text encounters a tab it will jump ahead 100 pixels. If you set tabs to be `[100,200]` then it will set the first tab at 100px and the second at 200px. ##### Type * integer | array Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 1919](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L1919)) ### text : string The text to be displayed by this Text object. Use a \n to insert a carriage return and split the text. The text will be rendered with any style currently set. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 1651](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L1651)) ### [readonly] textBounds : [Phaser.Rectangle](phaser.rectangle) The textBounds property allows you to specify a rectangular region upon which text alignment is based. See `Text.setTextBounds` for more details. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 81](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L81)) ### texture : [PIXI.Texture](pixi.texture) The texture that the sprite is using Inherited From * [PIXI.Sprite#texture](pixi.sprite#texture) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L28)) ### tint : number The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. Inherited From * [PIXI.Sprite#tint](pixi.sprite#tint) Default Value * 0xFFFFFF Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L54)) ### tintedTexture :Canvas A canvas that contains the tinted version of the Sprite (in Canvas mode, WebGL doesn't populate this) Inherited From * [PIXI.Sprite#tintedTexture](pixi.sprite#tintedTexture) Default Value * null Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 73](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L73)) ### top : number The y coordinate of the Game Object. This is the same as `y - offsetY`. Inherited From * [Phaser.Component.Bounds#top](phaser.component.bounds#top) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 146](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L146)) ### transformCallback : Function The callback that will apply any scale limiting to the worldTransform. Inherited From * [Phaser.Component.ScaleMinMax#transformCallback](phaser.component.scaleminmax#transformCallback) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L20)) ### transformCallbackContext : Object The context under which `transformCallback` is called. Inherited From * [Phaser.Component.ScaleMinMax#transformCallbackContext](phaser.component.scaleminmax#transformCallbackContext) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L26)) ### type : number The const type of this object. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 60](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L60)) ### useAdvancedWrap : boolean Will this Text object use Basic or Advanced Word Wrapping? Advanced wrapping breaks long words if they are the first of a line, and repeats the process as necessary. White space is condensed (e.g., consecutive spaces are replaced with one). Lines are trimmed of white space before processing. It throws an error if wordWrapWidth is less than a single character. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L132)) ### width : number The width of the Text. Setting this will modify the scale to achieve the value requested. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 2239](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L2239)) ### wordWrap : boolean Indicates if word wrap should be used. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 2036](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L2036)) ### wordWrapWidth : number The width at which text will wrap. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 2058](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L2058)) ### world : [Phaser.Point](phaser.point) The world coordinates of this Game Object in pixels. Depending on where in the display list this Game Object is placed this value can differ from `position`, which contains the x/y coordinates relative to the Game Objects parent. Inherited From * [Phaser.Component.Core#world](phaser.component.core#world) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 211](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L211)) ### x : number The position of the Game Object on the x axis relative to the local coordinates of the parent. Inherited From * [Phaser.Component.PhysicsBody#x](phaser.component.physicsbody#x) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L98)) ### y : number The position of the Game Object on the y axis relative to the local coordinates of the parent. Inherited From * [Phaser.Component.PhysicsBody#y](phaser.component.physicsbody#y) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L124)) ### [readonly] z : number The z depth of this Game Object within its parent Group. No two objects in a Group can have the same z value. This value is adjusted automatically whenever the Group hierarchy changes. If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. Inherited From * [Phaser.Component.Core#z](phaser.component.core#z) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 177](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L177)) Public Methods -------------- ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### addColor(color, position) → {[Phaser.Text](phaser.text)} Set specific colors for certain characters within the Text. It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position. The position value is the index of the character in the Text string to start applying this color to. Once set the color remains in use until either another color or the end of the string is encountered. For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow. If you wish to change the stroke color see addStrokeColor instead. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `color` | string | A canvas fillstyle that will be used on the text eg `red`, `#00FF00`, `rgba()`. | | `position` | number | The index of the character in the string to start applying this color value from. | ##### Returns [Phaser.Text](phaser.text) - This Text instance. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 829](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L829)) ### addFontStyle(style, position) → {[Phaser.Text](phaser.text)} Set specific font styles for certain characters within the Text. It works by taking a font style value, which is a typical string such as `normal`, `italic` or `oblique`. The position value is the index of the character in the Text string to start applying this font style to. Once set the font style remains in use until either another font style or the end of the string is encountered. For example if the Text was `Photon Storm` and you did `Text.addFontStyle('italic', 6)` it would font style in the word `Storm` in italic. If you wish to change the text font weight see addFontWeight instead. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `style` | string | A canvas font-style that will be used on the text style eg `normal`, `italic`, `oblique`. | | `position` | number | The index of the character in the string to start applying this font style value from. | ##### Returns [Phaser.Text](phaser.text) - This Text instance. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 879](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L879)) ### addFontWeight(style, position) → {[Phaser.Text](phaser.text)} Set specific font weights for certain characters within the Text. It works by taking a font weight value, which is a typical string such as `normal`, `bold`, `bolder`, etc. The position value is the index of the character in the Text string to start applying this font weight to. Once set the font weight remains in use until either another font weight or the end of the string is encountered. For example if the Text was `Photon Storm` and you did `Text.addFontWeight('bold', 6)` it would font weight in the word `Storm` in bold. If you wish to change the text font style see addFontStyle instead. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `style` | string | A canvas font-weight that will be used on the text weight eg `normal`, `bold`, `bolder`, `lighter`, etc. | | `position` | number | The index of the character in the string to start applying this font weight value from. | ##### Returns [Phaser.Text](phaser.text) - This Text instance. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 903](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L903)) ### addStrokeColor(color, position) → {[Phaser.Text](phaser.text)} Set specific stroke colors for certain characters within the Text. It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position. The position value is the index of the character in the Text string to start applying this color to. Once set the color remains in use until either another color or the end of the string is encountered. For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow. This has no effect if stroke is disabled or has a thickness of 0. If you wish to change the text fill color see addColor instead. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `color` | string | A canvas fillstyle that will be used on the text stroke eg `red`, `#00FF00`, `rgba()`. | | `position` | number | The index of the character in the string to start applying this color value from. | ##### Returns [Phaser.Text](phaser.text) - This Text instance. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 853](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L853)) ### alignIn(container, position, offsetX, offsetY) → {Object} Aligns this Game Object within another Game Object, or Rectangle, known as the 'container', to one of 9 possible positions. The container must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the container. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the container, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `container` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Inherited From * [Phaser.Component.Bounds#alignIn](phaser.component.bounds#alignIn) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 223](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L223)) ### alignTo(parent, position, offsetX, offsetY) → {Object} Aligns this Game Object to the side of another Game Object, or Rectangle, known as the 'parent', in one of 11 possible positions. The parent must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the parent. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the parent, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Inherited From * [Phaser.Component.Bounds#alignTo](phaser.component.bounds#alignTo) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 321](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L321)) ### bringToTop() → {PIXI.DisplayObject} Brings this Game Object to the top of its parents display list. Visually this means it will render over the top of any old child in the same Group. If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#bringToTop](phaser.component.bringtotop#bringToTop) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L24)) ### clearColors() → {[Phaser.Text](phaser.text)} Clears any text fill or stroke colors that were set by `addColor` or `addStrokeColor`. ##### Returns [Phaser.Text](phaser.text) - This Text instance. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 797](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L797)) ### clearFontValues() → {[Phaser.Text](phaser.text)} Clears any text styles or weights font that were set by `addFontStyle` or `addFontWeight`. ##### Returns [Phaser.Text](phaser.text) - This Text instance. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 813](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L813)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### crop(rect, copy) Crop allows you to crop the texture being used to display this Game Object. Setting a crop rectangle modifies the core texture frame. The Game Object width and height properties will be adjusted accordingly. Cropping takes place from the top-left and can be modified in real-time either by providing an updated rectangle object to this method, or by modifying `cropRect` property directly and then calling `updateCrop`. The rectangle object given to this method can be either a `Phaser.Rectangle` or any other object so long as it has public `x`, `y`, `width`, `height`, `right` and `bottom` properties. A reference to the rectangle is stored in `cropRect` unless the `copy` parameter is `true`, in which case the values are duplicated to a local object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `rect` | [Phaser.Rectangle](phaser.rectangle) | | | The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle. | | `copy` | boolean | <optional> | false | If false `cropRect` will be stored as a reference to the given rect. If true it will copy the rect values into a local Phaser Rectangle object stored in cropRect. | Inherited From * [Phaser.Component.Crop#crop](phaser.component.crop#crop) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L49)) ### destroy(destroyChildren) Destroy this Text object, removing it from the group it belongs to. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroyChildren` | boolean | <optional> | true | Should every child of this object have its destroy method called? | Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L217)) ### getBounds(matrix) → {[Phaser.Rectangle](phaser.rectangle)} Returns the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `matrix` | [Phaser.Matrix](phaser.matrix) | The transformation matrix of the Text. | ##### Returns [Phaser.Rectangle](phaser.rectangle) - The framing rectangle Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 1631](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L1631)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the Sprite as a rectangle. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.Sprite#getLocalBounds](pixi.sprite#getLocalBounds) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 315](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L315)) ### kill() → {PIXI.DisplayObject} Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false. It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal. Note that killing a Game Object is a way for you to quickly recycle it in an object pool, it doesn't destroy the object or free it up from memory. If you don't need this Game Object any more you should call `destroy` instead. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.LifeSpan#kill](phaser.component.lifespan#kill) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 113](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L113)) ### loadTexture(key, frame, stopAnimation) Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache. If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead. You should only use `loadTexture` if you want to replace the base texture entirely. Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU. You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite. Doing this then sets the key to be the `frame` argument (the frame is set to zero). This allows you to create sprites using `load.image` during development, and then change them to use a Texture Atlas later in development by simply searching your code for 'PENDING\_ATLAS' and swapping it to be the key of the atlas data. Note: You cannot use a RenderTexture as a texture for a TileSprite. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | | `stopAnimation` | boolean | <optional> | true | If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing. | Inherited From * [Phaser.Component.LoadTexture#loadTexture](phaser.component.loadtexture#loadTexture) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L51)) ### moveDown() → {PIXI.DisplayObject} Moves this Game Object down one place in its parents display list. This call has no effect if the Game Object is already at the bottom of the display list. If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#moveDown](phaser.component.bringtotop#moveDown) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L87)) ### moveUp() → {PIXI.DisplayObject} Moves this Game Object up one place in its parents display list. This call has no effect if the Game Object is already at the top of the display list. If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#moveUp](phaser.component.bringtotop#moveUp) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 66](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L66)) ### overlap(displayObject) → {boolean} Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object, which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result. This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result. Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency. It should be fine for low-volume testing where physics isn't required. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `displayObject` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.TileSprite](phaser.tilesprite) | [Phaser.Button](phaser.button) | PIXI.DisplayObject | The display object to check against. | ##### Returns boolean - True if the bounds of this Game Object intersects at any point with the bounds of the given display object. Inherited From * [Phaser.Component.Overlap#overlap](phaser.component.overlap#overlap) Source code: [gameobjects/components/Overlap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Overlap.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Overlap.js#L29)) ### parseList(list) → {[Phaser.Text](phaser.text)} Converts the given array into a tab delimited string and then updates this Text object. This is mostly used when you want to display external data using tab stops. The array can be either single or multi dimensional depending on the result you need: `[ 'a', 'b', 'c' ]` would convert in to `"a\tb\tc"`. Where as: `[ [ 'a', 'b', 'c' ], [ 'd', 'e', 'f'] ]` would convert in to: `"a\tb\tc\nd\te\tf"` ##### Parameters | Name | Type | Description | | --- | --- | --- | | `list` | array | The array of data to convert into a string. | ##### Returns [Phaser.Text](phaser.text) - This Text instance. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 1286](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L1286)) ### play(name, frameRate, loop, killOnComplete) → {[Phaser.Animation](phaser.animation)} Plays an Animation. The animation should have previously been created via `animations.add`. If the animation is already playing calling this again won't do anything. If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `name` | string | | | The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'. | | `frameRate` | number | <optional> | null | The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. | | `loop` | boolean | <optional> | false | Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. | | `killOnComplete` | boolean | <optional> | false | If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. | ##### Returns [Phaser.Animation](phaser.animation) - A reference to playing Animation. Inherited From * [Phaser.Component.Animation#play](phaser.component.animation#play) Source code: [gameobjects/components/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Animation.js) ([Line 31](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Animation.js#L31)) ### <internal> postUpdate() Internal method called by the World postUpdate cycle. Inherited From * [Phaser.Component.Core#postUpdate](phaser.component.core#postUpdate) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 338](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L338)) ### precalculateWordWrap(text) → {array} Runs the given text through the Text.runWordWrap function and returns the results as an array, where each element of the array corresponds to a wrapped line of text. Useful if you wish to control pagination on long pieces of content. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `text` | string | The text for which the wrapping will be calculated. | ##### Returns array - An array of strings with the pieces of wrapped text. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 927](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L927)) ### <internal> preUpdate() Automatically called by World.preUpdate. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 190](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L190)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### reset(x, y, health) → {PIXI.DisplayObject} Resets the Game Object. This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`, `visible` and `renderable` to true. If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value. If this Game Object has a Physics Body it will reset the Body. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate (in world space) to position the Game Object at. | | `y` | number | | | The y coordinate (in world space) to position the Game Object at. | | `health` | number | <optional> | 1 | The health to give the Game Object if it has the Health component. | ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.Reset#reset](phaser.component.reset#reset) Source code: [gameobjects/components/Reset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Reset.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Reset.js#L30)) ### resetFrame() Resets the texture frame dimensions that the Game Object uses for rendering. Inherited From * [Phaser.Component.LoadTexture#resetFrame](phaser.component.loadtexture#resetFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L232)) ### resizeFrame(parent, width, height) Resizes the Frame dimensions that the Game Object uses for rendering. You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData it can be useful to adjust the dimensions directly in this way. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `parent` | object | The parent texture object that caused the resize, i.e. a Phaser.Video object. | | `width` | integer | The new width of the texture. | | `height` | integer | The new height of the texture. | Inherited From * [Phaser.Component.LoadTexture#resizeFrame](phaser.component.loadtexture#resizeFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 220](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L220)) ### revive(health) → {PIXI.DisplayObject} Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `health` | number | <optional> | 100 | The health to give the Game Object. Only set if the GameObject has the Health component. | ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.LifeSpan#revive](phaser.component.lifespan#revive) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L78)) ### sendToBack() → {PIXI.DisplayObject} Sends this Game Object to the bottom of its parents display list. Visually this means it will render below all other children in the same Group. If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#sendToBack](phaser.component.bringtotop#sendToBack) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L45)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### setFrame(frame) Sets the texture frame the Game Object uses for rendering. This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `frame` | [Phaser.Frame](phaser.frame) | The Frame to be used by the texture. | Inherited From * [Phaser.Component.LoadTexture#setFrame](phaser.component.loadtexture#setFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 155](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L155)) ### setScaleMinMax(minX, minY, maxX, maxY) Sets the scaleMin and scaleMax values. These values are used to limit how far this Game Object will scale based on its parent. For example if this Game Object has a `minScale` value of 1 and its parent has a `scale` value of 0.5, the 0.5 will be ignored and the scale value of 1 will be used, as the parents scale is lower than the minimum scale this Game Object should adhere to. By setting these values you can carefully control how Game Objects deal with responsive scaling. If only one parameter is given then that value will be used for both scaleMin and scaleMax: `setScaleMinMax(1)` = scaleMin.x, scaleMin.y, scaleMax.x and scaleMax.y all = 1 If only two parameters are given the first is set as scaleMin.x and y and the second as scaleMax.x and y: `setScaleMinMax(0.5, 2)` = scaleMin.x and y = 0.5 and scaleMax.x and y = 2 If you wish to set `scaleMin` with different values for x and y then either modify Game Object.scaleMin directly, or pass `null` for the `maxX` and `maxY` parameters. Call `setScaleMinMax(null)` to clear all previously set values. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `minX` | number | null | The minimum horizontal scale value this Game Object can scale down to. | | `minY` | number | null | The minimum vertical scale value this Game Object can scale down to. | | `maxX` | number | null | The maximum horizontal scale value this Game Object can scale up to. | | `maxY` | number | null | The maximum vertical scale value this Game Object can scale up to. | Inherited From * [Phaser.Component.ScaleMinMax#setScaleMinMax](phaser.component.scaleminmax#setScaleMinMax) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 110](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L110)) ### setShadow(x, y, color, blur, shadowStroke, shadowFill) → {[Phaser.Text](phaser.text)} Sets a drop shadow effect on the Text. You can specify the horizontal and vertical distance of the drop shadow with the `x` and `y` parameters. The color controls the shade of the shadow (default is black) and can be either an `rgba` or `hex` value. The blur is the strength of the shadow. A value of zero means a hard shadow, a value of 10 means a very soft shadow. To remove a shadow already in place you can call this method with no parameters set. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | <optional> | 0 | The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be. | | `y` | number | <optional> | 0 | The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be. | | `color` | string | <optional> | 'rgba(0,0,0,1)' | The color of the shadow, as given in CSS rgba or hex format. Set the alpha component to 0 to disable the shadow. | | `blur` | number | <optional> | 0 | The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene). | | `shadowStroke` | boolean | <optional> | true | Apply the drop shadow to the Text stroke (if set). | | `shadowFill` | boolean | <optional> | true | Apply the drop shadow to the Text fill (if set). | ##### Returns [Phaser.Text](phaser.text) - This Text instance. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 231](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L231)) ### setStyle(style, update) → {[Phaser.Text](phaser.text)} Set the style of the text by passing a single style object to it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `style` | object | <optional> | | The style properties to be set on the Text. Properties | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `font` | string | <optional> | 'bold 20pt Arial' | The style and size of the font. | | `fontStyle` | string | <optional> | (from font) | The style of the font (eg. 'italic'): overrides the value in `style.font`. | | `fontVariant` | string | <optional> | (from font) | The variant of the font (eg. 'small-caps'): overrides the value in `style.font`. | | `fontWeight` | string | <optional> | (from font) | The weight of the font (eg. 'bold'): overrides the value in `style.font`. | | `fontSize` | string | number | <optional> | (from font) | The size of the font (eg. 32 or '32px'): overrides the value in `style.font`. | | `backgroundColor` | string | <optional> | null | A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable. | | `fill` | string | <optional> | 'black' | A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. | | `align` | string | <optional> | 'left' | Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that). | | `boundsAlignH` | string | <optional> | 'left' | Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. | | `boundsAlignV` | string | <optional> | 'top' | Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. | | `stroke` | string | <optional> | 'black' | A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'. | | `strokeThickness` | number | <optional> | 0 | A number that represents the thickness of the stroke. Default is 0 (no stroke). | | `wordWrap` | boolean | <optional> | false | Indicates if word wrap should be used. | | `wordWrapWidth` | number | <optional> | 100 | The width in pixels at which text will wrap. | | `maxLines` | number | <optional> | 0 | The maximum number of lines to be shown for wrapped text. | | `tabs` | number | array | <optional> | 0 | The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop. | | | `update` | boolean | <optional> | false | Immediately update the Text object after setting the new style? Or wait for the next frame. | ##### Returns [Phaser.Text](phaser.text) - This Text instance. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 267](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L267)) ### setText(text, immediate) → {[Phaser.Text](phaser.text)} The text to be displayed by this Text object. Use a \n to insert a carriage return and split the text. The text will be rendered with any style currently set. Use the optional `immediate` argument if you need the Text display to update immediately. If not it will re-create the texture of this Text object during the next time the render loop is called. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `text` | string | <optional> | | The text to be displayed. Set to an empty string to clear text that is already present. | | `immediate` | boolean | <optional> | false | Update the texture used by this Text object immediately (true) or automatically during the next render loop (false). | ##### Returns [Phaser.Text](phaser.text) - This Text instance. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 1252](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L1252)) ### setTextBounds(x, y, width, height) → {[Phaser.Text](phaser.text)} The Text Bounds is a rectangular region that you control the dimensions of into which the Text object itself is positioned, regardless of the number of lines in the text, the font size or any other attribute. Alignment is controlled via the properties `boundsAlignH` and `boundsAlignV` within the Text.style object, or can be directly set through the setters `Text.boundsAlignH` and `Text.boundsAlignV`. Bounds alignment is independent of text alignment. For example: If your game is 800x600 in size and you set the text bounds to be 0,0,800,600 then by setting boundsAlignH to 'center' and boundsAlignV to 'bottom' the text will render in the center and at the bottom of your game window, regardless of how many lines of text there may be. Even if you adjust the text content or change the style it will remain at the bottom center of the text bounds. This is especially powerful when you need to align text against specific coordinates in your game, but the actual text dimensions may vary based on font (say for multi-lingual games). If `Text.wordWrapWidth` is greater than the width of the text bounds it is clamped to match the bounds width. Call this method with no arguments given to reset an existing textBounds. It works by calculating the final position based on the Text.canvas size, which is modified as the text is updated. Some fonts have additional padding around them which you can mitigate by tweaking the Text.padding property. It then adjusts the `pivot` property based on the given bounds and canvas size. This means if you need to set the pivot property directly in your game then you either cannot use `setTextBounds` or you must place the Text object inside another DisplayObject on which you set the pivot. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `x` | number | <optional> | The x coordinate of the Text Bounds region. | | `y` | number | <optional> | The y coordinate of the Text Bounds region. | | `width` | number | <optional> | The width of the Text Bounds region. | | `height` | number | <optional> | The height of the Text Bounds region. | ##### Returns [Phaser.Text](phaser.text) - This Text instance. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 1347](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L1347)) ### setTexture(texture, destroy) Sets the texture of the sprite. Be warned that this doesn't remove or destroy the previous texture this Sprite was using. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `texture` | [PIXI.Texture](pixi.texture) | | | The PIXI texture that is displayed by the sprite | | `destroy` | Boolean | <optional> | false | Call Texture.destroy on the current texture before replacing it with the new one? | Inherited From * [PIXI.Sprite#setTexture](pixi.sprite#setTexture) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 163](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L163)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) ### <internal> update() Override this function to handle any special update requirements. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 207](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L207)) ### updateCrop() If you have set a crop rectangle on this Game Object via `crop` and since modified the `cropRect` property, or the rectangle it references, then you need to update the crop frame by calling this method. Inherited From * [Phaser.Component.Crop#updateCrop](phaser.component.crop#updateCrop) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L86)) ### updateShadow(state) Sets the Shadow on the Text.context based on the Style settings, or disables it if not enabled. This is called automatically by Text.updateText. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `state` | boolean | If true the shadow will be set to the Style values, otherwise it will be set to zero. | Source code: [gameobjects/Text.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js) ([Line 652](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Text.js#L652))
programming_docs
phaser Class: Phaser.Tilemap Class: Phaser.Tilemap ===================== Constructor ----------- ### new Tilemap(game, key, tileWidth, tileHeight, width, height) Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file. Tiled is a free software package specifically for creating tile maps, and is available from http://www.mapeditor.org To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. When using CSV data you must provide the key and the tileWidth and tileHeight parameters. If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. A Tile map is rendered to the display using a TilemapLayer. It is not added to the display list directly itself. A map may have multiple layers. You can perform operations on the map data such as copying, pasting, filling and shuffling the tiles around. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | | Game reference to the currently running game. | | `key` | string | <optional> | | The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. | | `tileWidth` | number | <optional> | 32 | The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. | | `tileHeight` | number | <optional> | 32 | The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. | | `width` | number | <optional> | 10 | The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. | | `height` | number | <optional> | 10 | The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. | Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L28)) Public Properties ----------------- ### [static] CSV : number Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 176](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L176)) ### [static] EAST : number Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 194](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L194)) ### [static] NORTH : number Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 188](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L188)) ### [static] SOUTH : number Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 200](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L200)) ### [static] TILED\_JSON : number Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 182](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L182)) ### [static] WEST : number Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 206](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L206)) ### collideIndexes :array An array of tile indexes that collide. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 125](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L125)) ### collision :array An array of collision data (polylines, etc). Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 130](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L130)) ### currentLayer : number The current layer. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 145](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L145)) ### debugMap :array Map data used for debug values only. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 150](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L150)) ### enableDebug : boolean If set then console.log is used to dump out useful layer creation debug data. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 140](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L140)) ### format : number The format of the map data, either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED\_JSON. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 75](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L75)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 33](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L33)) ### height : number The height of the map (in tiles). Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L55)) ### heightInPixels : number The height of the map in pixels based on height \* tileHeight. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 95](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L95)) ### imagecollections :array An array of Image Collections. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 110](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L110)) ### images :array An array of Tiled Image Layers. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 135](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L135)) ### key : string The key of this map data in the Phaser.Cache. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L38)) ### layer : number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) The current layer object. ##### Type * number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1947](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1947)) ### layers :array An array of Tilemap layer data. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 100](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L100)) ### objects :array An array of Tiled Object Layers. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 120](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L120)) ### orientation : string The orientation of the map data (as specified in Tiled), usually 'orthogonal'. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 70](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L70)) ### properties : Object Map specific properties as specified in Tiled. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L85)) ### tileHeight : number The base height of the tiles in the map (in pixels). Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 65](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L65)) ### tiles :array The super array of Tiles. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 115](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L115)) ### tilesets :array An array of Tilesets. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 105](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L105)) ### tileWidth : number The base width of the tiles in the map (in pixels). Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 60](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L60)) ### version : number The version of the map data (as specified in Tiled, usually 1). Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 80](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L80)) ### width : number The width of the map (in tiles). Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L50)) ### widthInPixels : number The width of the map in pixels based on width \* tileWidth. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 90](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L90)) Public Methods -------------- ### addTilesetImage(tileset, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid) → {[Phaser.Tileset](phaser.tileset)} Adds an image to the map to be used as a tileset. A single map may use multiple tilesets. Note that the tileset name can be found in the JSON file exported from Tiled, or in the Tiled editor. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `tileset` | string | | | The name of the tileset as specified in the map data. | | `key` | string | [Phaser.BitmapData](phaser.bitmapdata) | <optional> | | The key of the Phaser.Cache image used for this tileset. If `undefined` or `null` it will look for an image with a key matching the tileset parameter. You can also pass in a BitmapData which can be used instead of an Image. | | `tileWidth` | number | <optional> | 32 | The width of the tiles in the Tileset Image. If not given it will default to the map.tileWidth value, if that isn't set then 32. | | `tileHeight` | number | <optional> | 32 | The height of the tiles in the Tileset Image. If not given it will default to the map.tileHeight value, if that isn't set then 32. | | `tileMargin` | number | <optional> | 0 | The width of the tiles in the Tileset Image. | | `tileSpacing` | number | <optional> | 0 | The height of the tiles in the Tileset Image. | | `gid` | number | <optional> | 0 | If adding multiple tilesets to a blank/dynamic map, specify the starting GID the set will use here. | ##### Returns [Phaser.Tileset](phaser.tileset) - Returns the Tileset object that was created or updated, or null if it failed. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 253](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L253)) ### <internal> calculateFaces(layer) Internal function. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `layer` | number | The index of the TilemapLayer to operate on. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1073](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1073)) ### copy(x, y, width, height, layer) → {array} Copies all of the tiles in the given rectangular block into the tilemap data buffer. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `x` | integer | | X position of the top left of the area to copy (given in tiles, not pixels) | | `y` | integer | | Y position of the top left of the area to copy (given in tiles, not pixels) | | `width` | integer | | The width of the area to copy (given in tiles, not pixels) | | `height` | integer | | The height of the area to copy (given in tiles, not pixels) | | `layer` | integer | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | The layer to copy the tiles from. | ##### Returns array - An array of the tiles that were copied. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1543](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1543)) ### create(name, width, height, tileWidth, tileHeight, group) → {[Phaser.TilemapLayer](phaser.tilemaplayer)} Creates an empty map of the given dimensions and one blank layer. If layers already exist they are erased. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `name` | string | | The name of the default layer of the map. | | `width` | number | | The width of the map in tiles. | | `height` | number | | The height of the map in tiles. | | `tileWidth` | number | | The width of the tiles the map uses for calculations. | | `tileHeight` | number | | The height of the tiles the map uses for calculations. | | `group` | [Phaser.Group](phaser.group) | <optional> | Optional Group to add the layer to. If not specified it will be added to the World group. | ##### Returns [Phaser.TilemapLayer](phaser.tilemaplayer) - The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 210](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L210)) ### createBlankLayer(name, width, height, tileWidth, tileHeight, group) → {[Phaser.TilemapLayer](phaser.tilemaplayer)} Creates a new and empty layer on this Tilemap. By default TilemapLayers are fixed to the camera. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `name` | string | | The name of this layer. Must be unique within the map. | | `width` | number | | The width of the layer in tiles. | | `height` | number | | The height of the layer in tiles. | | `tileWidth` | number | | The width of the tiles the layer uses for calculations. | | `tileHeight` | number | | The height of the tiles the layer uses for calculations. | | `group` | [Phaser.Group](phaser.group) | <optional> | Optional Group to add the layer to. If not specified it will be added to the World group. | ##### Returns [Phaser.TilemapLayer](phaser.tilemaplayer) - The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 635](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L635)) ### createFromObjects(name, gid, key, frame, exists, autoCull, group, CustomClass, adjustY) Creates a Sprite for every object matching the given gid in the map data. You can optionally specify the group that the Sprite will be created in. If none is given it will be created in the World. All properties from the map data objectgroup are copied across to the Sprite, so you can use this as an easy way to configure Sprite properties from within the map editor. For example giving an object a property of alpha: 0.5 in the map editor will duplicate that when the Sprite is created. You could also give it a value like: body.velocity.x: 100 to set it moving automatically. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `name` | string | | | The name of the Object Group to create Sprites from. | | `gid` | number | | | The layer array index value, or if a string is given the layer name within the map data. | | `key` | string | | | The Game.cache key of the image that this Sprite will use. | | `frame` | number | string | <optional> | | If the Sprite image contains multiple frames you can specify which one to use here. | | `exists` | boolean | <optional> | true | The default exists state of the Sprite. | | `autoCull` | boolean | <optional> | false | The default autoCull state of the Sprite. Sprites that are autoCulled are culled from the camera if out of its range. | | `group` | [Phaser.Group](phaser.group) | <optional> | Phaser.World | Group to add the Sprite to. If not specified it will be added to the World group. | | `CustomClass` | object | <optional> | Phaser.Sprite | If you wish to create your own class, rather than Phaser.Sprite, pass the class here. Your class must extend Phaser.Sprite and have the same constructor parameters. | | `adjustY` | boolean | <optional> | true | By default the Tiled map editor uses a bottom-left coordinate system. Phaser uses top-left. So most objects will appear too low down. This parameter moves them up by their height. | Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 378](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L378)) ### createFromTiles(tiles, replacements, key, layer, group, properties) → {integer} Creates a Sprite for every object matching the given tile indexes in the map data. You can specify the group that the Sprite will be created in. If none is given it will be created in the World. You can optional specify if the tile will be replaced with another after the Sprite is created. This is useful if you want to lay down special tiles in a level that are converted to Sprites, but want to replace the tile itself with a floor tile or similar once converted. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `tiles` | integer | Array | | | The tile index, or array of indexes, to create Sprites from. | | `replacements` | integer | Array | | | The tile index, or array of indexes, to change a converted tile to. Set to `null` to not change. | | `key` | string | | | The Game.cache key of the image that this Sprite will use. | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | | The layer to operate on. | | `group` | [Phaser.Group](phaser.group) | <optional> | Phaser.World | Group to add the Sprite to. If not specified it will be added to the World group. | | `properties` | object | <optional> | | An object that contains the default properties for your newly created Sprite. This object will be iterated and any matching Sprite property will be set. | ##### Returns integer - The number of Sprites that were created. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 467](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L467)) ### createLayer(layer, width, height, group) → {[Phaser.TilemapLayer](phaser.tilemaplayer)} Creates a new TilemapLayer object. By default TilemapLayers are fixed to the camera. The `layer` parameter is important. If you've created your map in Tiled then you can get this by looking in Tiled and looking at the Layer name. Or you can open the JSON file it exports and look at the layers[].name value. Either way it must match. If you wish to create a blank layer to put your own tiles on then see Tilemap.createBlankLayer. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `layer` | number | string | | The layer array index value, or if a string is given the layer name, within the map data that this TilemapLayer represents. | | `width` | number | <optional> | The rendered width of the layer, should never be wider than Game.width. If not given it will be set to Game.width. | | `height` | number | <optional> | The rendered height of the layer, should never be wider than Game.height. If not given it will be set to Game.height. | | `group` | [Phaser.Group](phaser.group) | <optional> | Optional Group to add the object to. If not specified it will be added to the World group. | ##### Returns [Phaser.TilemapLayer](phaser.tilemaplayer) - The TilemapLayer object. This is an extension of Phaser.Sprite and can be moved around the display list accordingly. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 561](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L561)) ### destroy() Removes all layer data from this tile map and nulls the game reference. Note: You are responsible for destroying any TilemapLayer objects you generated yourself, as Tilemap doesn't keep a reference to them. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1929](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1929)) ### dump() Dumps the tilemap data out to the console. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1888](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1888)) ### fill(index, x, y, width, height, layer) Fills the given area with the specified tile. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `index` | number | | The index of the tile that the area will be filled with. | | `x` | number | | X position of the top left of the area to operate one, given in tiles, not pixels. | | `y` | number | | Y position of the top left of the area to operate one, given in tiles, not pixels. | | `width` | number | | The width in tiles of the area to operate on. | | `height` | number | | The height in tiles of the area to operate on. | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | The layer to operate on. | Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1845](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1845)) ### forEach(callback, context, x, y, width, height, layer) For each tile in the given area defined by x/y and width/height run the given callback. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `callback` | number | | The callback. Each tile in the given area will be passed to this callback as the first and only parameter. | | `context` | number | | The context under which the callback should be run. | | `x` | number | | X position of the top left of the area to operate one, given in tiles, not pixels. | | `y` | number | | Y position of the top left of the area to operate one, given in tiles, not pixels. | | `width` | number | | The width in tiles of the area to operate on. | | `height` | number | | The height in tiles of the area to operate on. | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | The layer to operate on. | Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1694](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1694)) ### getImageIndex(name) → {number} Gets the image index based on its name. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `name` | string | The name of the image to get. | ##### Returns number - The index of the image in this tilemap, or null if not found. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 766](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L766)) ### <internal> getIndex(location, name) → {number} Gets the layer index based on the layers name. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `location` | array | The local array to search. | | `name` | string | The name of the array element to get. | ##### Returns number - The index of the element in the array, or null if not found. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 717](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L717)) ### <internal> getLayer(layer) → {number} Gets the TilemapLayer index as used in the setCollision calls. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | The layer to operate on. If not given will default to this.currentLayer. | ##### Returns number - The TilemapLayer index. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1017](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1017)) ### getLayerIndex(name) → {number} Gets the layer index based on its name. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `name` | string | The name of the layer to get. | ##### Returns number - The index of the layer in this tilemap, or null if not found. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 740](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L740)) ### getTile(x, y, layer, nonNull) → {[Phaser.Tile](phaser.tile)} Gets a tile from the Tilemap Layer. The coordinates are given in tile values. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | X position to get the tile from (given in tile units, not pixels) | | `y` | number | | | Y position to get the tile from (given in tile units, not pixels) | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | | The layer to get the tile from. | | `nonNull` | boolean | <optional> | false | If true getTile won't return null for empty tiles, but a Tile object with an index of -1. | ##### Returns [Phaser.Tile](phaser.tile) - The tile at the given coordinates or null if no tile was found or the coordinates were invalid. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1476](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1476)) ### getTileAbove(layer, x, y) Gets the tile above the tile coordinates given. Mostly used as an internal function by calculateFaces. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `layer` | number | The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). | | `x` | number | The x coordinate to get the tile from. In tiles, not pixels. | | `y` | number | The y coordinate to get the tile from. In tiles, not pixels. | Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1143](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1143)) ### getTileBelow(layer, x, y) Gets the tile below the tile coordinates given. Mostly used as an internal function by calculateFaces. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `layer` | number | The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). | | `x` | number | The x coordinate to get the tile from. In tiles, not pixels. | | `y` | number | The y coordinate to get the tile from. In tiles, not pixels. | Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1163](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1163)) ### getTileLeft(layer, x, y) Gets the tile to the left of the tile coordinates given. Mostly used as an internal function by calculateFaces. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `layer` | number | The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). | | `x` | number | The x coordinate to get the tile from. In tiles, not pixels. | | `y` | number | The y coordinate to get the tile from. In tiles, not pixels. | Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1183](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1183)) ### getTileRight(layer, x, y) Gets the tile to the right of the tile coordinates given. Mostly used as an internal function by calculateFaces. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `layer` | number | The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). | | `x` | number | The x coordinate to get the tile from. In tiles, not pixels. | | `y` | number | The y coordinate to get the tile from. In tiles, not pixels. | Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1203](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1203)) ### getTilesetIndex(name) → {number} Gets the tileset index based on its name. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `name` | string | The name of the tileset to get. | ##### Returns number - The index of the tileset in this tilemap, or null if not found. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 753](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L753)) ### getTileWorldXY(x, y, tileWidth, tileHeight, layer, nonNull) → {[Phaser.Tile](phaser.tile)} Gets a tile from the Tilemap layer. The coordinates are given in pixel values. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | X position to get the tile from (given in pixels) | | `y` | number | | | Y position to get the tile from (given in pixels) | | `tileWidth` | number | <optional> | | The width of the tiles. If not given the map default is used. | | `tileHeight` | number | <optional> | | The height of the tiles. If not given the map default is used. | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | | The layer to get the tile from. | | `nonNull` | boolean | <optional> | false | If true getTile won't return null for empty tiles, but a Tile object with an index of -1. | ##### Returns [Phaser.Tile](phaser.tile) - The tile at the given coordinates. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1517](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1517)) ### hasTile(x, y, layer) → {boolean} Checks if there is a tile at the given location. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | X position to check if a tile exists at (given in tile units, not pixels) | | `y` | number | Y position to check if a tile exists at (given in tile units, not pixels) | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | The layer to set as current. | ##### Returns boolean - True if there is a tile at the given location, otherwise false. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1240](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1240)) ### paste(x, y, tileblock, layer) Pastes a previously copied block of tile data into the given x/y coordinates. Data should have been prepared with Tilemap.copy. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `x` | number | | X position of the top left of the area to paste to (given in tiles, not pixels) | | `y` | number | | Y position of the top left of the area to paste to (given in tiles, not pixels) | | `tileblock` | array | | The block of tiles to paste. | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | The layer to paste the tiles into. | Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1605](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1605)) ### putTile(tile, x, y, layer) → {[Phaser.Tile](phaser.tile)} Puts a tile of the given index value at the coordinate specified. If you pass `null` as the tile it will pass your call over to Tilemap.removeTile instead. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `tile` | [Phaser.Tile](phaser.tile) | number | null | | The index of this tile to set or a Phaser.Tile object. If null the tile is removed from the map. | | `x` | number | | X position to place the tile (given in tile units, not pixels) | | `y` | number | | Y position to place the tile (given in tile units, not pixels) | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | The layer to modify. | ##### Returns [Phaser.Tile](phaser.tile) - The Tile object that was created or added to this map. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1315](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1315)) ### putTileWorldXY(tile, x, y, tileWidth, tileHeight, layer) → {[Phaser.Tile](phaser.tile)} Puts a tile into the Tilemap layer. The coordinates are given in pixel values. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `tile` | [Phaser.Tile](phaser.tile) | number | | The index of this tile to set or a Phaser.Tile object. | | `x` | number | | X position to insert the tile (given in pixels) | | `y` | number | | Y position to insert the tile (given in pixels) | | `tileWidth` | number | | The width of the tile in pixels. | | `tileHeight` | number | | The height of the tile in pixels. | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | The layer to modify. | ##### Returns [Phaser.Tile](phaser.tile) - The Tile object that was created or added to this map. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1386](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1386)) ### random(x, y, width, height, layer) Randomises a set of tiles in a given area. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `x` | number | | X position of the top left of the area to operate one, given in tiles, not pixels. | | `y` | number | | Y position of the top left of the area to operate one, given in tiles, not pixels. | | `width` | number | | The width in tiles of the area to operate on. | | `height` | number | | The height in tiles of the area to operate on. | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | The layer to operate on. | Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1758](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1758)) ### removeAllLayers() Removes all layers from this tile map. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1876](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1876)) ### removeTile(x, y, layer) → {[Phaser.Tile](phaser.tile)} Removes the tile located at the given coordinates and updates the collision data. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `x` | number | | X position to place the tile (given in tile units, not pixels) | | `y` | number | | Y position to place the tile (given in tile units, not pixels) | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | The layer to modify. | ##### Returns [Phaser.Tile](phaser.tile) - The Tile object that was removed from this map. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1262](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1262)) ### removeTileWorldXY(x, y, tileWidth, tileHeight, layer) → {[Phaser.Tile](phaser.tile)} Removes the tile located at the given coordinates and updates the collision data. The coordinates are given in pixel values. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `x` | number | | X position to insert the tile (given in pixels) | | `y` | number | | Y position to insert the tile (given in pixels) | | `tileWidth` | number | | The width of the tile in pixels. | | `tileHeight` | number | | The height of the tile in pixels. | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | The layer to modify. | ##### Returns [Phaser.Tile](phaser.tile) - The Tile object that was removed from this map. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1293](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1293)) ### replace(source, dest, x, y, width, height, layer) Scans the given area for tiles with an index matching `source` and updates their index to match `dest`. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `source` | number | | The tile index value to scan for. | | `dest` | number | | The tile index value to replace found tiles with. | | `x` | number | | X position of the top left of the area to operate one, given in tiles, not pixels. | | `y` | number | | Y position of the top left of the area to operate one, given in tiles, not pixels. | | `width` | number | | The width in tiles of the area to operate on. | | `height` | number | | The height in tiles of the area to operate on. | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | The layer to operate on. | Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1723](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1723)) ### searchTileIndex(index, skip, reverse, layer) → {[Phaser.Tile](phaser.tile)} Searches the entire map layer for the first tile matching the given index, then returns that Phaser.Tile object. If no match is found it returns null. The search starts from the top-left tile and continues horizontally until it hits the end of the row, then it drops down to the next column. If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to the top-left. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `index` | number | | | The tile index value to search for. | | `skip` | number | <optional> | 0 | The number of times to skip a matching tile before returning. | | `reverse` | number | <optional> | false | If true it will scan the layer in reverse, starting at the bottom-right. Otherwise it scans from the top-left. | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | | The layer to get the tile from. | ##### Returns [Phaser.Tile](phaser.tile) - The first (or n skipped) tile with the matching index. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1409](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1409)) ### setCollision(indexes, collides, layer, recalculate) Sets collision the given tile or tiles. You can pass in either a single numeric index or an array of indexes: [ 2, 3, 15, 20]. The `collides` parameter controls if collision will be enabled (true) or disabled (false). ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `indexes` | number | array | | | Either a single tile index, or an array of tile IDs to be checked for collision. | | `collides` | boolean | <optional> | true | If true it will enable collision. If false it will clear collision. | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | | The layer to operate on. If not given will default to this.currentLayer. | | `recalculate` | boolean | <optional> | true | Recalculates the tile faces after the update. | Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 842](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L842)) ### setCollisionBetween(start, stop, collides, layer, recalculate) Sets collision on a range of tiles where the tile IDs increment sequentially. Calling this with a start value of 10 and a stop value of 14 would set collision for tiles 10, 11, 12, 13 and 14. The `collides` parameter controls if collision will be enabled (true) or disabled (false). ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `start` | number | | | The first index of the tile to be set for collision. | | `stop` | number | | | The last index of the tile to be set for collision. | | `collides` | boolean | <optional> | true | If true it will enable collision. If false it will clear collision. | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | | The layer to operate on. If not given will default to this.currentLayer. | | `recalculate` | boolean | <optional> | true | Recalculates the tile faces after the update. | Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 880](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L880)) ### setCollisionByExclusion(indexes, collides, layer, recalculate) Sets collision on all tiles in the given layer, except for the IDs of those in the given array. The `collides` parameter controls if collision will be enabled (true) or disabled (false). ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `indexes` | array | | | An array of the tile IDs to not be counted for collision. | | `collides` | boolean | <optional> | true | If true it will enable collision. If false it will clear collision. | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | | The layer to operate on. If not given will default to this.currentLayer. | | `recalculate` | boolean | <optional> | true | Recalculates the tile faces after the update. | Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 917](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L917)) ### <internal> setCollisionByIndex(index, collides, layer, recalculate) Sets collision values on a tile in the set. You shouldn't usually call this method directly, instead use setCollision, setCollisionBetween or setCollisionByExclusion. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `index` | number | | | The index of the tile on the layer. | | `collides` | boolean | <optional> | true | If true it will enable collision on the tile. If false it will clear collision values from the tile. | | `layer` | number | <optional> | | The layer to operate on. If not given will default to this.currentLayer. | | `recalculate` | boolean | <optional> | true | Recalculates the tile faces after the update. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 951](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L951)) ### setLayer(layer) Sets the current layer to the given index. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | The layer to set as current. | Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1223](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1223)) ### setPreventRecalculate(value) Turn off/on the recalculation of faces for tile or collision updates. `setPreventRecalculate(true)` puts recalculation on hold while `setPreventRecalculate(false)` recalculates all the changed layers. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `value` | boolean | If true it will put the recalculation on hold. | Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1044](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1044)) ### setTileIndexCallback(indexes, callback, callbackContext, layer) Sets a global collision callback for the given tile index within the layer. This will affect all tiles on this layer that have the same index. If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it. If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `indexes` | number | array | | Either a single tile index, or an array of tile indexes to have a collision callback set for. | | `callback` | function | | The callback that will be invoked when the tile is collided with. | | `callbackContext` | object | | The context under which the callback is called. | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | The layer to operate on. If not given will default to this.currentLayer. | Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 779](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L779)) ### setTileLocationCallback(x, y, width, height, callback, callbackContext, layer) Sets a global collision callback for the given map location within the layer. This will affect all tiles on this layer found in the given area. If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it. If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `x` | number | | X position of the top left of the area to copy (given in tiles, not pixels) | | `y` | number | | Y position of the top left of the area to copy (given in tiles, not pixels) | | `width` | number | | The width of the area to copy (given in tiles, not pixels) | | `height` | number | | The height of the area to copy (given in tiles, not pixels) | | `callback` | function | | The callback that will be invoked when the tile is collided with. | | `callbackContext` | object | | The context under which the callback is called. | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | The layer to operate on. If not given will default to this.currentLayer. | Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 810](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L810)) ### setTileSize(tileWidth, tileHeight) Sets the base tile size for the map. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `tileWidth` | number | The width of the tiles the map uses for calculations. | | `tileHeight` | number | The height of the tiles the map uses for calculations. | Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 237](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L237)) ### shuffle(x, y, width, height, layer) Shuffles a set of tiles in a given area. It will only randomise the tiles in that area, so if they're all the same nothing will appear to have changed! ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `x` | number | | X position of the top left of the area to operate one, given in tiles, not pixels. | | `y` | number | | Y position of the top left of the area to operate one, given in tiles, not pixels. | | `width` | number | | The width in tiles of the area to operate on. | | `height` | number | | The height in tiles of the area to operate on. | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | The layer to operate on. | Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1803](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1803)) ### swap(tileA, tileB, x, y, width, height, layer) Scans the given area for tiles with an index matching tileA and swaps them with tileB. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `tileA` | number | | First tile index. | | `tileB` | number | | Second tile index. | | `x` | number | | X position of the top left of the area to operate one, given in tiles, not pixels. | | `y` | number | | Y position of the top left of the area to operate one, given in tiles, not pixels. | | `width` | number | | The width in tiles of the area to operate on. | | `height` | number | | The height in tiles of the area to operate on. | | `layer` | number | string | [Phaser.TilemapLayer](phaser.tilemaplayer) | <optional> | The layer to operate on. | Source code: [tilemap/Tilemap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js) ([Line 1640](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/Tilemap.js#L1640))
programming_docs
phaser Class: PIXI.CanvasMaskManager Class: PIXI.CanvasMaskManager ============================= Constructor ----------- ### new CanvasMaskManager() A set of functions used to handle masking. Source code: [pixi/renderers/canvas/utils/CanvasMaskManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/utils/CanvasMaskManager.js) ([Line 5](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/utils/CanvasMaskManager.js#L5)) Public Methods -------------- ### popMask(renderSession) Restores the current drawing context to the state it was before the mask was applied. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `renderSession` | Object | The renderSession whose context will be used for this mask manager. | Source code: [pixi/renderers/canvas/utils/CanvasMaskManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/utils/CanvasMaskManager.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/utils/CanvasMaskManager.js#L49)) ### pushMask(maskData, renderSession) This method adds it to the current stack of masks. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `maskData` | Object | the maskData that will be pushed | | `renderSession` | Object | The renderSession whose context will be used for this mask manager. | Source code: [pixi/renderers/canvas/utils/CanvasMaskManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/utils/CanvasMaskManager.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/utils/CanvasMaskManager.js#L17)) phaser Class: Phaser.Particles.Arcade Class: Phaser.Particles.Arcade ============================== Constructor ----------- ### new Arcade() Arcade Particles is a Particle System integrated with Arcade Physics. Source code: [particles/arcade/ArcadeParticles.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/ArcadeParticles.js) ([Line 12](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/ArcadeParticles.js#L12)) Classes ------- [Emitter](phaser.particles.arcade.emitter) phaser Class: Phaser.TimerEvent Class: Phaser.TimerEvent ======================== Constructor ----------- ### new TimerEvent(timer, delay, tick, repeatCount, loop, callback, callbackContext, arguments) A TimerEvent is a single event that is processed by a Phaser.Timer. It consists of a delay, which is a value in milliseconds after which the event will fire. When the event fires it calls a specific callback with the specified arguments. TimerEvents are removed by their parent timer once finished firing or repeating. Use [Phaser.Timer#add](phaser.timer#add), [Phaser.Timer#repeat](phaser.timer#repeat), or [Phaser.Timer#loop](phaser.timer#loop) methods to create a new event. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `timer` | [Phaser.Timer](phaser.timer) | The Timer object that this TimerEvent belongs to. | | `delay` | number | The delay in ms at which this TimerEvent fires. | | `tick` | number | The tick is the next game clock time that this event will fire at. | | `repeatCount` | number | If this TimerEvent repeats it will do so this many times. | | `loop` | boolean | True if this TimerEvent loops, otherwise false. | | `callback` | function | The callback that will be called when the TimerEvent occurs. | | `callbackContext` | object | The context in which the callback will be called. | | `arguments` | Array.<any> | Additional arguments to be passed to the callback. | Source code: [time/TimerEvent.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/TimerEvent.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/TimerEvent.js#L28)) Public Properties ----------------- ### args ##### Properties: | Name | Type | Description | | --- | --- | --- | | `arguments` | Array.<any> | Additional arguments to be passed to the callback. | Source code: [time/TimerEvent.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/TimerEvent.js) ([Line 70](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/TimerEvent.js#L70)) ### callback : Function The callback that will be called when the TimerEvent occurs. Source code: [time/TimerEvent.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/TimerEvent.js) ([Line 60](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/TimerEvent.js#L60)) ### callbackContext : Object The context in which the callback will be called. Source code: [time/TimerEvent.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/TimerEvent.js) ([Line 65](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/TimerEvent.js#L65)) ### delay : number The delay in ms at which this TimerEvent fires. Source code: [time/TimerEvent.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/TimerEvent.js) ([Line 40](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/TimerEvent.js#L40)) ### loop : boolean True if this TimerEvent loops, otherwise false. Source code: [time/TimerEvent.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/TimerEvent.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/TimerEvent.js#L55)) ### <internal> pendingDelete : boolean A flag that controls if the TimerEvent is pending deletion. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [time/TimerEvent.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/TimerEvent.js) ([Line 76](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/TimerEvent.js#L76)) ### repeatCount : number If this TimerEvent repeats it will do so this many times. Source code: [time/TimerEvent.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/TimerEvent.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/TimerEvent.js#L50)) ### tick : number The tick is the next game clock time that this event will fire at. Source code: [time/TimerEvent.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/TimerEvent.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/TimerEvent.js#L45)) ### <internal, readonly> timer : [Phaser.Timer](phaser.timer) The Timer object that this TimerEvent belongs to. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [time/TimerEvent.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/TimerEvent.js) ([Line 35](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/TimerEvent.js#L35)) phaser Class: Phaser.AnimationParser Class: Phaser.AnimationParser ============================= Constructor ----------- ### new AnimationParser() Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations. Source code: [animation/AnimationParser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationParser.js) ([Line 13](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationParser.js#L13)) Public Methods -------------- ### <static> JSONData(game, json) → {[Phaser.FrameData](phaser.framedata)} Parse the JSON data and extract the animation frame data from it. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | | `json` | object | The JSON data from the Texture Atlas. Must be in Array format. | ##### Returns [Phaser.FrameData](phaser.framedata) - A FrameData object containing the parsed frames. Source code: [animation/AnimationParser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationParser.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationParser.js#L93)) ### <static> JSONDataHash(game, json) → {[Phaser.FrameData](phaser.framedata)} Parse the JSON data and extract the animation frame data from it. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | | `json` | object | The JSON data from the Texture Atlas. Must be in JSON Hash format. | ##### Returns [Phaser.FrameData](phaser.framedata) - A FrameData object containing the parsed frames. Source code: [animation/AnimationParser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationParser.js) ([Line 204](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationParser.js#L204)) ### <static> JSONDataPyxel(game, json) → {[Phaser.FrameData](phaser.framedata)} Parse the JSON data and extract the animation frame data from it. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | | `json` | object | The JSON data from the Texture Atlas. Must be in Pyxel JSON format. | ##### Returns [Phaser.FrameData](phaser.framedata) - A FrameData object containing the parsed frames. Source code: [animation/AnimationParser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationParser.js) ([Line 147](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationParser.js#L147)) ### <static> spriteSheet(game, key, frameWidth, frameHeight, frameMax, margin, spacing) → {[Phaser.FrameData](phaser.framedata)} Parse a Sprite Sheet and extract the animation frame data from it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | | A reference to the currently running game. | | `key` | string | Image | | | The Game.Cache asset key of the Sprite Sheet image or an actual HTML Image element. | | `frameWidth` | number | | | The fixed width of each frame of the animation. | | `frameHeight` | number | | | The fixed height of each frame of the animation. | | `frameMax` | number | <optional> | -1 | The total number of animation frames to extract from the Sprite Sheet. The default value of -1 means "extract all frames". | | `margin` | number | <optional> | 0 | If the frames have been drawn with a margin, specify the amount here. | | `spacing` | number | <optional> | 0 | If the frames have been drawn with spacing between them, specify the amount here. | ##### Returns [Phaser.FrameData](phaser.framedata) - A FrameData object containing the parsed frames. Source code: [animation/AnimationParser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationParser.js) ([Line 15](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationParser.js#L15)) ### <static> XMLData(game, xml) → {[Phaser.FrameData](phaser.framedata)} Parse the XML data and extract the animation frame data from it. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | | `xml` | object | The XML data from the Texture Atlas. Must be in Starling XML format. | ##### Returns [Phaser.FrameData](phaser.framedata) - A FrameData object containing the parsed frames. Source code: [animation/AnimationParser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationParser.js) ([Line 261](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationParser.js#L261)) phaser Class: PIXI.Strip Class: PIXI.Strip ================= Constructor ----------- ### new Strip(texture, width, height) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `texture` | [PIXI.Texture](pixi.texture) | The texture to use | | `width` | Number | the width | | `height` | Number | the height | Source code: [pixi/extras/Strip.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js) ([Line 5](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js#L5)) Extends ------- * [PIXI.DisplayObjectContainer](pixi.displayobjectcontainer) Public Properties ----------------- ### blendMode : number The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode. Default Value * PIXI.blendModes.NORMAL; Source code: [pixi/extras/Strip.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js#L51)) ### canvasPadding : number Triangles in canvas mode are automatically antialiased, use this value to force triangles to overlap a bit with each other. Source code: [pixi/extras/Strip.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js) ([Line 60](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js#L60)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### dirty : boolean Whether the strip is dirty or not Source code: [pixi/extras/Strip.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js) ([Line 43](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js#L43)) ### height : number The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#height](pixi.displayobjectcontainer#height) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 600](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L600)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### texture : [PIXI.Texture](pixi.texture) The texture of the strip Source code: [pixi/extras/Strip.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js#L20)) ### width : number The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#width](pixi.displayobjectcontainer#width) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 571](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L571)) Public Methods -------------- ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### getBounds(matrix) → {Rectangle} Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `matrix` | Matrix | the transformation matrix of the sprite | ##### Returns Rectangle - the framing rectangle Source code: [pixi/extras/Strip.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js) ([Line 405](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/extras/Strip.js#L405)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the displayObjectContainer as a rectangle without any transformations. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.DisplayObjectContainer#getLocalBounds](pixi.displayobjectcontainer#getLocalBounds) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 437](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L437)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85))
programming_docs
phaser Class: Phaser.Button Class: Phaser.Button ==================== Constructor ----------- ### new Button(game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) Create a new `Button` object. A Button is a special type of Sprite that is set-up to handle Pointer events automatically. The four states a Button responds to are: * 'Over' - when the Pointer moves over the Button. This is also commonly known as 'hover'. * 'Out' - when the Pointer that was previously over the Button moves out of it. * 'Down' - when the Pointer is pressed down on the Button. I.e. touched on a touch enabled device or clicked with the mouse. * 'Up' - when the Pointer that was pressed down on the Button is released again. A different texture/frame and activation sound can be specified for any of the states. Frames can be specified as either an integer (the frame ID) or a string (the frame name); the same values that can be used with a Sprite constructor. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | | Current game instance. | | `x` | number | <optional> | 0 | X position of the Button. | | `y` | number | <optional> | 0 | Y position of the Button. | | `key` | string | <optional> | | The image key (in the Game.Cache) to use as the texture for this Button. | | `callback` | function | <optional> | | The function to call when this Button is pressed. | | `callbackContext` | object | <optional> | | The context in which the callback will be called (usually 'this'). | | `overFrame` | string | integer | <optional> | | The frame / frameName when the button is in the Over state. | | `outFrame` | string | integer | <optional> | | The frame / frameName when the button is in the Out state. | | `downFrame` | string | integer | <optional> | | The frame / frameName when the button is in the Down state. | | `upFrame` | string | integer | <optional> | | The frame / frameName when the button is in the Up state. | Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 35](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L35)) Extends ------- * [Phaser.Image](phaser.image) Public Properties ----------------- ### alive : boolean A useful flag to control if the Game Object is alive or dead. This is set automatically by the Health components `damage` method should the object run out of health. Or you can toggle it via your game code. This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. Inherited From * [Phaser.Component.LifeSpan#alive](phaser.component.lifespan#alive) Default Value * true Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L50)) ### anchor :Point The anchor sets the origin point of the texture. The default is 0,0 this means the texture's origin is the top left Setting than anchor to 0.5,0.5 means the textures origin is centered Setting the anchor to 1,1 would mean the textures origin points will be the bottom right corner Inherited From * [PIXI.Sprite#anchor](pixi.sprite#anchor) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L17)) ### angle : number The angle property is the rotation of the Game Object in *degrees* from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90. If you wish to work in radians instead of degrees you can use the property `rotation` instead. Working in radians is slightly faster as it doesn't have to perform any calculations. Inherited From * [Phaser.Component.Angle#angle](phaser.component.angle#angle) Source code: [gameobjects/components/Angle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js#L29)) ### animations : [Phaser.AnimationManager](phaser.animationmanager) If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. Through it you can create, play, pause and stop animations. Inherited From * [Phaser.Component.Core#animations](phaser.component.core#animations) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 193](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L193)) See * [Phaser.AnimationManager](phaser.animationmanager) ### autoCull : boolean A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, or you have tested performance and find it acceptable. Inherited From * [Phaser.Component.AutoCull#autoCull](phaser.component.autocull#autoCull) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L28)) ### blendMode : number The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode. Warning: You cannot have a blend mode and a filter active on the same Sprite. Doing so will render the sprite invisible. Inherited From * [PIXI.Sprite#blendMode](pixi.sprite#blendMode) Default Value * PIXI.blendModes.NORMAL; Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 82](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L82)) ### bottom : number The sum of the y and height properties. This is the same as `y + height - offsetY`. Inherited From * [Phaser.Component.Bounds#bottom](phaser.component.bounds#bottom) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 168](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L168)) ### cameraOffset : [Phaser.Point](phaser.point) The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. Inherited From * [Phaser.Component.FixedToCamera#cameraOffset](phaser.component.fixedtocamera#cameraOffset) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L86)) ### centerX : number The center x coordinate of the Game Object. This is the same as `(x - offsetX) + (width / 2)`. Inherited From * [Phaser.Component.Bounds#centerX](phaser.component.bounds#centerX) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L58)) ### centerY : number The center y coordinate of the Game Object. This is the same as `(y - offsetY) + (height / 2)`. Inherited From * [Phaser.Component.Bounds#centerY](phaser.component.bounds#centerY) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 80](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L80)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### <internal> components : Object The components this Game Object has installed. Inherited From * [Phaser.Component.Core#components](phaser.component.core#components) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 167](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L167)) ### cropRect : [Phaser.Rectangle](phaser.rectangle) The Rectangle used to crop the texture this Game Object uses. Set this property via `crop`. If you modify this property directly you must call `updateCrop` in order to have the change take effect. Inherited From * [Phaser.Component.Crop#cropRect](phaser.component.crop#cropRect) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L24)) ### data : Object An empty Object that belongs to this Game Object. This value isn't ever used internally by Phaser, but may be used by your own code, or by Phaser Plugins, to store data that needs to be associated with the Game Object, without polluting the Game Object directly. Inherited From * [Phaser.Component.Core#data](phaser.component.core#data) Default Value * {} Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 160](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L160)) ### debug : boolean A debug flag designed for use with `Game.enableStep`. Inherited From * [Phaser.Component.Core#debug](phaser.component.core#debug) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 218](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L218)) ### [readonly] destroyPhase : boolean As a Game Object runs through its destroy method this flag is set to true, and can be checked in any sub-systems or plugins it is being destroyed from. Inherited From * [Phaser.Component.Destroy#destroyPhase](phaser.component.destroy#destroyPhase) Source code: [gameobjects/components/Destroy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js#L22)) ### events : [Phaser.Events](phaser.events) All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this Game Object, or any of its components. Inherited From * [Phaser.Component.Core#events](phaser.component.core#events) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 185](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L185)) See * [Phaser.Events](phaser.events) ### exists : boolean Controls if this Sprite is processed by the core Phaser game loops and Group loops. Inherited From * [PIXI.Sprite#exists](pixi.sprite#exists) Default Value * true Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 103](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L103)) ### fixedToCamera : boolean A Game Object that is "fixed" to the camera uses its x/y coordinates as offsets from the top left of the camera during rendering. The values are adjusted at the rendering stage, overriding the Game Objects actual world position. The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times regardless where in the world the camera is. The offsets are stored in the `cameraOffset` property. Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. Inherited From * [Phaser.Component.FixedToCamera#fixedToCamera](phaser.component.fixedtocamera#fixedToCamera) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 56](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L56)) ### forceOut : boolean | [Phaser.PointerMode](phaser.pointermode) When the Button is touched / clicked and then released you can force it to enter a state of "out" instead of "up". This can also accept a pointer mode bitmask for more refined control. ##### Type * boolean | [Phaser.PointerMode](phaser.pointermode) Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 199](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L199)) ### frame : integer Gets or sets the current frame index of the texture being used to render this Game Object. To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use, for example: `player.frame = 4`. If the frame index given doesn't exist it will revert to the first frame found in the texture. If you are using a texture atlas then you should use the `frameName` property instead. If you wish to fully replace the texture being used see `loadTexture`. Inherited From * [Phaser.Component.LoadTexture#frame](phaser.component.loadtexture#frame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 254](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L254)) ### frameName : string Gets or sets the current frame name of the texture being used to render this Game Object. To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use, for example: `player.frameName = "idle"`. If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning. If you are using a sprite sheet then you should use the `frame` property instead. If you wish to fully replace the texture being used see `loadTexture`. Inherited From * [Phaser.Component.LoadTexture#frameName](phaser.component.loadtexture#frameName) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 279](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L279)) ### freezeFrames : boolean When true the the texture frame will not be automatically switched on up/down/over/out events. Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 189](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L189)) ### [readonly] fresh : boolean A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. This property is mostly used internally by the physics systems, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#fresh](phaser.component.core#fresh) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 248](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L248)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Inherited From * [Phaser.Component.Core#game](phaser.component.core#game) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 142](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L142)) ### height : number The height of the sprite, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.Sprite#height](pixi.sprite#height) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 144](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L144)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### [readonly] inCamera : boolean Checks if the Game Objects bounds intersect with the Game Camera bounds. Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. Inherited From * [Phaser.Component.AutoCull#inCamera](phaser.component.autocull#inCamera) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L37)) ### input : [Phaser.InputHandler](phaser.inputhandler) | null The Input Handler for this Game Object. By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`. After you have done this, this property will be a reference to the Phaser InputHandler. ##### Type * [Phaser.InputHandler](phaser.inputhandler) | null Inherited From * [Phaser.Component.InputEnabled#input](phaser.component.inputenabled#input) Source code: [gameobjects/components/InputEnabled.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js#L24)) ### inputEnabled : boolean By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created for this Game Object and it will then start to process click / touch events and more. You can then access the Input Handler via `this.input`. Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`. If you set this property to false it will stop the Input Handler from processing any more input events. If you want to *temporarily* disable input for a Game Object, then it's better to set `input.enabled = false`, as it won't reset any of the Input Handlers internal properties. You can then toggle this back on as needed. Inherited From * [Phaser.Component.InputEnabled#inputEnabled](phaser.component.inputenabled#inputEnabled) Source code: [gameobjects/components/InputEnabled.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js#L42)) ### justReleasedPreventsOver : [Phaser.PointerMode](phaser.pointermode) Suppress the over event if a pointer was just released and it matches the given pointer mode bitmask. This behavior was introduced in Phaser 2.3.1; this property is a soft-revert of the change. Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 182](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L182)) ### key : string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) The key of the image or texture used by this Game Object during rendering. If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. ##### Type * string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) Inherited From * [Phaser.Component.Core#key](phaser.component.core#key) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 203](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L203)) ### left : number The left coordinate of the Game Object. This is the same as `x - offsetX`. Inherited From * [Phaser.Component.Bounds#left](phaser.component.bounds#left) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 102](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L102)) ### lifespan : number The lifespan allows you to give a Game Object a lifespan in milliseconds. Once the Game Object is 'born' you can set this to a positive value. It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. When it reaches zero it will call the `kill` method. Very handy for particles, bullets, collectibles, or any other short-lived entity. Inherited From * [Phaser.Component.LifeSpan#lifespan](phaser.component.lifespan#lifespan) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 65](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L65)) ### name : string A user defined name given to this Game Object. This value isn't ever used internally by Phaser, it is meant as a game level property. Inherited From * [Phaser.Component.Core#name](phaser.component.core#name) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 150](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L150)) ### [readonly] offsetX : number The amount the Game Object is visually offset from its x coordinate. This is the same as `width * anchor.x`. It will only be > 0 if anchor.x is not equal to zero. Inherited From * [Phaser.Component.Bounds#offsetX](phaser.component.bounds#offsetX) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L24)) ### [readonly] offsetY : number The amount the Game Object is visually offset from its y coordinate. This is the same as `height * anchor.y`. It will only be > 0 if anchor.y is not equal to zero. Inherited From * [Phaser.Component.Bounds#offsetY](phaser.component.bounds#offsetY) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L42)) ### [readonly] onDownSound : [Phaser.Sound](phaser.sound) | [Phaser.AudioSprite](phaser.audiosprite) | null The Sound to be played when this Buttons Down state is activated. ##### Type * [Phaser.Sound](phaser.sound) | [Phaser.AudioSprite](phaser.audiosprite) | null Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 105](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L105)) ### [readonly] onDownSoundMarker : string The Sound Marker used in conjunction with the onDownSound. Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 133](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L133)) ### onInputDown : [Phaser.Signal](phaser.signal) The Signal (or event) dispatched when this Button is in an Down state. Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 158](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L158)) ### onInputOut : [Phaser.Signal](phaser.signal) The Signal (or event) dispatched when this Button is in an Out state. Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 152](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L152)) ### onInputOver : [Phaser.Signal](phaser.signal) The Signal (or event) dispatched when this Button is in an Over state. Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 146](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L146)) ### onInputUp : [Phaser.Signal](phaser.signal) The Signal (or event) dispatched when this Button is in an Up state. Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 164](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L164)) ### [readonly] onOutSound : [Phaser.Sound](phaser.sound) | [Phaser.AudioSprite](phaser.audiosprite) | null The Sound to be played when this Buttons Out state is activated. ##### Type * [Phaser.Sound](phaser.sound) | [Phaser.AudioSprite](phaser.audiosprite) | null Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L98)) ### [readonly] onOutSoundMarker : string The Sound Marker used in conjunction with the onOutSound. Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 126](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L126)) ### onOverMouseOnly : boolean If true then onOver events (such as onOverSound) will only be triggered if the Pointer object causing them was the Mouse Pointer. The frame will still be changed as applicable. Default Value * true Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 173](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L173)) ### [readonly] onOverSound : [Phaser.Sound](phaser.sound) | [Phaser.AudioSprite](phaser.audiosprite) | null The Sound to be played when this Buttons Over state is activated. ##### Type * [Phaser.Sound](phaser.sound) | [Phaser.AudioSprite](phaser.audiosprite) | null Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 91](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L91)) ### [readonly] onOverSoundMarker : string The Sound Marker used in conjunction with the onOverSound. Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 119](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L119)) ### [readonly] onUpSound : [Phaser.Sound](phaser.sound) | [Phaser.AudioSprite](phaser.audiosprite) | null The Sound to be played when this Buttons Up state is activated. ##### Type * [Phaser.Sound](phaser.sound) | [Phaser.AudioSprite](phaser.audiosprite) | null Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L112)) ### [readonly] onUpSoundMarker : string The Sound Marker used in conjunction with the onUpSound. Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 140](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L140)) ### pendingDestroy : boolean A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. You can set it directly to allow you to flag an object to be destroyed on its next update. This is extremely useful if you wish to destroy an object from within one of its own callbacks such as with Buttons or other Input events. Inherited From * [Phaser.Component.Core#pendingDestroy](phaser.component.core#pendingDestroy) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 259](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L259)) ### [readonly] physicsType : number The const physics body type of this object. Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 56](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L56)) ### [readonly] previousPosition : [Phaser.Point](phaser.point) The position the Game Object was located in the previous frame. Inherited From * [Phaser.Component.Core#previousPosition](phaser.component.core#previousPosition) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 225](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L225)) ### [readonly] previousRotation : number The rotation the Game Object was in set to in the previous frame. Value is in radians. Inherited From * [Phaser.Component.Core#previousRotation](phaser.component.core#previousRotation) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L232)) ### [readonly] renderOrderID : number The render order ID is used internally by the renderer and Input Manager and should not be modified. This property is mostly used internally by the renderers, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#renderOrderID](phaser.component.core#renderOrderID) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 240](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L240)) ### right : number The right coordinate of the Game Object. This is the same as `x + width - offsetX`. Inherited From * [Phaser.Component.Bounds#right](phaser.component.bounds#right) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L124)) ### scaleMax : [Phaser.Point](phaser.point) The maximum scale this Game Object will scale up to. It allows you to prevent a parent from scaling this Game Object higher than the given value. Set it to `null` to remove the limit. Inherited From * [Phaser.Component.ScaleMinMax#scaleMax](phaser.component.scaleminmax#scaleMax) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L46)) ### scaleMin : [Phaser.Point](phaser.point) The minimum scale this Game Object will scale down to. It allows you to prevent a parent from scaling this Game Object lower than the given value. Set it to `null` to remove the limit. Inherited From * [Phaser.Component.ScaleMinMax#scaleMin](phaser.component.scaleminmax#scaleMin) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 36](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L36)) ### shader : [PIXI.AbstractFilter](pixi.abstractfilter) The shader that will be used to render this Sprite. Set to null to remove a current shader. Inherited From * [PIXI.Sprite#shader](pixi.sprite#shader) Default Value * null Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L93)) ### smoothed : boolean Enable or disable texture smoothing for this Game Object. It only takes effect if the Game Object is using an image based texture. Smoothing is enabled by default. Inherited From * [Phaser.Component.Smoothed#smoothed](phaser.component.smoothed#smoothed) Source code: [gameobjects/components/Smoothed.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Smoothed.js) ([Line 25](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Smoothed.js#L25)) ### texture : [PIXI.Texture](pixi.texture) The texture that the sprite is using Inherited From * [PIXI.Sprite#texture](pixi.sprite#texture) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L28)) ### tint : number The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. Inherited From * [PIXI.Sprite#tint](pixi.sprite#tint) Default Value * 0xFFFFFF Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L54)) ### tintedTexture :Canvas A canvas that contains the tinted version of the Sprite (in Canvas mode, WebGL doesn't populate this) Inherited From * [PIXI.Sprite#tintedTexture](pixi.sprite#tintedTexture) Default Value * null Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 73](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L73)) ### top : number The y coordinate of the Game Object. This is the same as `y - offsetY`. Inherited From * [Phaser.Component.Bounds#top](phaser.component.bounds#top) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 146](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L146)) ### transformCallback : Function The callback that will apply any scale limiting to the worldTransform. Inherited From * [Phaser.Component.ScaleMinMax#transformCallback](phaser.component.scaleminmax#transformCallback) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L20)) ### transformCallbackContext : Object The context under which `transformCallback` is called. Inherited From * [Phaser.Component.ScaleMinMax#transformCallbackContext](phaser.component.scaleminmax#transformCallbackContext) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L26)) ### [readonly] type : number The Phaser Object Type. Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L50)) ### width : number The width of the sprite, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.Sprite#width](pixi.sprite#width) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 125](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L125)) ### world : [Phaser.Point](phaser.point) The world coordinates of this Game Object in pixels. Depending on where in the display list this Game Object is placed this value can differ from `position`, which contains the x/y coordinates relative to the Game Objects parent. Inherited From * [Phaser.Component.Core#world](phaser.component.core#world) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 211](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L211)) ### [readonly] z : number The z depth of this Game Object within its parent Group. No two objects in a Group can have the same z value. This value is adjusted automatically whenever the Group hierarchy changes. If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. Inherited From * [Phaser.Component.Core#z](phaser.component.core#z) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 177](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L177)) Public Methods -------------- ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### alignIn(container, position, offsetX, offsetY) → {Object} Aligns this Game Object within another Game Object, or Rectangle, known as the 'container', to one of 9 possible positions. The container must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the container. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the container, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `container` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Inherited From * [Phaser.Component.Bounds#alignIn](phaser.component.bounds#alignIn) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 223](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L223)) ### alignTo(parent, position, offsetX, offsetY) → {Object} Aligns this Game Object to the side of another Game Object, or Rectangle, known as the 'parent', in one of 11 possible positions. The parent must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the parent. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the parent, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Inherited From * [Phaser.Component.Bounds#alignTo](phaser.component.bounds#alignTo) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 321](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L321)) ### bringToTop() → {PIXI.DisplayObject} Brings this Game Object to the top of its parents display list. Visually this means it will render over the top of any old child in the same Group. If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#bringToTop](phaser.component.bringtotop#bringToTop) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L24)) ### clearFrames() Clears all of the frames set on this Button. Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 233](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L233)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### crop(rect, copy) Crop allows you to crop the texture being used to display this Game Object. Setting a crop rectangle modifies the core texture frame. The Game Object width and height properties will be adjusted accordingly. Cropping takes place from the top-left and can be modified in real-time either by providing an updated rectangle object to this method, or by modifying `cropRect` property directly and then calling `updateCrop`. The rectangle object given to this method can be either a `Phaser.Rectangle` or any other object so long as it has public `x`, `y`, `width`, `height`, `right` and `bottom` properties. A reference to the rectangle is stored in `cropRect` unless the `copy` parameter is `true`, in which case the values are duplicated to a local object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `rect` | [Phaser.Rectangle](phaser.rectangle) | | | The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle. | | `copy` | boolean | <optional> | false | If false `cropRect` will be stored as a reference to the given rect. If true it will copy the rect values into a local Phaser Rectangle object stored in cropRect. | Inherited From * [Phaser.Component.Crop#crop](phaser.component.crop#crop) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L49)) ### destroy(destroyChildren, destroyTexture) Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present and nulls its reference to `game`, freeing it up for garbage collection. If this Game Object has the Events component it will also dispatch the `onDestroy` event. You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've more than one Game Object sharing the same BaseTexture. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroyChildren` | boolean | <optional> | true | Should every child of this object have its destroy method called as well? | | `destroyTexture` | boolean | <optional> | false | Destroy the BaseTexture this Game Object is using? Note that if another Game Object is sharing the same BaseTexture it will invalidate it. | Inherited From * [Phaser.Component.Destroy#destroy](phaser.component.destroy#destroy) Source code: [gameobjects/components/Destroy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js#L37)) ### getBounds(matrix) → {Rectangle} Returns the bounds of the Sprite as a rectangle. The bounds calculation takes the worldTransform into account. It is important to note that the transform is not updated when you call this method. So if this Sprite is the child of a Display Object which has had its transform updated since the last render pass, those changes will not yet have been applied to this Sprites worldTransform. If you need to ensure that all parent transforms are factored into this getBounds operation then you should call `updateTransform` on the root most object in this Sprites display list first. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `matrix` | Matrix | the transformation matrix of the sprite | ##### Returns Rectangle - the framing rectangle Inherited From * [PIXI.Sprite#getBounds](pixi.sprite#getBounds) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 199](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L199)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the Sprite as a rectangle. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.Sprite#getLocalBounds](pixi.sprite#getLocalBounds) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 315](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L315)) ### kill() → {PIXI.DisplayObject} Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false. It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal. Note that killing a Game Object is a way for you to quickly recycle it in an object pool, it doesn't destroy the object or free it up from memory. If you don't need this Game Object any more you should call `destroy` instead. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.LifeSpan#kill](phaser.component.lifespan#kill) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 113](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L113)) ### loadTexture(key, frame, stopAnimation) Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache. If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead. You should only use `loadTexture` if you want to replace the base texture entirely. Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU. You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite. Doing this then sets the key to be the `frame` argument (the frame is set to zero). This allows you to create sprites using `load.image` during development, and then change them to use a Texture Atlas later in development by simply searching your code for 'PENDING\_ATLAS' and swapping it to be the key of the atlas data. Note: You cannot use a RenderTexture as a texture for a TileSprite. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | | `stopAnimation` | boolean | <optional> | true | If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing. | Inherited From * [Phaser.Component.LoadTexture#loadTexture](phaser.component.loadtexture#loadTexture) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L51)) ### moveDown() → {PIXI.DisplayObject} Moves this Game Object down one place in its parents display list. This call has no effect if the Game Object is already at the bottom of the display list. If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#moveDown](phaser.component.bringtotop#moveDown) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L87)) ### moveUp() → {PIXI.DisplayObject} Moves this Game Object up one place in its parents display list. This call has no effect if the Game Object is already at the top of the display list. If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#moveUp](phaser.component.bringtotop#moveUp) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 66](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L66)) ### <internal> onInputDownHandler(sprite, pointer) Internal function that handles input events. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `sprite` | [Phaser.Button](phaser.button) | The Button that the event occurred on. | | `pointer` | [Phaser.Pointer](phaser.pointer) | The Pointer that activated the Button. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 531](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L531)) ### <internal> onInputOutHandler(sprite, pointer) Internal function that handles input events. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `sprite` | [Phaser.Button](phaser.button) | The Button that the event occurred on. | | `pointer` | [Phaser.Pointer](phaser.pointer) | The Pointer that activated the Button. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 511](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L511)) ### <internal> onInputOverHandler(sprite, pointer) Internal function that handles input events. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `sprite` | [Phaser.Button](phaser.button) | The Button that the event occurred on. | | `pointer` | [Phaser.Pointer](phaser.pointer) | The Pointer that activated the Button. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 478](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L478)) ### <internal> onInputUpHandler(sprite, pointer) Internal function that handles input events. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `sprite` | [Phaser.Button](phaser.button) | The Button that the event occurred on. | | `pointer` | [Phaser.Pointer](phaser.pointer) | The Pointer that activated the Button. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 551](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L551)) ### overlap(displayObject) → {boolean} Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object, which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result. This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result. Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency. It should be fine for low-volume testing where physics isn't required. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `displayObject` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.TileSprite](phaser.tilesprite) | [Phaser.Button](phaser.button) | PIXI.DisplayObject | The display object to check against. | ##### Returns boolean - True if the bounds of this Game Object intersects at any point with the bounds of the given display object. Inherited From * [Phaser.Component.Overlap#overlap](phaser.component.overlap#overlap) Source code: [gameobjects/components/Overlap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Overlap.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Overlap.js#L29)) ### play(name, frameRate, loop, killOnComplete) → {[Phaser.Animation](phaser.animation)} Plays an Animation. The animation should have previously been created via `animations.add`. If the animation is already playing calling this again won't do anything. If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `name` | string | | | The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'. | | `frameRate` | number | <optional> | null | The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. | | `loop` | boolean | <optional> | false | Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. | | `killOnComplete` | boolean | <optional> | false | If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. | ##### Returns [Phaser.Animation](phaser.animation) - A reference to playing Animation. Inherited From * [Phaser.Component.Animation#play](phaser.component.animation#play) Source code: [gameobjects/components/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Animation.js) ([Line 31](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Animation.js#L31)) ### <internal> postUpdate() Internal method called by the World postUpdate cycle. Inherited From * [Phaser.Component.Core#postUpdate](phaser.component.core#postUpdate) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 338](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L338)) ### preUpdate() Automatically called by World.preUpdate. Inherited From * [Phaser.Image#preUpdate](phaser.image#preUpdate) Source code: [gameobjects/Image.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Image.js) ([Line 79](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Image.js#L79)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### <internal> removedFromWorld() Called when this Button is removed from the World. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 244](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L244)) ### reset(x, y, health) → {PIXI.DisplayObject} Resets the Game Object. This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`, `visible` and `renderable` to true. If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value. If this Game Object has a Physics Body it will reset the Body. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate (in world space) to position the Game Object at. | | `y` | number | | | The y coordinate (in world space) to position the Game Object at. | | `health` | number | <optional> | 1 | The health to give the Game Object if it has the Health component. | ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.Reset#reset](phaser.component.reset#reset) Source code: [gameobjects/components/Reset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Reset.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Reset.js#L30)) ### resetFrame() Resets the texture frame dimensions that the Game Object uses for rendering. Inherited From * [Phaser.Component.LoadTexture#resetFrame](phaser.component.loadtexture#resetFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L232)) ### resizeFrame(parent, width, height) Resizes the Frame dimensions that the Game Object uses for rendering. You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData it can be useful to adjust the dimensions directly in this way. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `parent` | object | The parent texture object that caused the resize, i.e. a Phaser.Video object. | | `width` | integer | The new width of the texture. | | `height` | integer | The new height of the texture. | Inherited From * [Phaser.Component.LoadTexture#resizeFrame](phaser.component.loadtexture#resizeFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 220](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L220)) ### revive(health) → {PIXI.DisplayObject} Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `health` | number | <optional> | 100 | The health to give the Game Object. Only set if the GameObject has the Health component. | ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.LifeSpan#revive](phaser.component.lifespan#revive) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L78)) ### sendToBack() → {PIXI.DisplayObject} Sends this Game Object to the bottom of its parents display list. Visually this means it will render below all other children in the same Group. If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#sendToBack](phaser.component.bringtotop#sendToBack) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L45)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### setDownSound(sound, marker) The Sound to be played when a Pointer presses down on this Button. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `sound` | [Phaser.Sound](phaser.sound) | [Phaser.AudioSprite](phaser.audiosprite) | | The Sound that will be played. | | `marker` | string | <optional> | A Sound Marker that will be used in the playback. | Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 450](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L450)) ### setFrame(frame) Sets the texture frame the Game Object uses for rendering. This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `frame` | [Phaser.Frame](phaser.frame) | The Frame to be used by the texture. | Inherited From * [Phaser.Component.LoadTexture#setFrame](phaser.component.loadtexture#setFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 155](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L155)) ### setFrames(overFrame, outFrame, downFrame, upFrame) Used to manually set the frames that will be used for the different states of the Button. Frames can be specified as either an integer (the frame ID) or a string (the frame name); these are the same values that can be used with a Sprite constructor. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `overFrame` | string | integer | <optional> | The frame / frameName when the button is in the Over state. | | `outFrame` | string | integer | <optional> | The frame / frameName when the button is in the Out state. | | `downFrame` | string | integer | <optional> | The frame / frameName when the button is in the Down state. | | `upFrame` | string | integer | <optional> | The frame / frameName when the button is in the Up state. | Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 320](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L320)) ### setOutSound(sound, marker) The Sound to be played when a Pointer moves out of this Button. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `sound` | [Phaser.Sound](phaser.sound) | [Phaser.AudioSprite](phaser.audiosprite) | | The Sound that will be played. | | `marker` | string | <optional> | A Sound Marker that will be used in the playback. | Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 436](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L436)) ### setOverSound(sound, marker) The Sound to be played when a Pointer moves over this Button. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `sound` | [Phaser.Sound](phaser.sound) | [Phaser.AudioSprite](phaser.audiosprite) | | The Sound that will be played. | | `marker` | string | <optional> | A Sound Marker that will be used in the playback. | Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 422](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L422)) ### setScaleMinMax(minX, minY, maxX, maxY) Sets the scaleMin and scaleMax values. These values are used to limit how far this Game Object will scale based on its parent. For example if this Game Object has a `minScale` value of 1 and its parent has a `scale` value of 0.5, the 0.5 will be ignored and the scale value of 1 will be used, as the parents scale is lower than the minimum scale this Game Object should adhere to. By setting these values you can carefully control how Game Objects deal with responsive scaling. If only one parameter is given then that value will be used for both scaleMin and scaleMax: `setScaleMinMax(1)` = scaleMin.x, scaleMin.y, scaleMax.x and scaleMax.y all = 1 If only two parameters are given the first is set as scaleMin.x and y and the second as scaleMax.x and y: `setScaleMinMax(0.5, 2)` = scaleMin.x and y = 0.5 and scaleMax.x and y = 2 If you wish to set `scaleMin` with different values for x and y then either modify Game Object.scaleMin directly, or pass `null` for the `maxX` and `maxY` parameters. Call `setScaleMinMax(null)` to clear all previously set values. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `minX` | number | null | The minimum horizontal scale value this Game Object can scale down to. | | `minY` | number | null | The minimum vertical scale value this Game Object can scale down to. | | `maxX` | number | null | The maximum horizontal scale value this Game Object can scale up to. | | `maxY` | number | null | The maximum vertical scale value this Game Object can scale up to. | Inherited From * [Phaser.Component.ScaleMinMax#setScaleMinMax](phaser.component.scaleminmax#setScaleMinMax) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 110](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L110)) ### setSounds(overSound, overMarker, downSound, downMarker, outSound, outMarker, upSound, upMarker) Sets the sounds to be played whenever this Button is interacted with. Sounds can be either full Sound objects, or markers pointing to a section of a Sound object. The most common forms of sounds are 'hover' effects and 'click' effects, which is why the order of the parameters is overSound then downSound. Call this function with no parameters to reset all sounds on this Button. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `overSound` | [Phaser.Sound](phaser.sound) | [Phaser.AudioSprite](phaser.audiosprite) | <optional> | Over Button Sound. | | `overMarker` | string | <optional> | Over Button Sound Marker. | | `downSound` | [Phaser.Sound](phaser.sound) | [Phaser.AudioSprite](phaser.audiosprite) | <optional> | Down Button Sound. | | `downMarker` | string | <optional> | Down Button Sound Marker. | | `outSound` | [Phaser.Sound](phaser.sound) | [Phaser.AudioSprite](phaser.audiosprite) | <optional> | Out Button Sound. | | `outMarker` | string | <optional> | Out Button Sound Marker. | | `upSound` | [Phaser.Sound](phaser.sound) | [Phaser.AudioSprite](phaser.audiosprite) | <optional> | Up Button Sound. | | `upMarker` | string | <optional> | Up Button Sound Marker. | Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 396](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L396)) ### setTexture(texture, destroy) Sets the texture of the sprite. Be warned that this doesn't remove or destroy the previous texture this Sprite was using. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `texture` | [PIXI.Texture](pixi.texture) | | | The PIXI texture that is displayed by the sprite | | `destroy` | Boolean | <optional> | false | Call Texture.destroy on the current texture before replacing it with the new one? | Inherited From * [PIXI.Sprite#setTexture](pixi.sprite#setTexture) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 163](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L163)) ### setUpSound(sound, marker) The Sound to be played when a Pointer has pressed down and is released from this Button. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `sound` | [Phaser.Sound](phaser.sound) | [Phaser.AudioSprite](phaser.audiosprite) | | The Sound that will be played. | | `marker` | string | <optional> | A Sound Marker that will be used in the playback. | Source code: [gameobjects/Button.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js) ([Line 464](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Button.js#L464)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) ### update() Override this method in your own custom objects to handle any update requirements. It is called immediately after `preUpdate` and before `postUpdate`. Remember if this Game Object has any children you should call update on those too. Inherited From * [Phaser.Component.Core#update](phaser.component.core#update) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 328](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L328)) ### updateCrop() If you have set a crop rectangle on this Game Object via `crop` and since modified the `cropRect` property, or the rectangle it references, then you need to update the crop frame by calling this method. Inherited From * [Phaser.Component.Crop#updateCrop](phaser.component.crop#updateCrop) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L86))
programming_docs
phaser Class: Phaser.FlexGrid Class: Phaser.FlexGrid ====================== Constructor ----------- ### new FlexGrid(manager, width, height) WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete. Please try to avoid using in production games with a long time to build. This is also why the documentation is incomplete. FlexGrid is a a responsive grid manager that works in conjunction with the ScaleManager RESIZE scaling mode and FlexLayers to provide for game object positioning in a responsive manner. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `manager` | [Phaser.ScaleManager](phaser.scalemanager) | The ScaleManager. | | `width` | number | The width of the game. | | `height` | number | The height of the game. | Source code: [core/FlexGrid.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js) ([Line 21](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js#L21)) Public Properties ----------------- ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Source code: [core/FlexGrid.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js#L26)) ### manager : [Phaser.ScaleManager](phaser.scalemanager) A reference to the ScaleManager. Source code: [core/FlexGrid.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js) ([Line 31](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js#L31)) ### [readonly] positionCustom ##### Properties: | Name | Type | Description | | --- | --- | --- | | `position` | [Phaser.Point](phaser.point) | - | Source code: [core/FlexGrid.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js#L46)) ### [readonly] scaleCustom ##### Properties: | Name | Type | Description | | --- | --- | --- | | `scaleFactor` | [Phaser.Point](phaser.point) | The scale factor based on the game dimensions vs. the scaled dimensions. | Source code: [core/FlexGrid.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js#L55)) Public Methods -------------- ### createCustomLayer(width, height, children) → {[Phaser.FlexLayer](phaser.flexlayer)} A custom layer is centered on the game and maintains its aspect ratio as it scales up and down. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `width` | number | | Width of this layer in pixels. | | `height` | number | | Height of this layer in pixels. | | `children` | Array.<PIXI.DisplayObject> | <optional> | An array of children that are used to populate the FlexLayer. | ##### Returns [Phaser.FlexLayer](phaser.flexlayer) - The Layer object. Source code: [core/FlexGrid.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js) ([Line 104](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js#L104)) ### createFixedLayer(children) → {[Phaser.FlexLayer](phaser.flexlayer)} A fixed layer is centered on the game and is the size of the required dimensions and is never scaled. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `children` | Array.<PIXI.DisplayObject> | <optional> | An array of children that are used to populate the FlexLayer. | ##### Returns [Phaser.FlexLayer](phaser.flexlayer) - The Layer object. Source code: [core/FlexGrid.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js) ([Line 194](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js#L194)) ### createFluidLayer(children) → {[Phaser.FlexLayer](phaser.flexlayer)} A fluid layer is centered on the game and maintains its aspect ratio as it scales up and down. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `children` | array | <optional> | An array of children that are used to populate the FlexLayer. | ##### Returns [Phaser.FlexLayer](phaser.flexlayer) - The Layer object. Source code: [core/FlexGrid.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js) ([Line 141](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js#L141)) ### createFullLayer(children) → {[Phaser.FlexLayer](phaser.flexlayer)} A full layer is placed at 0,0 and extends to the full size of the game. Children are scaled according to the fluid ratios. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `children` | array | <optional> | An array of children that are used to populate the FlexLayer. | ##### Returns [Phaser.FlexLayer](phaser.flexlayer) - The Layer object. Source code: [core/FlexGrid.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js) ([Line 170](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js#L170)) ### debug() Call in the render function to output the bounds rects. Source code: [core/FlexGrid.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js) ([Line 299](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js#L299)) ### fitSprite(sprite) Fits a sprites width to the bounds. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `sprite` | [Phaser.Sprite](phaser.sprite) | The Sprite to fit. | Source code: [core/FlexGrid.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js) ([Line 284](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js#L284)) ### onResize(width, height) Called when the game container changes dimensions. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `width` | number | The new width of the game container. | | `height` | number | The new height of the game container. | Source code: [core/FlexGrid.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js) ([Line 240](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js#L240)) ### refresh() Updates all internal vars such as the bounds and scale values. Source code: [core/FlexGrid.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js) ([Line 256](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js#L256)) ### reset() Resets the layer children references Source code: [core/FlexGrid.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js) ([Line 218](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js#L218)) ### setSize(width, height) Sets the core game size. This resets the w/h parameters and bounds. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `width` | number | The new dimensions. | | `height` | number | The new dimensions. | Source code: [core/FlexGrid.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js) ([Line 77](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexGrid.js#L77)) phaser Class: Phaser.Easing.Back Class: Phaser.Easing.Back ========================= Constructor ----------- ### new Back() Back easing. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 457](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L457)) Public Methods -------------- ### In(k) → {number} Back ease-in. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 459](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L459)) ### InOut(k) → {number} Back ease-in/out. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 487](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L487)) ### Out(k) → {number} Back ease-out. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 473](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L473)) phaser Class: PIXI.RenderTexture Class: PIXI.RenderTexture ========================= Constructor ----------- ### new RenderTexture(width, height, renderer, scaleMode, resolution) A RenderTexture is a special texture that allows any Pixi display object to be rendered to it. **Hint**: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded otherwise black rectangles will be drawn instead. A RenderTexture takes a snapshot of any Display Object given to its render method. The position and rotation of the given Display Objects is ignored. For example: var renderTexture = new PIXI.RenderTexture(800, 600); var sprite = PIXI.Sprite.fromImage("spinObj\_01.png"); sprite.position.x = 800/2; sprite.position.y = 600/2; sprite.anchor.x = 0.5; sprite.anchor.y = 0.5; renderTexture.render(sprite); The Sprite in this case will be rendered to a position of 0,0. To render this sprite at its actual position a DisplayObjectContainer should be used: var doc = new PIXI.DisplayObjectContainer(); doc.addChild(sprite); renderTexture.render(doc); // Renders to center of renderTexture ##### Parameters | Name | Type | Description | | --- | --- | --- | | `width` | Number | The width of the render texture | | `height` | Number | The height of the render texture | | `renderer` | [PIXI.CanvasRenderer](pixi.canvasrenderer) | [PIXI.WebGLRenderer](pixi.webglrenderer) | The renderer used for this RenderTexture | | `scaleMode` | Number | See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values | | `resolution` | Number | The resolution of the texture being generated | Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 5](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L5)) Extends ------- * [PIXI.Texture](pixi.texture) Public Properties ----------------- ### baseTexture : [PIXI.BaseTexture](pixi.basetexture) The base texture object that this texture uses Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L78)) ### crop :Rectangle This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 69](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L69)) ### frame :Rectangle The framing rectangle of the render texture Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 61](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L61)) ### height : number The height of the render texture Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L45)) ### isTiling : boolean Is this a tiling texture? As used by the likes of a TilingSprite. Inherited From * [PIXI.Texture#isTiling](pixi.texture#isTiling) Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 79](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L79)) ### noFrame : boolean Does this Texture have any frame data assigned to it? Inherited From * [PIXI.Texture#noFrame](pixi.texture#noFrame) Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L28)) ### renderer : [PIXI.CanvasRenderer](pixi.canvasrenderer) | [PIXI.WebGLRenderer](pixi.webglrenderer) The renderer this RenderTexture uses. A RenderTexture can only belong to one renderer at the moment if its webGL. ##### Type * [PIXI.CanvasRenderer](pixi.canvasrenderer) | [PIXI.WebGLRenderer](pixi.webglrenderer) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 99](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L99)) ### requiresReTint : boolean This will let a renderer know that a tinted parent has updated its texture. Inherited From * [PIXI.Texture#requiresReTint](pixi.texture#requiresReTint) Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 95](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L95)) ### requiresUpdate : boolean This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) Inherited From * [PIXI.Texture#requiresUpdate](pixi.texture#requiresUpdate) Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L87)) ### resolution : number The Resolution of the texture. Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 53](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L53)) ### trim :Rectangle The texture trim data. Inherited From * [PIXI.Texture#trim](pixi.texture#trim) Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 63](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L63)) ### valid : boolean Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 125](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L125)) ### width : number The with of the render texture Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L37)) Public Methods -------------- ### clear() Clears the RenderTexture. Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 175](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L175)) ### destroy(destroyBase) Destroys this texture ##### Parameters | Name | Type | Description | | --- | --- | --- | | `destroyBase` | Boolean | Whether to destroy the base texture as well | Inherited From * [PIXI.Texture#destroy](pixi.texture#destroy) Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 165](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L165)) ### getBase64() → {String} Will return a base64 encoded string of this texture. It works by calling RenderTexture.getCanvas and then running toDataURL on that. ##### Returns String - A base64 encoded string of the texture. Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 309](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L309)) ### getCanvas() → {HTMLCanvasElement} Creates a Canvas element, renders this RenderTexture to it and then returns it. ##### Returns HTMLCanvasElement - A Canvas element with the texture rendered on. Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 320](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L320)) ### getImage() → {Image} Will return a HTML Image of the texture ##### Returns Image - Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 296](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L296)) ### resize(width, height, updateBase) Resizes the RenderTexture. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `width` | Number | The width to resize to. | | `height` | Number | The height to resize to. | | `updateBase` | Boolean | Should the baseTexture.width and height values be resized as well? | Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 139](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L139)) ### setFrame(frame) Specifies the region of the baseTexture that this texture will use. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `frame` | Rectangle | The frame of the texture to set it to | Inherited From * [PIXI.Texture#setFrame](pixi.texture#setFrame) Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 178](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L178)) phaser Class: Phaser.Create Class: Phaser.Create ==================== Constructor ----------- ### new Create(game) The Phaser.Create class is a collection of smaller helper methods that allow you to generate game content quickly and easily, without the need for any external files. You can create textures for sprites and in coming releases we'll add dynamic sound effect generation support as well (like sfxr). Access this via `Game.create` (`this.game.create` from within a State object) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | Game reference to the currently running game. | Source code: [core/Create.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js) ([Line 18](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js#L18)) Public Properties ----------------- ### [static] PALETTE\_ARNE : number A 16 color palette by [Arne](http://androidarts.com/palette/16pal.htm) Source code: [core/Create.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js#L58)) ### [static] PALETTE\_C64 : number A 16 color C64 inspired palette. Source code: [core/Create.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js) ([Line 79](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js#L79)) ### [static] PALETTE\_CGA : number A 16 color CGA inspired palette. Source code: [core/Create.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js) ([Line 72](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js#L72)) ### [static] PALETTE\_JAPANESE\_MACHINE : number A 16 color palette inspired by Japanese computers like the MSX. Source code: [core/Create.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js#L86)) ### [static] PALETTE\_JMP : number A 16 color JMP inspired palette. Source code: [core/Create.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js) ([Line 65](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js#L65)) ### bmd : [Phaser.BitmapData](phaser.bitmapdata) The internal BitmapData Create uses to generate textures from. Source code: [core/Create.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js#L28)) ### canvas :HTMLCanvasElement The canvas the BitmapData uses. Source code: [core/Create.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js) ([Line 33](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js#L33)) ### ctx ##### Properties: | Name | Type | Description | | --- | --- | --- | | `context` | CanvasRenderingContext2D | The 2d context of the canvas. | Source code: [core/Create.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js#L38)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Source code: [core/Create.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js) ([Line 23](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js#L23)) ### palettes :array A range of 16 color palettes for use with sprite generation. Source code: [core/Create.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js) ([Line 43](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js#L43)) Public Methods -------------- ### grid(key, width, height, cellWidth, cellHeight, color) → {[PIXI.Texture](pixi.texture)} Creates a grid texture based on the given dimensions. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key used to store this texture in the Phaser Cache. | | `width` | integer | The width of the grid in pixels. | | `height` | integer | The height of the grid in pixels. | | `cellWidth` | integer | The width of the grid cells in pixels. | | `cellHeight` | integer | The height of the grid cells in pixels. | | `color` | string | The color to draw the grid lines in. Should be a Canvas supported color string like `#ff5500` or `rgba(200,50,3,0.5)`. | ##### Returns [PIXI.Texture](pixi.texture) - The newly generated texture. Source code: [core/Create.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js) ([Line 162](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js#L162)) ### texture(key, data, pixelWidth, pixelHeight, palette) → {[PIXI.Texture](pixi.texture)} Generates a new PIXI.Texture from the given data, which can be applied to a Sprite. This allows you to create game graphics quickly and easily, with no external files but that use actual proper images rather than Phaser.Graphics objects, which are expensive to render and limited in scope. Each element of the array is a string holding the pixel color values, as mapped to one of the Phaser.Create PALETTE consts. For example: `var data = [ ' 333 ', ' 777 ', 'E333E', ' 333 ', ' 3 3 ' ];` `game.create.texture('bob', data);` The above will create a new texture called `bob`, which will look like a little man wearing a hat. You can then use it for sprites the same way you use any other texture: `game.add.sprite(0, 0, 'bob');` ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The key used to store this texture in the Phaser Cache. | | `data` | array | | | An array of pixel data. | | `pixelWidth` | integer | <optional> | 8 | The width of each pixel. | | `pixelHeight` | integer | <optional> | 8 | The height of each pixel. | | `palette` | integer | <optional> | 0 | The palette to use when rendering the texture. One of the Phaser.Create.PALETTE consts. | ##### Returns [PIXI.Texture](pixi.texture) - The newly generated texture. Source code: [core/Create.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js) ([Line 90](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Create.js#L90))
programming_docs