{"id":8451,"library":"pubnub","title":"PubNub Python SDK","description":"The PubNub Python SDK provides real-time messaging, presence, and push services. It enables developers to build interactive applications with features like chat, IoT, and live event streaming. The current stable version is 10.6.2, with active development and frequent releases addressing bug fixes and feature enhancements, typically on a monthly to quarterly cadence.","status":"active","version":"10.6.2","language":"en","source_language":"en","source_url":"https://github.com/pubnub/python","tags":["real-time","messaging","pubsub","chat","iot","websockets"],"install":[{"cmd":"pip install pubnub","lang":"bash","label":"Install latest stable version"}],"dependencies":[{"reason":"Requires Python 3.9 or newer.","package":"python","optional":false}],"imports":[{"symbol":"PubNub","correct":"from pubnub.pubnub import PubNub"},{"symbol":"PNConfiguration","correct":"from pubnub.pnconfiguration import PNConfiguration"},{"symbol":"SubscribeCallback","correct":"from pubnub.callbacks import SubscribeCallback"},{"symbol":"PNStatusCategory","correct":"from pubnub.enums import PNStatusCategory"}],"quickstart":{"code":"import os\nimport time\nfrom pubnub.pubnub import PubNub\nfrom pubnub.pnconfiguration import PNConfiguration\nfrom pubnub.callbacks import SubscribeCallback\nfrom pubnub.enums import PNStatusCategory\n\n# Replace with your actual publish and subscribe keys\npublish_key = os.environ.get('PUBNUB_PUBLISH_KEY', 'demo')\nsubscribe_key = os.environ.get('PUBNUB_SUBSCRIBE_KEY', 'demo')\n\nif publish_key == 'demo' or subscribe_key == 'demo':\n    print(\"WARNING: Using demo keys. Replace with your own PubNub keys for production.\")\n\npnconfig = PNConfiguration()\npnconfig.publish_key = publish_key\npnconfig.subscribe_key = subscribe_key\npnconfig.uuid = \"my_unique_uuid_py\"\n\npnub = PubNub(pnconfig)\n\nclass MySubscribeCallback(SubscribeCallback):\n    def presence(self, pubnub, presence):\n        print(f\"PRESENCE: {presence.event}\")\n\n    def status(self, pubnub, status):\n        if status.category == PNStatusCategory.PNUnexpectedDisconnectCategory:\n            print(\"Disconnected.\")\n        elif status.category == PNStatusCategory.PNConnectedCategory:\n            print(\"Connected to PubNub.\")\n        elif status.category == PNStatusCategory.PNReconnectedCategory:\n            print(\"Reconnected to PubNub.\")\n        else:\n            print(f\"STATUS: {status.category}\")\n\n    def message(self, pubnub, message):\n        print(f\"MESSAGE: {message.message} from {message.channel}\")\n\npnub.add_listener(MySubscribeCallback())\npnub.subscribe().channels('my_channel').with_presence().execute()\n\ntry:\n    print(\"Publishing 'hello world' in 5 seconds...\")\n    time.sleep(5)\n    pubnub.publish().channel('my_channel').message({'text': 'hello world', 'timestamp': time.time()}).sync()\n    print(\"Published 'hello world'. Staying subscribed for 10 seconds.\")\n    time.sleep(10)\nfinally:\n    pubnub.unsubscribe().channels('my_channel').execute()\n    pubnub.stop()\n    print(\"Unsubscribed and stopped PubNub client.\")\n","lang":"python","description":"This quickstart initializes the PubNub client, subscribes to a channel, and publishes a message. It demonstrates setting up `PNConfiguration`, attaching a `SubscribeCallback` for handling messages, status, and presence events, and performing basic publish/subscribe operations. Remember to replace demo keys with your own."},"warnings":[{"fix":"Update push notification configurations to use FCM. Refer to PubNub's push notification documentation for the new setup.","message":"FCM (Firebase Cloud Messaging) is now the supported push type, replacing GCM (Google Cloud Messaging) and MPNS (Microsoft Push Notification Service), which are deprecated and removed. Applications relying on GCM/MPNS for push notifications must migrate to FCM.","severity":"breaking","affected_versions":"10.5.0+"},{"fix":"Upgrade to PubNub Python SDK v10.6.1 or later. Ensure all messages published are JSON-serializable (e.g., dicts, lists, strings, numbers, booleans, None). Implement proper error handling for publish operations to catch serialization exceptions.","message":"Publishing non-JSON-serializable objects (e.g., custom Python classes, sets) prior to v10.6.1 could silently fail without raising an explicit error, leading to messages not being delivered or malformed.","severity":"gotcha","affected_versions":"<10.6.1"},{"fix":"Upgrade to PubNub Python SDK v10.6.2 or later. The fix ensures `PubNubAsyncioException` always carries a valid `PNStatus` object with error details.","message":"In asynchronous contexts (e.g., asyncio), `PubNubAsyncioException` might return without valid `PNStatus` or `error_data`, leading to `AttributeError` when trying to access these properties during error handling.","severity":"gotcha","affected_versions":"<10.6.2"},{"fix":"Always consult the official PubNub Python SDK migration guide when upgrading between major versions. Update import paths, client initialization, and method calls as per the new API specification.","message":"Major version changes (e.g., v4 to v7, v7 to v9/v10) often involve significant API refactoring, especially around asynchronous operations and listener patterns. Direct upgrades across major versions without consulting migration guides are likely to break existing code.","severity":"breaking","affected_versions":"All major version upgrades"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Before publishing, ensure your message data is JSON-serializable. Convert custom objects to dictionaries or lists using a custom serializer, or pass only basic Python types (strings, numbers, dicts, lists, booleans, None).","cause":"Attempting to publish a Python object that cannot be directly converted to JSON (e.g., a custom class instance, a set) without explicit serialization.","error":"TypeError: Object of type <YourCustomClass> is not JSON serializable"},{"fix":"Upgrade your PubNub Python SDK to version 10.6.2 or newer. This version includes fixes to ensure `PubNubAsyncioException` always contains valid error data.","cause":"This typically occurs in older versions (<10.6.2) when a `PubNubAsyncioException` is raised but the underlying `PNStatus` or `error_data` was not properly set, leading to attempts to access attributes on a `None` object.","error":"AttributeError: 'NoneType' object has no attribute 'error_data'"},{"fix":"Wait for a successful `PNConnectedCategory` status in your `SubscribeCallback` before performing publish or other interactive operations. For critical actions, consider using the `pnub.subscribe().sync()` or waiting for the connection status to change.","cause":"This error occurs if you try to perform operations like `publish` or `signal` before the client has successfully established a subscription connection. The client needs to connect and be ready to send/receive.","error":"PubNubException: Not subscribed."}]}