Python Forum

Full Version: Code completion for namedtupe-based object in PyCharm
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I am defining an Enum-style object as a wrapper for string constants
import time, re, collections
def make_enum(*enum_args, **enum_kwargs):
  _tokenizer = lambda s: re.sub('\W+', '_', s)
  enum_kwargs = {k.upper(): v for k, v in enum_kwargs.items()}

  enum_kwargs.update([(_tokenizer(s).upper(), s) for s in enum_args])
  return collections.namedtuple('_C_{:x}'.format(hash(time.time())), enum_kwargs.keys())(**enum_kwargs)

C = make_enum('true', 'false', sentence='This is long')


My only issue - PyCharm does not recognize the structure of the generated object. Is there some way to force auto-completion for that kind of objects?
I don't know much about pycharm, but it seems like it'd be difficult to have autocompletion for dynamically generated classes, unless it was parsing and running your file as you were typing or something.

I was thinking maybe it could work if you used an annotation to offer a type hint for it, but I can't test it since I don't pycharm.
import time, re, collections
def make_enum(*enum_args, **enum_kwargs):
 _tokenizer = lambda s: re.sub('\W+', '_', s)
 enum_kwargs = {k.upper(): v for k, v in enum_kwargs.items()}

 enum_kwargs.update([(_tokenizer(s).upper(), s) for s in enum_args])
 enum = collections.namedtuple('_C_{:x}'.format(hash(time.time())), enum_kwargs.keys())
 def generate() -> enum:
     return enum(**enum_kwargs)
 return generate

builder = make_enum('true', 'false', sentence='This is long')
C = builder()
print(C)
print(type(C))
@nilamo Thanks, I will give it a try
I don't use pycharm, but you might see if you have better luck with the built-in enum.
(May-01-2017, 07:06 PM)micseydel Wrote: [ -> ]I don't use pycharm, but you might see if you have better luck with the built-in enum.
Built-in enum requires value qualification when used in
  • os.path functions
  • Robot FrameWork
After adding qualifier for the n-th time I decided that it - enum - sucks, and dropped the bloody thing Wall