1

I have a Lego mindstorms 51515 and like to program it with python.

There are some default image in the module I'd like to loop over and use.

import hub
images = dir(hub.Image)
print(images)

Output:

['__class__', '__name__', '__bases__', '__dict__', 'ALL_ARROWS', 'ALL_CLOCKS', 'ANGRY', 'ARROW_E', 'ARROW_N', 'ARROW_NE', 'ARROW_NW', 'ARROW_S', 'ARROW_SE', 'ARROW_SW', 'ARROW_W', 'ASLEEP', 'BUTTERFLY', 'CHESSBOARD', 'CLOCK1', 'CLOCK10', 'CLOCK11', 'CLOCK12', 'CLOCK2', 'CLOCK3', 'CLOCK4', 'CLOCK5', 'CLOCK6', 'CLOCK7', 'CLOCK8', 'CLOCK9', 'CONFUSED', 'COW', 'DIAMOND', 'DIAMOND_SMALL', 'DUCK', 'FABULOUS', 'GHOST', 'GIRAFFE', 'GO_DOWN', 'GO_LEFT', 'GO_RIGHT', 'GO_UP', 'HAPPY', 'HEART', 'HEART_SMALL', 'HOUSE', 'MEH', 'MUSIC_CROTCHET', 'MUSIC_QUAVER', 'MUSIC_QUAVERS', 'NO', 'PACMAN', 'PITCHFORK', 'RABBIT', 'ROLLERSKATE', 'SAD', 'SILLY', 'SKULL', 'SMILE', 'SNAKE', 'SQUARE', 'SQUARE_SMALL', 'STICKFIGURE', 'SURPRISED', 'SWORD', 'TARGET', 'TORTOISE', 'TRIANGLE', 'TRIANGLE_LEFT', 'TSHIRT', 'UMBRELLA', 'XMAS', 'YES', 'get_pixel', 'height', 'set_pixel', 'shift_down', 'shift_left', 'shift_right', 'shift_up', 'width']

All the full names that have only upper case letter should be constants I would like to loop over.

How to do this?

for dynamic_image in images:
    if not dynamic_image.isupper():
        continue
    var = hub.Image.{dynamic_image} # This is the real question on how to do this
Jeromba6
  • 383
  • 1
  • 2
  • 7

3 Answers3

0

With a dict comprehension to grab all attributes of hub.Image which are upper-case only:

import hub
names = {name: getattr(hub.Image, name, None) 
         for name in dir(hub.Image) if name.isupper()}

That would give a dict of all constants: names and their values. To e.g. print it, use

print(list(var.items())
9769953
  • 10,344
  • 3
  • 26
  • 37
0

You can use filter() and .isupper():

import hub
images = dir(hub.Image)
print(list(filter(lambda x: x.isupper(), names))) # Strings with uppercase letters and underscores only
print(list(filter(lambda x: x.isupper() and x.isalpha(), names))) # Strings with uppercase letters only (no underscores)
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
0

I solved it, and the answer is as folling:

import hub
import time

images = dir(hub.Image)
while True:
    for image in images:
        if image.upper() != image:
            continue
        print(image)
        img = hub.Image.__dict__[image]  # This was what I was looking  for
        hub.display.show(img)
        time.sleep(1)
Jeromba6
  • 383
  • 1
  • 2
  • 7