0

I want to create a namespace whose members are suggested by the IDE just as it works for module variables for example.

argparse.Namespace

This question is about how to create a namespace via argparse.Namespace.

However such a namespace is not assisted by my IDE (PyCharm 2016.1.3). Suppose the following:

module1.py

from argparse import Namespace

namespace = Namespace(var=1)

module2.py

from .module1 import namespace

# No suggestion for `var` by the IDE.
namespace.var

Even when I explicitly assign var to namespace I don't get a suggestion:

# In module1.py
namespace.var = 1

dict

What works are dict key suggestions:

module1.py

namespace = dict(var=1)

module2.py

from .module1 import namespace

# Suggests dict key 'var'.
namespace['var']

However I find using dicts as namespaces makes the code appear less clear.

module variables with name prefix

As module variables are suggested I could simply prefix every variable with the namespace name: namespace_var = 1. However then I cannot simply import one namespace as all variables live in the same scope. Also the naming is not clear, what part refers to the namespace and what to the variable name.

class

Another option is to use a class:

module1.py

class namespace: var = 1

module2.py

from .module1 import namespace

# Suggests `var`.
namespace.var

However if I want my namespaces to be lower case then the class definitions don't conform to the PEP8 naming conventions (about which the IDE will complain). Thus I'm not happy with this solution either. Also class Namespace: var = 1; namespace = Namespace feels too artificial.


Do you have any experiences with other IDEs or do you know of a way how to create namespaces that are assisted by IDEs (specifically PyCharm)?

Community
  • 1
  • 1
a_guest
  • 34,165
  • 12
  • 64
  • 118

1 Answers1

0

I ended up using separate modules for the different namespaces and grouping those modules in a package.

The structure is as follows:

module1/
├── __init__.py
└── namespace.py

__init__.py

import namespace

namespace.py

var = 1

Like this one can import module1 and access module1.namespace.var or from module1 import namespace with namespace.var. That is module1 can be used as it still was a module with similar content.

Additional namespaces can be added as separate modules and made available by importing in __init__.py.

a_guest
  • 34,165
  • 12
  • 64
  • 118