2

So I have written this module:

plaform.py

from enum import IntFlag

class PlatformFlag(IntFlag):
    LINUX = 1,
    MACOSX = 2,
    WINDOWS = 3
globals().update(PlatformFlag.__members__)

And I am trying to use it this way:

import platform

if __name__ == '__main__':
    if platform.WINDOWS:
        print("This is Windows!")

However, I get:

"Exception has occurred: AttributeError module 'platform' has no attribute 'WINDOWS'"

This works:

import platform

if __name__ == '__main__':
    if platform.PlatformFlag.WINDOWS:
        print("This is Windows!")

However, this is NOT the desired way of doing it. I am thinking about the re.py in cPython. They way you can invoke this e.g. re.compile(pattern, flags=re.M). However, for some reason unknown to me, the globals().upate() doesn't seem to do the trick, or I am missing something here.

Re.py:

https://github.com/python/cpython/blob/master/Lib/re.py

EDIT: This deserves credit, https://repl.it/@JoranBeasley/IntentionalPastStrategies

John Smith
  • 465
  • 4
  • 15
  • 38

1 Answers1

3

The problem you have comes from naming, as there is a builtin module called platform.

https://docs.python.org/3.7/library/platform.html

Running your code with another name like platform123.py works. However the functionality to determine which OS is running is not part of your code and as such does not work :)

The way RE works is by taking the flags as input to the functions. The globals().update(xx.__members__) only makes the members of the classes available in the global namespace so you can use platform.WINDOWS instead of platform.PlatformFlag.WINDOWS.

SimonF
  • 1,855
  • 10
  • 23
  • @SimonF, thanks for the update! But I keep getting: Module 'p' has no 'WINDOWS' memberpylint(E1101), why do I get this? – John Smith Dec 28 '18 at 07:17
  • 1
    @JohnSmith pylint probable doesn't realise that you change the global namespace dynamically. However the code runs and behaves as expected. – SimonF Dec 28 '18 at 07:20
  • @SimonF, Yes, it does indeed work! Thanks a lot for clarifying this to me. – John Smith Dec 28 '18 at 07:22
  • 1
    @JohnSmith No problem! To see the members of an object you can use print(dir(p)) – SimonF Dec 28 '18 at 07:24