Replace package import in a module - python-3.x

I use a module that imports a function as a package import using relative import dot notation:
from .utils import target_func
class ClassINeed:
def function_i_call(self):
return target_func()
I want to import ClassINeed with from classineed import ClassINeed but replace target_func with a function of my own. Problem is, target_func is not part of the class I am importing. Therefore I do not see a way to access it. What would be a way to accomplish this?

On top of from classineed import ClassINeed, also do a import classineed then override the target_func as needed via classineed.target_func = lambda : 'hello!' for example.
P.S. Referring to the class ClassINeed with classineed.ClassINeed might be cleaner if you already have import classineed.

Related

Using a QGraphicsItem in a QGraphicsLayout

I'm trying to use instances of QGraphicsItem such as QGraphicsRectItem in a QGraphicsLayout. My understanding from the example here is that I should define a class that inherits from both QGraphicsRectItem and QGraphicsLayout. If I try to do that then scene.addItem(rect) causes a segmentation fault, but reversing the order of QGraphicsLayoutItem and QGraphicsRectItem in the class definition fixes it. This however leads to the same issue when I try to add an instance of this class to a QGraphicsLayout. Does it only recognize the inheritance from the first class listed? Do I have to use a different approach due to limitations in Python? If so, what would that approach be?
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
class MyRectItem(QGraphicsLayoutItem, QGraphicsRectItem):
pass
app = QApplication([])
rect = MyRectItem()
scene = QGraphicsScene()
scene.addItem(rect)
graphics_view = QGraphicsView(scene)
graphics_view.show()
sys.exit(app.exec_())

How to pass the production variable to Authorize.Net API?

I am working on getting the transactions on Authorize.Net API.
I am using the same code sample and the SDK says that in order to switch to the production environment, I need to set the environment variable on the controller.
The link is here. I am not sure where should I add this line of code
createtransactioncontroller.setenvironment(constants.PRODUCTION)
Rest of the code is the here
Is this the right way to use the controller
import os
import sys
import imp
from datetime import datetime, timedelta
from authorizenet import apicontractsv1
from authorizenet.apicontrollers import getSettledBatchListController
from authorizenet.apicontrollers import createTransactionController
constants = imp.load_source('modulename', 'constants.py')
def get_settled_batch_list():
"""get settled batch list"""
createTransactionController.setenvironment(constants.PRODUCTION)
merchantAuth = apicontractsv1.merchantAuthenticationType()
I had this same error and the way I fixed it was I changed the file constants.py to credentials.py and then I changed the variable to MY_CONSTANTS but you can change them to be credentials if you want.
If it does doesn't work at that point you could try to hard code it instead with createtransactioncontroller.setenvironment('https://api2.authorize.net/xml/v1/request.api')
but if you don't then leave it to be constants.PRODUCTION
createtransactioncontroller = createTransactionController(createtransactionrequest)
createtransactioncontroller.setenvironment(constants.PRODUCTION)
# or createtransactioncontroller.setenvironment('https://api2.authorize.net/xml/v1/request.api')
createtransactioncontroller.execute()
I used a dictionary for my credentials(constants in your case) so mine looks a little different.
import imp
import os
import sys
import importlib
from authorizenet.constants import constants
from authorizenet import apicontractsv1
from authorizenet.apicontrollers import createTransactionController
from .credentials import MY_CONSTANTS
# retrieved from the constants file
merchantAuth = apicontractsv1.merchantAuthenticationType()
merchantAuth.name = MY_CONSTANTS['apiLoginId']
merchantAuth.transactionKey = MY_CONSTANTS['transactionKey']
I hope this helped you.

'spaceship' class is not defined (even though I've imported it?)

I run the main module, which should work correctly. But an error gets returned. 'spaceship' is not defined when I define 's=spaceship(parameters)' why is this I don't get it. I'm using zelle graphics for python. thank you
Functions from main module:
spaceshipGame file
from graphics import *
from spaceshipClass import *
def main():
window=createGraphicsWindow()
runGame(window)
def createGraphicsWindow():
win=GraphWin("Spaceship game",800,800)
return win
def createSpaceship(window,p1,p2,p3,speed,colour):
s=spaceship(window,p1,p2,p3,speed,colour)
return s
def runGame(window):
player=createSpaceship(window,Point(500,500),Point(500,470),Point(520,485),0.5,"red")
player.draw(window)
main()
spaceshipClass file
from spaceshipGame import *
from graphics import *
class spaceship:
def __init__(self,window,p1,p2,p3,speed,colour):
self.p1=p1
self.p2=p2
self.p3=p3
self.speed=speed
self.colour=colour
self.window=window
Never mind, I see the problem. Consult this example for more information:
Simple cross import in python
But the problem is the way you are cross importing, so delete from spaceshipGame import * from spaceshipClass or vise-versa (i.e. delete from spaceshipClass import * from spaceshipGame). You can import individually if you need to like in the example I provided.
There are also many other ways around it if you read the example. One of the easiest would be just merging them in the same file if they need to share a lot of methods.

Case-insensitive getattr

Given a module I want to be able to search for classes in that module with case insensitivity.
For example if I have the following module utils/helpers.py
class UtilityClass:
def __init__(self):
...
In a different script, I want to be able to retrieve the class by its name in a case insensitive way
import utils.helpers as util_helpers
module = getattr(util_helpers, 'utilityclass')
What is the right and most Pythonic way to implement this?
You can override builtins.getattr with a case-insensitive version:
import builtins
import pprint
def igetattr(obj, attr):
for a in dir(obj):
if a.lower() == attr.lower():
return orig_getattr(obj, a)
orig_getattr = builtins.getattr
builtins.getattr = igetattr
print(getattr(pprint, 'prettyprinter'))
This outputs: <class 'pprint.PrettyPrinter'>

Python - how to import class form another python file

i have two files test.py and site.py in c:\newfolder. I want to import siteElements class from site.py to test.py.....I have written
from site import siteElements
siteElements = SiteElements(webdriver)
but its not working.....
ImportError : cannot import name 'siteElements'
You have a mismatch, what you should do is this:
from modulefile import classname
variable_object = classname(something)
Instead, it seems you do:
from modulefile import classname
classname = variable_object(something)
If we assume that you spelled the class correct, your code should read:
from site import siteElements
variable_object_name = siteElements(webdriver)
Alternatively you can do this like this, introducing an alias to the imported class (make sure the alias name is unique):
from site import siteElements as se
variable_object_name = se(webdriver)
You did not post the "site" module, so you need to check that siteElements is indeed the correct name/spelling of your class.

Resources