w3resource

Python: Check if a given value is compiled code, module


4. Compiled Code and Module Checker

Write a Python program to check if a given value is compiled code or not. Also check if a given value is a module or not. Use types.CodeType, types.ModuleType()

Sample Solution:

Python Code:

import types
print("Check if a given value is compiled code:")
code = compile("print('Hello')", "sample", "exec")
print(isinstance(code, types.CodeType))
print(isinstance("print(abs(-111))", types.CodeType))
print("\nCheck if a given value is a module:")
print(isinstance(types, types.ModuleType))

Sample Output:

Check if a given value is compiled code:
True
False

Check if a given value is a module:
True

Flowchart:

Flowchart: Check if a given value is compiled code, module.

For more Practice: Solve these Related Problems:

  • Write a Python program that compiles a string of code using compile(), then checks if the resulting object is of type types.CodeType and prints the result.
  • Write a Python script to import a standard library module and verify that the imported object is of type types.ModuleType.
  • Write a Python function that takes a code snippet as a string, compiles it, and returns a tuple indicating whether the result is compiled code (using types.CodeType) and whether a given variable is a module (using types.ModuleType).
  • Write a Python program to examine a lambda function’s __code__ attribute and compare it against types.CodeType, and then check a module’s type against types.ModuleType, printing both outcomes.

Go to:


Previous: Write a Python program to check if a given function is a generator or not.
Next: Python module Exercises Home.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.