# Python Bindings

Pythonic API to the notmuch database.

## Creating Objects

Only the `Database` object is meant to be created by the user. All other objects should be created from this initial object. Users should consider their signatures implementation details.

## Errors

All errors occurring due to errors from the underlying notmuch database are subclasses of the `NotmuchError`. Due to memory management it is possible to try and use an object after it has been freed. In this case a `ObjectDestroyedError` will be raised.

## Memory Management

Libnotmuch uses a hierarchical memory allocator, this means all objects have a strict parent-child relationship and when the parent is freed all the children are freed as well. This has some implications for these Python bindings as parent objects need to be kept alive. This is normally shielded entirely from the user however and the Python objects automatically make sure the right references are kept alive. It is however the reason the `BaseObject` exists as it defines the API all Python objects need to implement to work correctly.

## Collections and Containers

Libnotmuch exposes nearly all collections of things as iterators only. In these python bindings they have sometimes been exposed as `collections.abc.Container` instances or subclasses of this like `collections.abc.Set` or `collections.abc.Mapping` etc. This gives a more natural API to work with, e.g. being able to treat tags as sets. However it does mean that the `__contains__()`, `__len__()` and similar methods on these are usually more expensive and essentially O(n) rather than O(1) as you might expect from Python containers.

class notmuch2.AtomicContext(db, ptr_name)

  Context manager for atomic support.

  This supports the notmuch_database_begin_atomic and notmuch_database_end_atomic API calls. The object can not be directly instantiated by the user, only via `Database.atomic`. It does keep a reference to the `Database` instance to keep the C memory alive.

  Raises:

    - XapianError – When this is raised at enter time the atomic section is not active. When it is raised at exit time the atomic section is still active and you may need to try using `force_end()`.

    - ObjectDestroyedError – if used after destroyed.

  abort()

    Abort the transaction.

    Aborting a transaction will not commit any of the changes, but will also implicitly close the database.

  force_end()

    Force ending the atomic section.

    This can only be called once __exit__ has been called. It will attempt to close the atomic section (again). This is useful if the original exit raised an exception and the atomic section is still open. But things are pretty ugly by now.

    Raises:

      - XapianError – If exiting fails, the atomic section is not ended.

      - UnbalancedAtomicError – If the database was currently not in an atomic section.

      - ObjectDestroyedError – if used after destroyed.

class notmuch2.BinString(data, encoding='utf-8', errors='ignore')

  A str subclass with binary data.

  Most data in libnotmuch should be valid ASCII or valid UTF-8. However since it is a C library these are represented as bytestrings instead which means on an API level we can not guarantee that decoding this to UTF-8 will both succeed and be lossless. This string type converts bytes to unicode in a lossy way, but also makes the raw bytes available.

  This object is a normal unicode string for most intents and purposes, but you can get the original bytestring back by calling `bytes()` on it.

  classmethod from_cffi(cdata)

    Create a new string from a CFFI cdata pointer.

class notmuch2.Database(path=None, mode=Mode.READ_ONLY, config=ConfigFile.SEARCH)

  Toplevel access to notmuch.

  A `Database` can be opened read-only or read-write. Modifications are not atomic by default, use `begin_atomic()` for atomic updates. If the underlying database has been modified outside of this class a `XapianError` will be raised and the instance must be closed and a new one created.

  You can use an instance of this class as a context-manager.

  Variables:

    - MODE – The mode a database can be opened with, an enumeration of `READ_ONLY` and `READ_WRITE`

    - SORT – The sort order for search results, `OLDEST_FIRST`, `NEWEST_FIRST`, `MESSAGE_ID` or `UNSORTED`.

    - EXCLUDE – Which messages to exclude from queries, `TRUE`, `FLAG`, `FALSE` or `ALL`. See the query documentation for details.

    - CONFIG – Control loading of config file. Enumeration of `EMPTY` (don’t load a config file), and `SEARCH` (search as in CONFIGURATION)

    - AddedMessage – A namedtuple `(msg, dup)` used by `add()` as return value.

    - STR_MODE_MAP – A map mapping strings to `MODE` items. This is used to implement the `ro` and `rw` string variants.

    - closed – Boolean indicating if the database is closed or still open.

  Parameters:

    - path (str, bytes, os.PathLike or pathlib.Path) – The directory of where the database is stored. If `None` the location will be searched according to DATABASE LOCATION

    - mode (`MODE` or str.) – The mode to open the database in. One of `MODE.READ_ONLY` OR `MODE.READ_WRITE`. For convenience you can also use the strings `ro` for `MODE.READ_ONLY` and `rw` for `MODE.READ_WRITE`.

    - config (`CONFIG.EMPTY`, `CONFIG.SEARCH`, str, bytes, os.PathLike, pathlib.Path) – Where to load the configuration from, if any.

  Raises:

    - KeyError – if an unknown mode string is used.

    - OSError – or subclasses if the configuration file can not be opened.

    - configparser.Error – or subclasses if the configuration file can not be parsed.

    - NotmuchError – or subclasses for other failures.

  class AddedMessage(msg, dup)
    dup

      Alias for field number 1

    msg

      Alias for field number 0

  CONFIG

    alias of `ConfigFile`

  EXCLUDE

    alias of `QueryExclude`

  MODE

    alias of `Mode`

  SORT

    alias of `QuerySortOrder`

  add(filename, *, sync_flags=False, indexopts=None)

    Add a message to the database.

    Add a new message to the notmuch database. The message is referred to by the pathname of the maildir file. If the message ID of the new message already exists in the database, this adds `pathname` to the list of list of files for the existing message.

    Parameters:

      - filename (str, bytes, os.PathLike or pathlib.Path.) – The path of the file containing the message.

      - sync_flags (bool) – Whether to sync the known maildir flags to notmuch tags. See `Message.flags_to_tags()` for details.

      - indexopts (`IndexOptions` or None) – The indexing options, see `default_indexopts()`. Leave as None to use the default options configured in the database.

    Returns:

      A tuple where the first item is the newly inserted messages as a `Message` instance, and the second item is a boolean indicating if the message inserted was a duplicate. This is the namedtuple `AddedMessage(msg, dup)`.

    Return type:

      Database.AddedMessage

    If an exception is raised, no message was added.

    Raises:

      - XapianError – A Xapian exception occurred.

      - FileError – The file referred to by `pathname` could not be opened.

      - FileNotEmailError – The file referred to by `pathname` is not recognised as an email message.

      - ReadOnlyDatabaseError – The database is opened in READ_ONLY mode.

      - UpgradeRequiredError – The database must be upgraded first.

      - ObjectDestroyedError – if used after destroyed.

  property alive

    Whether the object is still alive.

    This indicates whether the object is still alive. The first thing this needs to check is whether the parent object is still alive, if it is not then this object can not be alive either. If the parent is alive then it depends on whether the memory for this object has been freed yet or not.

  atomic()

    Return a context manager to perform atomic operations.

    The returned context manager can be used to perform atomic operations on the database.

    Note

    Unlike a traditional RDBMS transaction this does not imply durability, it only ensures the changes are performed atomically.

    Raises:

      ObjectDestroyedError – if used after destroyed.

  close()

    Close the notmuch database.

    Once closed most operations will fail. This can still be useful however to explicitly close a database which is opened read-write as this would otherwise stop other processes from reading the database while it is open.

    Raises:

      ObjectDestroyedError – if used after destroyed.

  property config

    Return a mutable mapping with the settings stored in this database.

    This returns an mutable dict-like object implementing the collections.abc.MutableMapping Abstract Base Class.

    Return type:

      Config

    Raises:

      ObjectDestroyedError – if used after destroyed.

  count_messages(query, *, omit_excluded=QueryExclude.TRUE, sort=QuerySortOrder.UNSORTED, exclude_tags=None)

    Search the database for messages.

    Returns:

      An iterator over the messages found.

    Return type:

      MessageIter

    Raises:

      ObjectDestroyedError – if used after destroyed.

  classmethod create(path=None, config=ConfigFile.EMPTY)

    Create and open database in READ_WRITE mode.

    This is creates a new notmuch database and returns an opened instance in `MODE.READ_WRITE` mode.

    Parameters:

      - path (str, bytes or os.PathLike) – The directory of where the database is stored. If `None` the location will be read searched by the notmuch library (see notmuch(3)::notmuch_open_with_config).

      - config (`CONFIG.EMPTY`, `CONFIG.SEARCH`, str, bytes, os.PathLike, pathlib.Path) – The pathname of the notmuch configuration file.

    Raises:

      - OSError – or subclasses if the configuration file can not be opened.

      - configparser.Error – or subclasses if the configuration file can not be parsed.

      - NotmuchError – if the config file does not have the database.path setting.

      - FileError – if the database already exists.

    Returns:

      The newly created instance.

  default_indexopts()

    Returns default index options for the database.

    Raises:

      ObjectDestroyedError – if used after destroyed.

    Returns:

      `IndexOptions`.

  static default_path(cfg_path=None)

    Return the path of the user’s default database.

    This reads the user’s configuration file and returns the default path of the database.

    Parameters:

      cfg_path (str, bytes, os.PathLike or pathlib.Path.) – The pathname of the notmuch configuration file. If not specified tries to use the pathname provided in the `NOTMUCH_CONFIG` environment variable and falls back to `~/.notmuch-config`.

    Returns:

      The path of the database, which does not necessarily exists.

    Return type:

      pathlib.Path

    Raises:

      - OSError – or subclasses if the configuration file can not be opened.

      - configparser.Error – or subclasses if the configuration file can not be parsed.

      - NotmuchError – if the config file does not have the database.path setting.

    Deprecated since version 0.35: Use the `config` parameter to `__init__()` or `__create__()` instead.

  find(msgid)

    Return the message matching the given message ID.

    If a message with the given message ID is found a `Message` instance is returned. Otherwise a `LookupError` is raised.

    Parameters:

      msgid (str) – The message ID to look for.

    Returns:

      The message instance.

    Return type:

      Message

    Raises:

      - LookupError – If no message was found.

      - OutOfMemoryError – When there is no memory to allocate the message instance.

      - XapianError – A Xapian exception occurred.

      - ObjectDestroyedError – if used after destroyed.

  get(filename)

    Return the `Message` given a pathname.

    If a message with the given pathname exists in the database return the `Message` instance for the message. Otherwise raise a `LookupError` exception.

    Parameters:

      filename (str, bytes, os.PathLike or pathlib.Path) – The pathname of the message.

    Returns:

      The message instance.

    Return type:

      Message

    Raises:

      - LookupError – If no message was found. This is also a subclass of `KeyError`.

      - OutOfMemoryError – When there is no memory to allocate the message instance.

      - XapianError – A Xapian exception occurred.

      - ObjectDestroyedError – if used after destroyed.

  messages(query, *, omit_excluded=QueryExclude.TRUE, sort=QuerySortOrder.UNSORTED, exclude_tags=None)

    Search the database for messages.

    Returns:

      An iterator over the messages found.

    Return type:

      MessageIter

    Raises:

      - OutOfMemoryError – if no memory is available to allocate the query.

      - ObjectDestroyedError – if used after destroyed.

  property needs_upgrade

    Whether the database should be upgraded.

    If True the database can be upgraded using `upgrade()`. Not doing so may result in some operations raising `UpgradeRequiredError`.

    A read-only database will never be upgradable.

    Raises:

      ObjectDestroyedError – if used after destroyed.

  property path

    The pathname of the notmuch database.

    This is returned as a `pathlib.Path` instance.

    Raises:

      ObjectDestroyedError – if used after destroyed.

  remove(filename)

    Remove a message from the notmuch database.

    Removing a message which is not in the database is just a silent nop-operation.

    Parameters:

      filename (str, bytes, os.PathLike or pathlib.Path.) – The pathname of the file containing the message to be removed.

    Returns:

      True if the message is still in the database. This can happen when multiple files contain the same message ID. The true/false distinction is fairly arbitrary, but think of it as `dup = db.remove_message(name); if dup: ...`.

    Return type:

      bool

    Raises:

      - XapianError – A Xapian exception occurred.

      - ReadOnlyDatabaseError – The database is opened in READ_ONLY mode.

      - UpgradeRequiredError – The database must be upgraded first.

      - ObjectDestroyedError – if used after destroyed.

  reopen(mode=None)

    Reopen an opened notmuch database.

    Parameters:

      mode (`MODE`, str, or None.) – Mode to reopen the database with. When None, the previously active mode is preserved.

    This is useful e.g. for: - switching the mode between read-only and read-write - recovering from OperationInvalidatedError

  revision()

    The currently committed revision in the database.

    Returned as a `(revision, uuid)` namedtuple.

    Raises:

      ObjectDestroyedError – if used after destroyed.

  property tags

    Return an immutable set with all tags used in this database.

    This returns an immutable set-like object implementing the collections.abc.Set Abstract Base Class. Due to the underlying libnotmuch implementation some operations have different performance characteristics then plain set objects. Mainly any lookup operation is O(n) rather then O(1).

    Normal usage treats tags as UTF-8 encoded unicode strings so they are exposed to Python as normal unicode string objects. If you need to handle tags stored in libnotmuch which are not valid unicode do check the `ImmutableTagSet` docs for how to handle this.

    Return type:

      ImmutableTagSet

    Raises:

      ObjectDestroyedError – if used after destroyed.

  upgrade(progress_cb=None)

    Upgrade the database to the latest version.

    Upgrade the database, optionally with a progress callback which should be a callable which will be called with a floating point number in the range of [0.0 .. 1.0].

  property version

    The database format version.

    This is a positive integer.

    Raises:

      ObjectDestroyedError – if used after destroyed.

exception notmuch2.DatabaseExistsError(*args, **kwargs)

class notmuch2.DbRevision(rev, uuid)

  A database revision.

  The database revision number increases monotonically with each commit to the database. Which means user-visible changes can be ordered. This object is sortable with other revisions. It carries the UUID of the database to ensure it is only ever compared with revisions from the same database.

  property rev

    The revision number, a positive integer.

  property uuid

    The UUID of the database, consider this opaque.

exception notmuch2.DuplicateMessageIdError(*args, **kwargs)

exception notmuch2.FileError(*args, **kwargs)

exception notmuch2.FileNotEmailError(*args, **kwargs)

exception notmuch2.IllegalArgumentError(*args, **kwargs)

class notmuch2.ImmutableTagSet(parent, ptr_name, cffi_fn)

  The tags associated with a message thread or whole database.

  Both a thread as well as the database expose the union of all tags in messages associated with them. This exposes these as a `collections.abc.Set` object.

  Note that due to the underlying notmuch API the performance of the implementation is not the same as you would expect from normal sets. E.g. the `__contains__()` and `__len__()` are O(n) rather then O(1).

  Tags are internally stored as bytestrings but normally exposed as unicode strings using the UTF-8 encoding and the ignore decoder error handler. However the `iter()` method can be used to return tags as bytestrings or using a different error handler.

  Note that when doing arithmetic operations on tags, this class will return a plain normal set as it is no longer associated with the message.

  Parameters:

    - parent – the parent object

    - ptr_name – the name of the attribute on the parent which will return the memory pointer. This allows this object to access the pointer via the parent’s descriptor and thus trigger `MemoryPointer`’s memory safety.

    - cffi_fn – the callable CFFI wrapper to retrieve the tags iter. This can be one of notmuch_database_get_all_tags, notmuch_thread_get_tags or notmuch_message_get_tags.

  property alive

    Whether the object is still alive.

    This indicates whether the object is still alive. The first thing this needs to check is whether the parent object is still alive, if it is not then this object can not be alive either. If the parent is alive then it depends on whether the memory for this object has been freed yet or not.

  iter(*, encoding=None, errors='strict')

    Alternate iterator constructor controlling string decoding.

    Tags are stored as bytes in the notmuch database, in Python it’s easier to work with unicode strings and thus is what the normal iterator returns. However this method allows you to specify how you would like to get the tags, defaulting to the bytestring representation instead of unicode strings.

    Parameters:

      - encoding – Which codec to use. The default None does not decode at all and will return the unmodified bytes. Otherwise this is passed on to `str.decode()`.

      - errors – If using a codec, this is the error handler. See `str.decode()` to which this is passed on.

    Raises:

      NullPointerError – When things do not go as planned.

class notmuch2.IndexOptions(parent, opts_p)

  Indexing options.

  This represents the indexing options which can be used to index a message. See `Database.default_indexopts()` to create an instance of this. It can be used e.g. when indexing a new message using `Database.add()`.

  property alive

    Whether the object is still alive.

    This indicates whether the object is still alive. The first thing this needs to check is whether the parent object is still alive, if it is not then this object can not be alive either. If the parent is alive then it depends on whether the memory for this object has been freed yet or not.

  property decrypt_policy

    The decryption policy.

    This is an enum from the `DecryptionPolicy`. See the index.decrypt section in notmuch-config for details on the options. Do not set this to :attr:`DecryptionPolicy.TRUE` without considering the security of your index.

    You can change this policy by assigning a new `DecryptionPolicy` to this property.

    Raises:

      ObjectDestroyedError – if used after destroyed.

    Returns:

      A `DecryptionPolicy` enum instance.

class notmuch2.Message(parent, msg_p, *, db)

  An email message stored in the notmuch database retrieved via a query.

  This should not be directly created, instead it will be returned by calling methods on `Database`. A message keeps a reference to the database object since the database object can not be released while the message is in use.

  Note that this represents a message in the notmuch database. For full email functionality you may want to use the `email` package from Python’s standard library. You could e.g. create this as such:

      notmuch_msg = db.find(msgid)  # or from a query
      parser = email.parser.BytesParser(policy=email.policy.default)
      with notmuch_msg.path.open('rb) as fp:
          email_msg = parser.parse(fp)

  Most commonly the functionality provided by notmuch is sufficient to read email however.

  Messages are considered equal when they have the same message ID. This is how libnotmuch treats messages as well, the `pathnames()` function returns multiple results for duplicates.

  Parameters:

    - parent (NotmuchObject) – The parent object. This is probably one off a `Database`, `Thread` or `Query`.

    - db (Database) – The database instance this message is associated with. This could be the same as the parent.

    - msg_p (<cdata>) – The C pointer to the `notmuch_message_t`.

    - dup (None or bool) – Whether the message was a duplicate on insertion.

  property alive

    Whether the object is still alive.

    This indicates whether the object is still alive. The first thing this needs to check is whether the parent object is still alive, if it is not then this object can not be alive either. If the parent is alive then it depends on whether the memory for this object has been freed yet or not.

  property date

    The message date as an integer.

    The time the message was sent as an integer number of seconds since the epoch, 1 Jan 1970. This is derived from the message’s header, you can get the original header value with `header()`.

    Raises:

      ObjectDestroyedError – if used after destroyed.

  property excluded

    Indicates whether this message was excluded from the query.

    When a message is created from a search, sometimes messages that where excluded by the search query could still be returned by it, e.g. because they are part of a thread matching the query. the `Database.query()` method allows these messages to be flagged, which results in this property being set to True.

    Raises:

      ObjectDestroyedError – if used after destroyed.

  filenames()

    Return an iterator of all files for this message.

    If multiple files contained the same message ID they will all be returned here. The files are returned as instances of `pathlib.Path`.

    Returns:

      Iterator yielding `pathlib.Path` instances.

    Return type:

      iter

    Raises:

      ObjectDestroyedError – if used after destroyed.

  filenamesb()

    Return an iterator of all files for this message.

    This is like `pathnames()` but the files are returned as byte objects instead.

    Returns:

      Iterator yielding `bytes` instances.

    Return type:

      iter

    Raises:

      ObjectDestroyedError – if used after destroyed.

  frozen()

    Context manager to freeze the message state.

    This allows you to perform atomic tag updates:

        with msg.frozen():
            msg.tags.clear()
            msg.tags.add('foo')

    Using This would ensure the message never ends up with no tags applied at all.

    It is safe to nest calls to this context manager.

    Raises:

      - ReadOnlyDatabaseError – if the database is opened in read-only mode.

      - UnbalancedFreezeThawError – if you somehow managed to call __exit__ of this context manager more than once. Why did you do that?

      - ObjectDestroyedError – if used after destroyed.

  property ghost

    Indicates whether this message is a ghost message.

    A ghost message if a message which we know exists, but it has no files or content associated with it. This can happen if it was referenced by some other message. Only the `messageid` and `threadid` attributes are valid for it.

    Raises:

      ObjectDestroyedError – if used after destroyed.

  header(name)

    Return the value of the named header.

    Returns the header from notmuch, some common headers are stored in the database, others are read from the file. Headers are returned with their newlines stripped and collapsed concatenated together if they occur multiple times. You may be better off using the standard library email package’s `email.message_from_file(msg.path.open())` if that is not sufficient for you.

    Parameters:

      header (str or bytes) – Case-insensitive header name to retrieve.

    Returns:

      The header value.

    Return type:

      str

    Raises:

      - LookupError – if the header is not present.

      - NullPointerError – For unexpected notmuch errors.

      - ObjectDestroyedError – if used after destroyed.

  property matched

    Indicates whether this message was matched by the query.

    When a thread is created from a search, some of the messages may not match the original query. This property is set to True for those that do match.

    Raises:

      ObjectDestroyedError – if used after destroyed.

  property messageid

    The message ID as a string.

    Note that notmuch will decode the message ID value and thus strip off the surrounding `<` and `>` characters. This is different from Python’s `email` package behaviour which leaves these characters in place.

    Returns:

      The message ID.

    Return type:

      `BinString`, this is a normal str but calling bytes() on it will return the original bytes used to create it.

    Raises:

      ObjectDestroyedError – if used after destroyed.

  property path

    A pathname of the message as a pathlib.Path instance.

    If multiple files in the database contain the same message ID this will be just one of the files, chosen at random.

    Raises:

      ObjectDestroyedError – if used after destroyed.

  property pathb

    A pathname of the message as a bytes object.

    See `path` for details, this is the same but does return the path as a bytes object which is faster but less convenient.

    Raises:

      ObjectDestroyedError – if used after destroyed.

  property properties

    A map of arbitrary key-value pairs associated with the message.

    Be aware that properties may be used by other extensions to store state in. So delete or modify with care.

    The properties map is somewhat special. It is essentially a multimap-like structure where each key can have multiple values. Therefore accessing a single item using `PropertiesMap.get()` or `PropertiesMap.__getitem__()` will only return you the first item if there are multiple and thus are only recommended if you know there to be only one value.

    Instead the map has an additional `PropertiesMap.getall()` method which can be used to retrieve all properties of a given key. This method also allows iterating of a subset of the keys starting with a given prefix.

  replies()

    Return an iterator of all replies to this message.

    This method will only work if the message was created from a thread. Otherwise it will yield no results.

    Returns:

      An iterator yielding `OwnedMessage` instances.

    Return type:

      MessageIter

  property tags

    The tags associated with the message.

    This behaves as a set. But removing and adding items to the set removes and adds them to the message in the database.

    Raises:

      - ReadOnlyDatabaseError – When manipulating tags on a database opened in read-only mode.

      - ObjectDestroyedError – if used after destroyed.

  property threadid

    The thread ID.

    The thread ID is decoded with the surrogateescape error handler so that it is possible to reconstruct the original thread ID if it is not valid UTF-8.

    Returns:

      The thread ID.

    Return type:

      `BinString`, this is a normal str but calling bytes() on it will return the original bytes used to create it.

    Raises:

      ObjectDestroyedError – if used after destroyed.

class notmuch2.MutableTagSet(parent, ptr_name, cffi_fn)

  The tags associated with a message.

  This is a `collections.abc.MutableSet` object which can be used to manipulate the tags of a message.

  Note that due to the underlying notmuch API the performance of the implementation is not the same as you would expect from normal sets. E.g. the `in` operator and variants are O(n) rather then O(1).

  Tags are bytestrings and calling `iter()` will return an iterator yielding bytestrings. However the `iter()` method can be used to return tags as unicode strings, while all other operations accept either bytestrings or unicode strings. In case unicode strings are used they will be encoded using utf-8 before being passed to notmuch.

  add(tag)

    Add a tag to the message.

    Parameters:

      - tag (str or bytes. A str will be encoded using UTF-8.) – The tag to add.

      - sync_flags – Whether to sync the maildir flags with the new set of tags. Leaving this as None respects the configuration set in the database, while True will always sync and False will never sync.

      - sync_flags – NoneType or bool

    Raises:

      - TypeError – If the tag is not a valid type.

      - TagTooLongError – If the added tag exceeds the maximum length, see `notmuch_cffi.NOTMUCH_TAG_MAX`.

      - ReadOnlyDatabaseError – If the database is opened in read-only mode.

  clear()

    Remove all tags from the message.

    Raises:

      ReadOnlyDatabaseError – If the database is opened in read-only mode.

  discard(tag)

    Remove a tag from the message.

    Parameters:

      - tag (str of bytes. A str will be encoded using UTF-8.) – The tag to remove.

      - sync_flags – Whether to sync the maildir flags with the new set of tags. Leaving this as None respects the configuration set in the database, while True will always sync and False will never sync.

      - sync_flags – NoneType or bool

    Raises:

      - TypeError – If the tag is not a valid type.

      - TagTooLongError – If the tag exceeds the maximum length, see `notmuch_cffi.NOTMUCH_TAG_MAX`.

      - ReadOnlyDatabaseError – If the database is opened in read-only mode.

  from_maildir_flags()

    Update the tags based on the state in the message’s maildir flags.

    This function examines the filenames of ‘message’ for maildir flags, and adds or removes tags on ‘message’ as follows when these flags are present:

    Flag Action if present —- —————– ‘D’ Adds the “draft” tag to the message ‘F’ Adds the “flagged” tag to the message ‘P’ Adds the “passed” tag to the message ‘R’ Adds the “replied” tag to the message ‘S’ Removes the “unread” tag from the message

    For each flag that is not present, the opposite action (add/remove) is performed for the corresponding tags.

    Flags are identified as trailing components of the filename after a sequence of “:2,”.

    If there are multiple filenames associated with this message, the flag is considered present if it appears in one or more filenames. (That is, the flags from the multiple filenames are combined with the logical OR operator.)

  to_maildir_flags()

    Update the message’s maildir flags based on the notmuch tags.

    If the message’s filename is in a maildir directory, that is a directory named `new` or `cur`, and has a valid maildir filename then the flags will be added as such:

    ‘D’ if the message has the “draft” tag ‘F’ if the message has the “flagged” tag ‘P’ if the message has the “passed” tag ‘R’ if the message has the “replied” tag ‘S’ if the message does not have the “unread” tag

    Any existing flags unmentioned in the list above will be preserved in the renaming.

    Also, if this filename is in a directory named “new”, rename it to be within the neighboring directory named “cur”.

    In case there are multiple files associated with the message all filenames will get the same logic applied.

exception notmuch2.NoConfigError(*args, **kwargs)

exception notmuch2.NoDatabaseError(*args, **kwargs)

exception notmuch2.NotmuchError(*args, **kwargs)

  Base exception for errors originating from the notmuch library.

  Usually this will have two attributes:

  Status:

    This is a numeric status code corresponding to the error code in the notmuch library. This is normally fairly meaningless, it can also often be `None`. This exists mostly to easily create new errors from notmuch status codes and should not normally be used by users.

  Message:

    A user-facing message for the error. This can occasionally also be `None`. Usually you’ll want to call `str()` on the error object instead to get a sensible message.

  classmethod exc_type(status)

    Return correct exception type for notmuch status.

class notmuch2.NotmuchObject(parent, *args, **kwargs)

  Base notmuch object syntax.

  This base class exists to define the memory management handling required to use the notmuch library. It is meant as an interface definition rather than a base class, though you can use it as a base class to ensure you don’t forget part of the interface. It only concerns you if you are implementing this package itself rather then using it.

  libnotmuch uses a hierarchical memory allocator, where freeing the memory of a parent object also frees the memory of all child objects. To make this work seamlessly in Python this package keeps references to parent objects which makes them stay alive correctly under normal circumstances. When an object finally gets deleted the `__del__()` method will be called to free the memory.

  However during some peculiar situations, e.g. interpreter shutdown, it is possible for the `__del__()` method to have been called, while there are still references to an object. This could result in child objects asking their memory to be freed after the parent has already freed the memory, making things rather unhappy as double frees are not taken lightly in C. To handle this case all objects need to follow the same protocol to destroy themselves, see `destroy()`.

  Once an object has been destroyed trying to use it should raise the `ObjectDestroyedError` exception. For this see also the convenience `MemoryPointer` descriptor in this module which can be used as a pointer to libnotmuch memory.

  abstract property alive

    Whether the object is still alive.

    This indicates whether the object is still alive. The first thing this needs to check is whether the parent object is still alive, if it is not then this object can not be alive either. If the parent is alive then it depends on whether the memory for this object has been freed yet or not.

exception notmuch2.NullPointerError(*args, **kwargs)

exception notmuch2.ObjectDestroyedError(*args, **kwargs)

  The object has already been destroyed and it’s memory freed.

  This occurs when `destroy()` has been called on the object but you still happen to have access to the object. This should not normally occur since you should never call `destroy()` by hand.

exception notmuch2.OperationInvalidatedError(*args, **kwargs)

exception notmuch2.OutOfMemoryError(*args, **kwargs)

exception notmuch2.PathError(*args, **kwargs)

exception notmuch2.QuerySyntaxError(*args, **kwargs)

exception notmuch2.ReadOnlyDatabaseError(*args, **kwargs)

exception notmuch2.TagTooLongError(*args, **kwargs)

class notmuch2.TagsIter(parent, tags_p, *, encoding=None, errors='strict')

  Iterator over tags.

  This is only an iterator, not a container so calling `__iter__()` does not return a new, replenished iterator but only itself.

  Parameters:

    - parent – The parent object to keep alive.

    - tags_p – The CFFI pointer to the C-level tags iterator.

    - encoding – Which codec to use. The default None does not decode at all and will return the unmodified bytes. Otherwise this is passed on to `str.decode()`.

    - errors – If using a codec, this is the error handler. See `str.decode()` to which this is passed on.

  Raises:

    ObjectDestroyedError – if used after destroyed.

  property alive

    Whether the object is still alive.

    This indicates whether the object is still alive. The first thing this needs to check is whether the parent object is still alive, if it is not then this object can not be alive either. If the parent is alive then it depends on whether the memory for this object has been freed yet or not.

class notmuch2.Thread(parent, thread_p, *, db)
  property alive

    Whether the object is still alive.

    This indicates whether the object is still alive. The first thing this needs to check is whether the parent object is still alive, if it is not then this object can not be alive either. If the parent is alive then it depends on whether the memory for this object has been freed yet or not.

  property authors

    A comma-separated string of all authors in the thread.

    Authors of messages which matched the query the thread was retrieved from will be at the head of the string, ordered by date of their messages. Following this will be the authors of the other messages in the thread, also ordered by date of their messages. Both groups of authors are separated by the `|` character.

    Returns:

      The stringified list of authors.

    Return type:

      BinString

    Raises:

      ObjectDestroyedError – if used after destroyed.

  property first

    Return the date of the oldest message in the thread.

    The time the first message was sent as an integer number of seconds since the epoch, 1 Jan 1970.

    Raises:

      ObjectDestroyedError – if used after destroyed.

  property last

    Return the date of the newest message in the thread.

    The time the last message was sent as an integer number of seconds since the epoch, 1 Jan 1970.

    Raises:

      ObjectDestroyedError – if used after destroyed.

  property matched

    The number of messages in this thread which matched the query.

    Of the messages in the thread this gives the count of messages which did directly match the search query which this thread originates from.

    Raises:

      ObjectDestroyedError – if used after destroyed.

  property subject

    The subject of the thread, taken from the first message.

    The thread’s subject is taken to be the subject of the first message according to query sort order.

    Returns:

      The thread’s subject.

    Return type:

      BinString

    Raises:

      ObjectDestroyedError – if used after destroyed.

  property tags

    Return an immutable set with all tags used in this thread.

    This returns an immutable set-like object implementing the collections.abc.Set Abstract Base Class. Due to the underlying libnotmuch implementation some operations have different performance characteristics then plain set objects. Mainly any lookup operation is O(n) rather then O(1).

    Normal usage treats tags as UTF-8 encoded unicode strings so they are exposed to Python as normal unicode string objects. If you need to handle tags stored in libnotmuch which are not valid unicode do check the `ImmutableTagSet` docs for how to handle this.

    Return type:

      ImmutableTagSet

    Raises:

      ObjectDestroyedError – if used after destroyed.

  property threadid

    The thread ID as a `BinString`.

    Raises:

      ObjectDestroyedError – if used after destroyed.

  toplevel()

    Return an iterator of the toplevel messages.

    Returns:

      An iterator yielding `Message` instances.

    Raises:

      ObjectDestroyedError – if used after destroyed.

exception notmuch2.UnbalancedAtomicError(*args, **kwargs)

exception notmuch2.UnbalancedFreezeThawError(*args, **kwargs)

exception notmuch2.UnsupportedOperationError(*args, **kwargs)

exception notmuch2.UpgradeRequiredError(*args, **kwargs)

exception notmuch2.XapianError(*args, **kwargs)