Python Forum
making a module mimic another module
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
making a module mimic another module
#1
i want to create a module that mimics another module in a special way. in order to do this i need to create functions in my module with names discovered when that other module is imported. the names to be created are different than what the imported module has. the big problem is that locals() is not supposed to be used to add names to the local name space. is there any alternative way to do that? or is globals() the more appropriate way (in my module at the time it gets imported) to add variables dynamically (by name figured out at import time).
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
You can create a new module by using the constructor types.ModuleType()
>>> import os
>>> import types
>>> m = types.ModuleType('OS')
>>> for k in dir(os):
...     setattr(m, k.upper(), getattr(os, k))
... 
>>> m.CHDIR
<built-in function chdir>
>>> import sys
>>> sys.modules[m.__name__] = m # optional, if you want to make it importable
>>> import OS
>>> OS is m
True
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  importing a module given a path to the file Skaperen 8 1,332 Nov-04-2023, 07:03 PM
Last Post: Skaperen
  where module is loaded from Skaperen 1 746 Jul-26-2023, 05:38 AM
Last Post: Gribouillis
  looking fo documentation for module files Skaperen 39 94,733 Aug-09-2022, 07:37 AM
Last Post: Gribouillis
  Mixed types of numeric data in the statistics module stevendaprano 2 1,311 May-23-2022, 02:15 AM
Last Post: stevendaprano
  a module can be found but another cannot Skaperen 7 2,711 Oct-25-2021, 12:16 AM
Last Post: Skaperen
  Eric6 No module named 'serial' BvdP4Py 0 2,714 Jul-30-2021, 08:38 AM
Last Post: BvdP4Py
Lightbulb Feedback needed! Controlled entropy in programs with 'ordered' module grandrew 0 1,423 Jul-27-2021, 01:49 AM
Last Post: grandrew
  PIL module and Python 2.7 under Windows 10 Lad 3 2,185 Jul-06-2021, 07:39 PM
Last Post: Lad
  finding a mismatched triple-quote in a huge module Skaperen 1 1,598 Apr-15-2020, 04:29 AM
Last Post: UGuntupalli
  random module lacks instantiation Skaperen 3 2,317 Dec-03-2019, 02:53 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020