3

How would I go about making a special singleton, like None? (I'm new to python.)

I want to be able to do this sort of thing:

def create_mutations(d):
    return [
        Mutation(c, v)
        if v is not CellAction.Delete else
        Mutation(c, isDelete=True)
        for (c, v) in d
        ]

Used like this:

create_mutations({'a': 5, 'b': None, 'c': CellAction.Delete})

This would create a list containing three mutations, meaning "set a to 5, set b to None, and delete c."

The point is that in the definition of create_mutations I cannot use ... if v is not None else ... because then there is no distinction between "set b to None" and "delete b."

I can clarify if the question isn't clear.

Timothy Shields
  • 70,640
  • 17
  • 114
  • 164

3 Answers3

6

You can just instantiate an object somewhere in your module or class like this:

Delete = object()

This is enough for most cases.

Michael
  • 8,624
  • 3
  • 36
  • 54
3

Simply make some object and give it a name. An empty class will do:

class Delete:
    pass

Or, as Michael notes, an object instance.

Whatever object you use should be mutable if you plan to test for it using is; Python has a habit of sharing instances of immutable objects. (For example, all empty tuples are the same object.)

kindall
  • 168,929
  • 32
  • 262
  • 294
  • I've seen a few projects that merge both answers, and have something like `DELETE = Delete()` – Jonathan Vanasco Jul 10 '13 at 20:54
  • @JonathanVanasco What does that accomplish? – endolith Oct 16 '17 at 00:23
  • 1
    With `DELETE = object()`, you must always check `if foo is DELETE`. With `DELETE = Delete()`, you can check using `if isinstance(DELETE, Delete)`. Depending on what you're working with, it may be better to use `isinstance` with a class than `is` with an object. For example, if you're persisting data (pickle, shelf, marshall, etc), `DELETE = object()` will be different on subsequent runs of your program and will not match your persisted data, however testing against a custom `Delete` class will still work. – Jonathan Vanasco Oct 16 '17 at 14:20
1

Well, the simple answer is you can't (well, you could, but that's not what you want to do).

You should probably just use a class here, such as DeleteCell = object() (or, you could have a CellAction class or module with various actions (other classes) inside of it).

Isaac
  • 14,813
  • 8
  • 51
  • 75