Note that there are some explanatory texts on larger screens.

plurals
  1. POCreating Truly Empty Types in Python
    primarykey
    data
    text
    <p>On a regular basis, I want to create completely empty objects in Python. Basically, I want to have a dict where the keys are attributes. In Python 2.x, I can create an old-style type like this:</p> <pre><code>class Empty: pass </code></pre> <p>This will create a type that only has two attributes (<code>__doc__</code> and <code>__module__</code>). In Python 3.x, everything is a new-style class, so I get 18 attributes.</p> <p>In my current situation, I have a class that allows you to specify types that need monkey patched within a unit test. When the patches are applied, I am creating a type with attributes with the names of each mocked-out type. This is pretty much what my current implementation is doing:</p> <pre><code>class EmptyType: pass ... mocks = EmptyType() for mock_name, mock in patches: setattr(mocks, mock_name, mock) </code></pre> <p>My concern is that should someone be mocking a private member, they might run into naming collisions with the names in the <code>EmptyType</code> object. That's why I'd like to keep as few attributes in the <code>EmptyType</code> as possible. And it is way easier to say <code>mocks.find_users</code> than it is to say <code>mocks["find_users"]</code>, especially when I know the name has to be a valid identifier.</p> <p>Right now, I have provided the ability to give mocks different names, other than what would otherwise be the default. Still, it would be nice to avoid confusing errors in the first place. It is very easy to create <em>almost</em> empty types in JavaScript and I was hoping there was something similar in Python, since I keep finding good uses for them.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload